cache.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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, List, Optional, Tuple
  18. from synapse.api.constants import EventTypes
  19. from synapse.replication.tcp.streams import BackfillStream, CachesStream
  20. from synapse.replication.tcp.streams.events import (
  21. EventsStream,
  22. EventsStreamCurrentStateRow,
  23. EventsStreamEventRow,
  24. )
  25. from synapse.storage._base import SQLBaseStore
  26. from synapse.storage.database import DatabasePool
  27. from synapse.storage.engines import PostgresEngine
  28. from synapse.util.iterutils import batch_iter
  29. logger = logging.getLogger(__name__)
  30. # This is a special cache name we use to batch multiple invalidations of caches
  31. # based on the current state when notifying workers over replication.
  32. CURRENT_STATE_CACHE_NAME = "cs_cache_fake"
  33. class CacheInvalidationWorkerStore(SQLBaseStore):
  34. def __init__(self, database: DatabasePool, db_conn, hs):
  35. super().__init__(database, db_conn, hs)
  36. self._instance_name = hs.get_instance_name()
  37. async def get_all_updated_caches(
  38. self, instance_name: str, last_id: int, current_id: int, limit: int
  39. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  40. """Get updates for caches replication stream.
  41. Args:
  42. instance_name: The writer we want to fetch updates from. Unused
  43. here since there is only ever one writer.
  44. last_id: The token to fetch updates from. Exclusive.
  45. current_id: The token to fetch updates up to. Inclusive.
  46. limit: The requested limit for the number of rows to return. The
  47. function may return more or fewer rows.
  48. Returns:
  49. A tuple consisting of: the updates, a token to use to fetch
  50. subsequent updates, and whether we returned fewer rows than exists
  51. between the requested tokens due to the limit.
  52. The token returned can be used in a subsequent call to this
  53. function to get further updatees.
  54. The updates are a list of 2-tuples of stream ID and the row data
  55. """
  56. if last_id == current_id:
  57. return [], current_id, False
  58. def get_all_updated_caches_txn(txn):
  59. # We purposefully don't bound by the current token, as we want to
  60. # send across cache invalidations as quickly as possible. Cache
  61. # invalidations are idempotent, so duplicates are fine.
  62. sql = """
  63. SELECT stream_id, cache_func, keys, invalidation_ts
  64. FROM cache_invalidation_stream_by_instance
  65. WHERE stream_id > ? AND instance_name = ?
  66. ORDER BY stream_id ASC
  67. LIMIT ?
  68. """
  69. txn.execute(sql, (last_id, instance_name, limit))
  70. updates = [(row[0], row[1:]) for row in txn]
  71. limited = False
  72. upto_token = current_id
  73. if len(updates) >= limit:
  74. upto_token = updates[-1][0]
  75. limited = True
  76. return updates, upto_token, limited
  77. return await self.db_pool.runInteraction(
  78. "get_all_updated_caches", get_all_updated_caches_txn
  79. )
  80. def process_replication_rows(self, stream_name, instance_name, token, rows):
  81. if stream_name == EventsStream.NAME:
  82. for row in rows:
  83. self._process_event_stream_row(token, row)
  84. elif stream_name == BackfillStream.NAME:
  85. for row in rows:
  86. self._invalidate_caches_for_event(
  87. -token,
  88. row.event_id,
  89. row.room_id,
  90. row.type,
  91. row.state_key,
  92. row.redacts,
  93. row.relates_to,
  94. backfilled=True,
  95. )
  96. elif stream_name == CachesStream.NAME:
  97. if self._cache_id_gen:
  98. self._cache_id_gen.advance(instance_name, token)
  99. for row in rows:
  100. if row.cache_func == CURRENT_STATE_CACHE_NAME:
  101. if row.keys is None:
  102. raise Exception(
  103. "Can't send an 'invalidate all' for current state cache"
  104. )
  105. room_id = row.keys[0]
  106. members_changed = set(row.keys[1:])
  107. self._invalidate_state_caches(room_id, members_changed)
  108. else:
  109. self._attempt_to_invalidate_cache(row.cache_func, row.keys)
  110. super().process_replication_rows(stream_name, instance_name, token, rows)
  111. def _process_event_stream_row(self, token, row):
  112. data = row.data
  113. if row.type == EventsStreamEventRow.TypeId:
  114. self._invalidate_caches_for_event(
  115. token,
  116. data.event_id,
  117. data.room_id,
  118. data.type,
  119. data.state_key,
  120. data.redacts,
  121. data.relates_to,
  122. backfilled=False,
  123. )
  124. elif row.type == EventsStreamCurrentStateRow.TypeId:
  125. self._curr_state_delta_stream_cache.entity_has_changed(
  126. row.data.room_id, token
  127. )
  128. if data.type == EventTypes.Member:
  129. self.get_rooms_for_user_with_stream_ordering.invalidate(
  130. (data.state_key,)
  131. )
  132. else:
  133. raise Exception("Unknown events stream row type %s" % (row.type,))
  134. def _invalidate_caches_for_event(
  135. self,
  136. stream_ordering,
  137. event_id,
  138. room_id,
  139. etype,
  140. state_key,
  141. redacts,
  142. relates_to,
  143. backfilled,
  144. ):
  145. self._invalidate_get_event_cache(event_id)
  146. self.get_latest_event_ids_in_room.invalidate((room_id,))
  147. self.get_unread_message_count_for_user.invalidate_many((room_id,))
  148. self.get_unread_event_push_actions_by_room_for_user.invalidate_many((room_id,))
  149. if not backfilled:
  150. self._events_stream_cache.entity_has_changed(room_id, stream_ordering)
  151. if redacts:
  152. self._invalidate_get_event_cache(redacts)
  153. if etype == EventTypes.Member:
  154. self._membership_stream_cache.entity_has_changed(state_key, stream_ordering)
  155. self.get_invited_rooms_for_local_user.invalidate((state_key,))
  156. if relates_to:
  157. self.get_relations_for_event.invalidate_many((relates_to,))
  158. self.get_aggregation_groups_for_event.invalidate_many((relates_to,))
  159. self.get_applicable_edit.invalidate((relates_to,))
  160. async def invalidate_cache_and_stream(self, cache_name: str, keys: Tuple[Any, ...]):
  161. """Invalidates the cache and adds it to the cache stream so slaves
  162. will know to invalidate their caches.
  163. This should only be used to invalidate caches where slaves won't
  164. otherwise know from other replication streams that the cache should
  165. be invalidated.
  166. """
  167. cache_func = getattr(self, cache_name, None)
  168. if not cache_func:
  169. return
  170. cache_func.invalidate(keys)
  171. await self.db_pool.runInteraction(
  172. "invalidate_cache_and_stream",
  173. self._send_invalidation_to_replication,
  174. cache_func.__name__,
  175. keys,
  176. )
  177. def _invalidate_cache_and_stream(self, txn, cache_func, keys):
  178. """Invalidates the cache and adds it to the cache stream so slaves
  179. will know to invalidate their caches.
  180. This should only be used to invalidate caches where slaves won't
  181. otherwise know from other replication streams that the cache should
  182. be invalidated.
  183. """
  184. txn.call_after(cache_func.invalidate, keys)
  185. self._send_invalidation_to_replication(txn, cache_func.__name__, keys)
  186. def _invalidate_all_cache_and_stream(self, txn, cache_func):
  187. """Invalidates the entire cache and adds it to the cache stream so slaves
  188. will know to invalidate their caches.
  189. """
  190. txn.call_after(cache_func.invalidate_all)
  191. self._send_invalidation_to_replication(txn, cache_func.__name__, None)
  192. def _invalidate_state_caches_and_stream(self, txn, room_id, members_changed):
  193. """Special case invalidation of caches based on current state.
  194. We special case this so that we can batch the cache invalidations into a
  195. single replication poke.
  196. Args:
  197. txn
  198. room_id (str): Room where state changed
  199. members_changed (iterable[str]): The user_ids of members that have changed
  200. """
  201. txn.call_after(self._invalidate_state_caches, room_id, members_changed)
  202. if members_changed:
  203. # We need to be careful that the size of the `members_changed` list
  204. # isn't so large that it causes problems sending over replication, so we
  205. # send them in chunks.
  206. # Max line length is 16K, and max user ID length is 255, so 50 should
  207. # be safe.
  208. for chunk in batch_iter(members_changed, 50):
  209. keys = itertools.chain([room_id], chunk)
  210. self._send_invalidation_to_replication(
  211. txn, CURRENT_STATE_CACHE_NAME, keys
  212. )
  213. else:
  214. # if no members changed, we still need to invalidate the other caches.
  215. self._send_invalidation_to_replication(
  216. txn, CURRENT_STATE_CACHE_NAME, [room_id]
  217. )
  218. def _send_invalidation_to_replication(
  219. self, txn, cache_name: str, keys: Optional[Iterable[Any]]
  220. ):
  221. """Notifies replication that given cache has been invalidated.
  222. Note that this does *not* invalidate the cache locally.
  223. Args:
  224. txn
  225. cache_name
  226. keys: Entry to invalidate. If None will invalidate all.
  227. """
  228. if cache_name == CURRENT_STATE_CACHE_NAME and keys is None:
  229. raise Exception(
  230. "Can't stream invalidate all with magic current state cache"
  231. )
  232. if isinstance(self.database_engine, PostgresEngine):
  233. # get_next() returns a context manager which is designed to wrap
  234. # the transaction. However, we want to only get an ID when we want
  235. # to use it, here, so we need to call __enter__ manually, and have
  236. # __exit__ called after the transaction finishes.
  237. stream_id = self._cache_id_gen.get_next_txn(txn)
  238. txn.call_after(self.hs.get_notifier().on_new_replication_data)
  239. if keys is not None:
  240. keys = list(keys)
  241. self.db_pool.simple_insert_txn(
  242. txn,
  243. table="cache_invalidation_stream_by_instance",
  244. values={
  245. "stream_id": stream_id,
  246. "instance_name": self._instance_name,
  247. "cache_func": cache_name,
  248. "keys": keys,
  249. "invalidation_ts": self.clock.time_msec(),
  250. },
  251. )
  252. def get_cache_stream_token(self, instance_name):
  253. if self._cache_id_gen:
  254. return self._cache_id_gen.get_current_token(instance_name)
  255. else:
  256. return 0