summary refs log tree commit diff
path: root/synapse/util/caches/expiringcache.py
blob: b9ead9cbd5e531b4e998a72c1ed22ba188a2eb35 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from synapse.util.caches import register_cache

from collections import OrderedDict
import logging


logger = logging.getLogger(__name__)


class ExpiringCache(object):
    def __init__(self, cache_name, clock, max_len=0, expiry_ms=0,
                 reset_expiry_on_get=False, iterable=False):
        """
        Args:
            cache_name (str): Name of this cache, used for logging.
            clock (Clock)
            max_len (int): Max size of dict. If the dict grows larger than this
                then the oldest items get automatically evicted. Default is 0,
                which indicates there is no max limit.
            expiry_ms (int): How long before an item is evicted from the cache
                in milliseconds. Default is 0, indicating items never get
                evicted based on time.
            reset_expiry_on_get (bool): If true, will reset the expiry time for
                an item on access. Defaults to False.
            iterable (bool): If true, the size is calculated by summing the
                sizes of all entries, rather than the number of entries.

        """
        self._cache_name = cache_name

        self._clock = clock

        self._max_len = max_len
        self._expiry_ms = expiry_ms

        self._reset_expiry_on_get = reset_expiry_on_get

        self._cache = OrderedDict()

        self.metrics = register_cache(cache_name, self)

        self.iterable = iterable

    def start(self):
        if not self._expiry_ms:
            # Don't bother starting the loop if things never expire
            return

        def f():
            self._prune_cache()

        self._clock.looping_call(f, self._expiry_ms / 2)

    def __setitem__(self, key, value):
        now = self._clock.time_msec()
        self._cache[key] = _CacheEntry(now, value)

        # Evict if there are now too many items
        while self._max_len and len(self) > self._max_len:
            self._cache.popitem(last=False)

    def __getitem__(self, key):
        try:
            entry = self._cache[key]
            self.metrics.inc_hits()
        except KeyError:
            self.metrics.inc_misses()
            raise

        if self._reset_expiry_on_get:
            entry.time = self._clock.time_msec()

        return entry.value

    def get(self, key, default=None):
        try:
            return self[key]
        except KeyError:
            return default

    def _prune_cache(self):
        if not self._expiry_ms:
            # zero expiry time means don't expire. This should never get called
            # since we have this check in start too.
            return
        begin_length = len(self)

        now = self._clock.time_msec()

        keys_to_delete = set()

        for key, cache_entry in self._cache.items():
            if now - cache_entry.time > self._expiry_ms:
                keys_to_delete.add(key)

        for k in keys_to_delete:
            self._cache.pop(k)

        logger.debug(
            "[%s] _prune_cache before: %d, after len: %d",
            self._cache_name, begin_length, len(self)
        )

    def __len__(self):
        if self.iterable:
            return sum(len(value.value) for value in self._cache.itervalues())
        else:
            return len(self._cache)


class _CacheEntry(object):
    def __init__(self, time, value):
        self.time = time
        self.value = value