expiringcache.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from synapse.util.caches import register_cache
  16. from collections import OrderedDict
  17. import logging
  18. logger = logging.getLogger(__name__)
  19. class ExpiringCache(object):
  20. def __init__(self, cache_name, clock, max_len=0, expiry_ms=0,
  21. reset_expiry_on_get=False, iterable=False):
  22. """
  23. Args:
  24. cache_name (str): Name of this cache, used for logging.
  25. clock (Clock)
  26. max_len (int): Max size of dict. If the dict grows larger than this
  27. then the oldest items get automatically evicted. Default is 0,
  28. which indicates there is no max limit.
  29. expiry_ms (int): How long before an item is evicted from the cache
  30. in milliseconds. Default is 0, indicating items never get
  31. evicted based on time.
  32. reset_expiry_on_get (bool): If true, will reset the expiry time for
  33. an item on access. Defaults to False.
  34. iterable (bool): If true, the size is calculated by summing the
  35. sizes of all entries, rather than the number of entries.
  36. """
  37. self._cache_name = cache_name
  38. self._clock = clock
  39. self._max_len = max_len
  40. self._expiry_ms = expiry_ms
  41. self._reset_expiry_on_get = reset_expiry_on_get
  42. self._cache = OrderedDict()
  43. self.iterable = iterable
  44. self._size_estimate = 0
  45. self.metrics = register_cache("expiring", cache_name, self)
  46. def start(self):
  47. if not self._expiry_ms:
  48. # Don't bother starting the loop if things never expire
  49. return
  50. def f():
  51. self._prune_cache()
  52. self._clock.looping_call(f, self._expiry_ms / 2)
  53. def __setitem__(self, key, value):
  54. now = self._clock.time_msec()
  55. self._cache[key] = _CacheEntry(now, value)
  56. if self.iterable:
  57. self._size_estimate += len(value)
  58. # Evict if there are now too many items
  59. while self._max_len and len(self) > self._max_len:
  60. _key, value = self._cache.popitem(last=False)
  61. if self.iterable:
  62. removed_len = len(value.value)
  63. self.metrics.inc_evictions(removed_len)
  64. self._size_estimate -= removed_len
  65. else:
  66. self.metrics.inc_evictions()
  67. def __getitem__(self, key):
  68. try:
  69. entry = self._cache[key]
  70. self.metrics.inc_hits()
  71. except KeyError:
  72. self.metrics.inc_misses()
  73. raise
  74. if self._reset_expiry_on_get:
  75. entry.time = self._clock.time_msec()
  76. return entry.value
  77. def __contains__(self, key):
  78. return key in self._cache
  79. def get(self, key, default=None):
  80. try:
  81. return self[key]
  82. except KeyError:
  83. return default
  84. def setdefault(self, key, value):
  85. try:
  86. return self[key]
  87. except KeyError:
  88. self[key] = value
  89. return value
  90. def _prune_cache(self):
  91. if not self._expiry_ms:
  92. # zero expiry time means don't expire. This should never get called
  93. # since we have this check in start too.
  94. return
  95. begin_length = len(self)
  96. now = self._clock.time_msec()
  97. keys_to_delete = set()
  98. for key, cache_entry in self._cache.items():
  99. if now - cache_entry.time > self._expiry_ms:
  100. keys_to_delete.add(key)
  101. for k in keys_to_delete:
  102. value = self._cache.pop(k)
  103. if self.iterable:
  104. self._size_estimate -= len(value.value)
  105. logger.debug(
  106. "[%s] _prune_cache before: %d, after len: %d",
  107. self._cache_name, begin_length, len(self)
  108. )
  109. def __len__(self):
  110. if self.iterable:
  111. return self._size_estimate
  112. else:
  113. return len(self._cache)
  114. class _CacheEntry(object):
  115. def __init__(self, time, value):
  116. self.time = time
  117. self.value = value