dictionary_cache.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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.lrucache import LruCache
  16. from collections import namedtuple
  17. from . import register_cache
  18. import threading
  19. import logging
  20. logger = logging.getLogger(__name__)
  21. class DictionaryEntry(namedtuple("DictionaryEntry", ("full", "known_absent", "value"))):
  22. """Returned when getting an entry from the cache
  23. Attributes:
  24. full (bool): Whether the cache has the full or dict or just some keys.
  25. If not full then not all requested keys will necessarily be present
  26. in `value`
  27. known_absent (set): Keys that were looked up in the dict and were not
  28. there.
  29. value (dict): The full or partial dict value
  30. """
  31. def __len__(self):
  32. return len(self.value)
  33. class DictionaryCache(object):
  34. """Caches key -> dictionary lookups, supporting caching partial dicts, i.e.
  35. fetching a subset of dictionary keys for a particular key.
  36. """
  37. def __init__(self, name, max_entries=1000):
  38. self.cache = LruCache(max_size=max_entries, size_callback=len)
  39. self.name = name
  40. self.sequence = 0
  41. self.thread = None
  42. # caches_by_name[name] = self.cache
  43. class Sentinel(object):
  44. __slots__ = []
  45. self.sentinel = Sentinel()
  46. self.metrics = register_cache("dictionary", name, self.cache)
  47. def check_thread(self):
  48. expected_thread = self.thread
  49. if expected_thread is None:
  50. self.thread = threading.current_thread()
  51. else:
  52. if expected_thread is not threading.current_thread():
  53. raise ValueError(
  54. "Cache objects can only be accessed from the main thread"
  55. )
  56. def get(self, key, dict_keys=None):
  57. """Fetch an entry out of the cache
  58. Args:
  59. key
  60. dict_key(list): If given a set of keys then return only those keys
  61. that exist in the cache.
  62. Returns:
  63. DictionaryEntry
  64. """
  65. entry = self.cache.get(key, self.sentinel)
  66. if entry is not self.sentinel:
  67. self.metrics.inc_hits()
  68. if dict_keys is None:
  69. return DictionaryEntry(entry.full, entry.known_absent, dict(entry.value))
  70. else:
  71. return DictionaryEntry(entry.full, entry.known_absent, {
  72. k: entry.value[k]
  73. for k in dict_keys
  74. if k in entry.value
  75. })
  76. self.metrics.inc_misses()
  77. return DictionaryEntry(False, set(), {})
  78. def invalidate(self, key):
  79. self.check_thread()
  80. # Increment the sequence number so that any SELECT statements that
  81. # raced with the INSERT don't update the cache (SYN-369)
  82. self.sequence += 1
  83. self.cache.pop(key, None)
  84. def invalidate_all(self):
  85. self.check_thread()
  86. self.sequence += 1
  87. self.cache.clear()
  88. def update(self, sequence, key, value, full=False, known_absent=None):
  89. """Updates the entry in the cache
  90. Args:
  91. sequence
  92. key
  93. value (dict): The value to update the cache with.
  94. full (bool): Whether the given value is the full dict, or just a
  95. partial subset there of. If not full then any existing entries
  96. for the key will be updated.
  97. known_absent (set): Set of keys that we know don't exist in the full
  98. dict.
  99. """
  100. self.check_thread()
  101. if self.sequence == sequence:
  102. # Only update the cache if the caches sequence number matches the
  103. # number that the cache had before the SELECT was started (SYN-369)
  104. if known_absent is None:
  105. known_absent = set()
  106. if full:
  107. self._insert(key, value, known_absent)
  108. else:
  109. self._update_or_insert(key, value, known_absent)
  110. def _update_or_insert(self, key, value, known_absent):
  111. # We pop and reinsert as we need to tell the cache the size may have
  112. # changed
  113. entry = self.cache.pop(key, DictionaryEntry(False, set(), {}))
  114. entry.value.update(value)
  115. entry.known_absent.update(known_absent)
  116. self.cache[key] = entry
  117. def _insert(self, key, value, known_absent):
  118. self.cache[key] = DictionaryEntry(True, known_absent, value)