cache.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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. import itertools
  16. import logging
  17. from typing import Any, Iterable, Optional, Tuple
  18. from twisted.internet import defer
  19. from synapse.storage._base import SQLBaseStore
  20. from synapse.storage.engines import PostgresEngine
  21. from synapse.util.iterutils import batch_iter
  22. logger = logging.getLogger(__name__)
  23. # This is a special cache name we use to batch multiple invalidations of caches
  24. # based on the current state when notifying workers over replication.
  25. CURRENT_STATE_CACHE_NAME = "cs_cache_fake"
  26. class CacheInvalidationStore(SQLBaseStore):
  27. async def invalidate_cache_and_stream(self, cache_name: str, keys: Tuple[Any, ...]):
  28. """Invalidates the cache and adds it to the cache stream so slaves
  29. will know to invalidate their caches.
  30. This should only be used to invalidate caches where slaves won't
  31. otherwise know from other replication streams that the cache should
  32. be invalidated.
  33. """
  34. cache_func = getattr(self, cache_name, None)
  35. if not cache_func:
  36. return
  37. cache_func.invalidate(keys)
  38. await self.runInteraction(
  39. "invalidate_cache_and_stream",
  40. self._send_invalidation_to_replication,
  41. cache_func.__name__,
  42. keys,
  43. )
  44. def _invalidate_cache_and_stream(self, txn, cache_func, keys):
  45. """Invalidates the cache and adds it to the cache stream so slaves
  46. will know to invalidate their caches.
  47. This should only be used to invalidate caches where slaves won't
  48. otherwise know from other replication streams that the cache should
  49. be invalidated.
  50. """
  51. txn.call_after(cache_func.invalidate, keys)
  52. self._send_invalidation_to_replication(txn, cache_func.__name__, keys)
  53. def _invalidate_all_cache_and_stream(self, txn, cache_func):
  54. """Invalidates the entire cache and adds it to the cache stream so slaves
  55. will know to invalidate their caches.
  56. """
  57. txn.call_after(cache_func.invalidate_all)
  58. self._send_invalidation_to_replication(txn, cache_func.__name__, None)
  59. def _invalidate_state_caches_and_stream(self, txn, room_id, members_changed):
  60. """Special case invalidation of caches based on current state.
  61. We special case this so that we can batch the cache invalidations into a
  62. single replication poke.
  63. Args:
  64. txn
  65. room_id (str): Room where state changed
  66. members_changed (iterable[str]): The user_ids of members that have changed
  67. """
  68. txn.call_after(self._invalidate_state_caches, room_id, members_changed)
  69. if members_changed:
  70. # We need to be careful that the size of the `members_changed` list
  71. # isn't so large that it causes problems sending over replication, so we
  72. # send them in chunks.
  73. # Max line length is 16K, and max user ID length is 255, so 50 should
  74. # be safe.
  75. for chunk in batch_iter(members_changed, 50):
  76. keys = itertools.chain([room_id], chunk)
  77. self._send_invalidation_to_replication(
  78. txn, CURRENT_STATE_CACHE_NAME, keys
  79. )
  80. else:
  81. # if no members changed, we still need to invalidate the other caches.
  82. self._send_invalidation_to_replication(
  83. txn, CURRENT_STATE_CACHE_NAME, [room_id]
  84. )
  85. def _send_invalidation_to_replication(
  86. self, txn, cache_name: str, keys: Optional[Iterable[Any]]
  87. ):
  88. """Notifies replication that given cache has been invalidated.
  89. Note that this does *not* invalidate the cache locally.
  90. Args:
  91. txn
  92. cache_name
  93. keys: Entry to invalidate. If None will invalidate all.
  94. """
  95. if cache_name == CURRENT_STATE_CACHE_NAME and keys is None:
  96. raise Exception(
  97. "Can't stream invalidate all with magic current state cache"
  98. )
  99. if isinstance(self.database_engine, PostgresEngine):
  100. # get_next() returns a context manager which is designed to wrap
  101. # the transaction. However, we want to only get an ID when we want
  102. # to use it, here, so we need to call __enter__ manually, and have
  103. # __exit__ called after the transaction finishes.
  104. ctx = self._cache_id_gen.get_next()
  105. stream_id = ctx.__enter__()
  106. txn.call_on_exception(ctx.__exit__, None, None, None)
  107. txn.call_after(ctx.__exit__, None, None, None)
  108. txn.call_after(self.hs.get_notifier().on_new_replication_data)
  109. if keys is not None:
  110. keys = list(keys)
  111. self.db.simple_insert_txn(
  112. txn,
  113. table="cache_invalidation_stream",
  114. values={
  115. "stream_id": stream_id,
  116. "cache_func": cache_name,
  117. "keys": keys,
  118. "invalidation_ts": self.clock.time_msec(),
  119. },
  120. )
  121. def get_all_updated_caches(self, last_id, current_id, limit):
  122. if last_id == current_id:
  123. return defer.succeed([])
  124. def get_all_updated_caches_txn(txn):
  125. # We purposefully don't bound by the current token, as we want to
  126. # send across cache invalidations as quickly as possible. Cache
  127. # invalidations are idempotent, so duplicates are fine.
  128. sql = (
  129. "SELECT stream_id, cache_func, keys, invalidation_ts"
  130. " FROM cache_invalidation_stream"
  131. " WHERE stream_id > ? ORDER BY stream_id ASC LIMIT ?"
  132. )
  133. txn.execute(sql, (last_id, limit))
  134. return txn.fetchall()
  135. return self.db.runInteraction(
  136. "get_all_updated_caches", get_all_updated_caches_txn
  137. )
  138. def get_cache_stream_token(self):
  139. if self._cache_id_gen:
  140. return self._cache_id_gen.get_current_token()
  141. else:
  142. return 0