cache.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. # Copyright 2019 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import itertools
  15. import logging
  16. from typing import TYPE_CHECKING, Any, Collection, Iterable, List, Optional, Tuple
  17. from synapse.api.constants import EventTypes
  18. from synapse.replication.tcp.streams import BackfillStream, CachesStream
  19. from synapse.replication.tcp.streams.events import (
  20. EventsStream,
  21. EventsStreamCurrentStateRow,
  22. EventsStreamEventRow,
  23. EventsStreamRow,
  24. )
  25. from synapse.storage._base import SQLBaseStore
  26. from synapse.storage.database import (
  27. DatabasePool,
  28. LoggingDatabaseConnection,
  29. LoggingTransaction,
  30. )
  31. from synapse.storage.engines import PostgresEngine
  32. from synapse.storage.util.id_generators import MultiWriterIdGenerator
  33. from synapse.util.caches.descriptors import CachedFunction
  34. from synapse.util.iterutils import batch_iter
  35. if TYPE_CHECKING:
  36. from synapse.server import HomeServer
  37. logger = logging.getLogger(__name__)
  38. # This is a special cache name we use to batch multiple invalidations of caches
  39. # based on the current state when notifying workers over replication.
  40. CURRENT_STATE_CACHE_NAME = "cs_cache_fake"
  41. # As above, but for invalidating event caches on history deletion
  42. PURGE_HISTORY_CACHE_NAME = "ph_cache_fake"
  43. # As above, but for invalidating room caches on room deletion
  44. DELETE_ROOM_CACHE_NAME = "dr_cache_fake"
  45. class CacheInvalidationWorkerStore(SQLBaseStore):
  46. def __init__(
  47. self,
  48. database: DatabasePool,
  49. db_conn: LoggingDatabaseConnection,
  50. hs: "HomeServer",
  51. ):
  52. super().__init__(database, db_conn, hs)
  53. self._instance_name = hs.get_instance_name()
  54. self.db_pool.updates.register_background_index_update(
  55. update_name="cache_invalidation_index_by_instance",
  56. index_name="cache_invalidation_stream_by_instance_instance_index",
  57. table="cache_invalidation_stream_by_instance",
  58. columns=("instance_name", "stream_id"),
  59. psql_only=True, # The table is only on postgres DBs.
  60. )
  61. self._cache_id_gen: Optional[MultiWriterIdGenerator]
  62. if isinstance(self.database_engine, PostgresEngine):
  63. # We set the `writers` to an empty list here as we don't care about
  64. # missing updates over restarts, as we'll not have anything in our
  65. # caches to invalidate. (This reduces the amount of writes to the DB
  66. # that happen).
  67. self._cache_id_gen = MultiWriterIdGenerator(
  68. db_conn,
  69. database,
  70. notifier=hs.get_replication_notifier(),
  71. stream_name="caches",
  72. instance_name=hs.get_instance_name(),
  73. tables=[
  74. (
  75. "cache_invalidation_stream_by_instance",
  76. "instance_name",
  77. "stream_id",
  78. )
  79. ],
  80. sequence_name="cache_invalidation_stream_seq",
  81. writers=[],
  82. )
  83. else:
  84. self._cache_id_gen = None
  85. async def get_all_updated_caches(
  86. self, instance_name: str, last_id: int, current_id: int, limit: int
  87. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  88. """Get updates for caches replication stream.
  89. Args:
  90. instance_name: The writer we want to fetch updates from. Unused
  91. here since there is only ever one writer.
  92. last_id: The token to fetch updates from. Exclusive.
  93. current_id: The token to fetch updates up to. Inclusive.
  94. limit: The requested limit for the number of rows to return. The
  95. function may return more or fewer rows.
  96. Returns:
  97. A tuple consisting of: the updates, a token to use to fetch
  98. subsequent updates, and whether we returned fewer rows than exists
  99. between the requested tokens due to the limit.
  100. The token returned can be used in a subsequent call to this
  101. function to get further updatees.
  102. The updates are a list of 2-tuples of stream ID and the row data
  103. """
  104. if last_id == current_id:
  105. return [], current_id, False
  106. def get_all_updated_caches_txn(
  107. txn: LoggingTransaction,
  108. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  109. # We purposefully don't bound by the current token, as we want to
  110. # send across cache invalidations as quickly as possible. Cache
  111. # invalidations are idempotent, so duplicates are fine.
  112. sql = """
  113. SELECT stream_id, cache_func, keys, invalidation_ts
  114. FROM cache_invalidation_stream_by_instance
  115. WHERE stream_id > ? AND instance_name = ?
  116. ORDER BY stream_id ASC
  117. LIMIT ?
  118. """
  119. txn.execute(sql, (last_id, instance_name, limit))
  120. updates = [(row[0], row[1:]) for row in txn]
  121. limited = False
  122. upto_token = current_id
  123. if len(updates) >= limit:
  124. upto_token = updates[-1][0]
  125. limited = True
  126. return updates, upto_token, limited
  127. return await self.db_pool.runInteraction(
  128. "get_all_updated_caches", get_all_updated_caches_txn
  129. )
  130. def process_replication_rows(
  131. self, stream_name: str, instance_name: str, token: int, rows: Iterable[Any]
  132. ) -> None:
  133. if stream_name == EventsStream.NAME:
  134. for row in rows:
  135. self._process_event_stream_row(token, row)
  136. elif stream_name == BackfillStream.NAME:
  137. for row in rows:
  138. self._invalidate_caches_for_event(
  139. -token,
  140. row.event_id,
  141. row.room_id,
  142. row.type,
  143. row.state_key,
  144. row.redacts,
  145. row.relates_to,
  146. backfilled=True,
  147. )
  148. elif stream_name == CachesStream.NAME:
  149. for row in rows:
  150. if row.cache_func == CURRENT_STATE_CACHE_NAME:
  151. if row.keys is None:
  152. raise Exception(
  153. "Can't send an 'invalidate all' for current state cache"
  154. )
  155. room_id = row.keys[0]
  156. members_changed = set(row.keys[1:])
  157. self._invalidate_state_caches(room_id, members_changed)
  158. elif row.cache_func == PURGE_HISTORY_CACHE_NAME:
  159. if row.keys is None:
  160. raise Exception(
  161. "Can't send an 'invalidate all' for 'purge history' cache"
  162. )
  163. room_id = row.keys[0]
  164. self._invalidate_caches_for_room_events(room_id)
  165. elif row.cache_func == DELETE_ROOM_CACHE_NAME:
  166. if row.keys is None:
  167. raise Exception(
  168. "Can't send an 'invalidate all' for 'delete room' cache"
  169. )
  170. room_id = row.keys[0]
  171. self._invalidate_caches_for_room_events(room_id)
  172. self._invalidate_caches_for_room(room_id)
  173. else:
  174. self._attempt_to_invalidate_cache(row.cache_func, row.keys)
  175. super().process_replication_rows(stream_name, instance_name, token, rows)
  176. def process_replication_position(
  177. self, stream_name: str, instance_name: str, token: int
  178. ) -> None:
  179. if stream_name == CachesStream.NAME:
  180. if self._cache_id_gen:
  181. self._cache_id_gen.advance(instance_name, token)
  182. super().process_replication_position(stream_name, instance_name, token)
  183. def _process_event_stream_row(self, token: int, row: EventsStreamRow) -> None:
  184. data = row.data
  185. if row.type == EventsStreamEventRow.TypeId:
  186. assert isinstance(data, EventsStreamEventRow)
  187. self._invalidate_caches_for_event(
  188. token,
  189. data.event_id,
  190. data.room_id,
  191. data.type,
  192. data.state_key,
  193. data.redacts,
  194. data.relates_to,
  195. backfilled=False,
  196. )
  197. elif row.type == EventsStreamCurrentStateRow.TypeId:
  198. assert isinstance(data, EventsStreamCurrentStateRow)
  199. self._curr_state_delta_stream_cache.entity_has_changed(data.room_id, token) # type: ignore[attr-defined]
  200. if data.type == EventTypes.Member:
  201. self.get_rooms_for_user_with_stream_ordering.invalidate( # type: ignore[attr-defined]
  202. (data.state_key,)
  203. )
  204. self.get_rooms_for_user.invalidate((data.state_key,)) # type: ignore[attr-defined]
  205. else:
  206. raise Exception("Unknown events stream row type %s" % (row.type,))
  207. def _invalidate_caches_for_event(
  208. self,
  209. stream_ordering: int,
  210. event_id: str,
  211. room_id: str,
  212. etype: str,
  213. state_key: Optional[str],
  214. redacts: Optional[str],
  215. relates_to: Optional[str],
  216. backfilled: bool,
  217. ) -> None:
  218. # XXX: If you add something to this function make sure you add it to
  219. # `_invalidate_caches_for_room_events` as well.
  220. # This invalidates any local in-memory cached event objects, the original
  221. # process triggering the invalidation is responsible for clearing any external
  222. # cached objects.
  223. self._invalidate_local_get_event_cache(event_id) # type: ignore[attr-defined]
  224. self._attempt_to_invalidate_cache("have_seen_event", (room_id, event_id))
  225. self._attempt_to_invalidate_cache("get_latest_event_ids_in_room", (room_id,))
  226. self._attempt_to_invalidate_cache(
  227. "get_unread_event_push_actions_by_room_for_user", (room_id,)
  228. )
  229. # The `_get_membership_from_event_id` is immutable, except for the
  230. # case where we look up an event *before* persisting it.
  231. self._attempt_to_invalidate_cache("_get_membership_from_event_id", (event_id,))
  232. if not backfilled:
  233. self._events_stream_cache.entity_has_changed(room_id, stream_ordering) # type: ignore[attr-defined]
  234. if redacts:
  235. self._invalidate_local_get_event_cache(redacts) # type: ignore[attr-defined]
  236. # Caches which might leak edits must be invalidated for the event being
  237. # redacted.
  238. self._attempt_to_invalidate_cache("get_relations_for_event", (redacts,))
  239. self._attempt_to_invalidate_cache("get_applicable_edit", (redacts,))
  240. self._attempt_to_invalidate_cache("get_thread_id", (redacts,))
  241. self._attempt_to_invalidate_cache("get_thread_id_for_receipts", (redacts,))
  242. if etype == EventTypes.Member:
  243. self._membership_stream_cache.entity_has_changed(state_key, stream_ordering) # type: ignore[attr-defined]
  244. self._attempt_to_invalidate_cache(
  245. "get_invited_rooms_for_local_user", (state_key,)
  246. )
  247. self._attempt_to_invalidate_cache(
  248. "get_rooms_for_user_with_stream_ordering", (state_key,)
  249. )
  250. self._attempt_to_invalidate_cache("get_rooms_for_user", (state_key,))
  251. self._attempt_to_invalidate_cache(
  252. "did_forget",
  253. (
  254. state_key,
  255. room_id,
  256. ),
  257. )
  258. self._attempt_to_invalidate_cache(
  259. "get_forgotten_rooms_for_user", (state_key,)
  260. )
  261. if relates_to:
  262. self._attempt_to_invalidate_cache("get_relations_for_event", (relates_to,))
  263. self._attempt_to_invalidate_cache("get_references_for_event", (relates_to,))
  264. self._attempt_to_invalidate_cache("get_applicable_edit", (relates_to,))
  265. self._attempt_to_invalidate_cache("get_thread_summary", (relates_to,))
  266. self._attempt_to_invalidate_cache("get_thread_participated", (relates_to,))
  267. self._attempt_to_invalidate_cache("get_threads", (room_id,))
  268. def _invalidate_caches_for_room_events_and_stream(
  269. self, txn: LoggingTransaction, room_id: str
  270. ) -> None:
  271. """Invalidate caches associated with events in a room, and stream to
  272. replication.
  273. Used when we delete events a room, but don't know which events we've
  274. deleted.
  275. """
  276. self._send_invalidation_to_replication(txn, PURGE_HISTORY_CACHE_NAME, [room_id])
  277. txn.call_after(self._invalidate_caches_for_room_events, room_id)
  278. def _invalidate_caches_for_room_events(self, room_id: str) -> None:
  279. """Invalidate caches associated with events in a room, and stream to
  280. replication.
  281. Used when we delete events in a room, but don't know which events we've
  282. deleted.
  283. """
  284. self._invalidate_local_get_event_cache_all() # type: ignore[attr-defined]
  285. self._attempt_to_invalidate_cache("have_seen_event", (room_id,))
  286. self._attempt_to_invalidate_cache("get_latest_event_ids_in_room", (room_id,))
  287. self._attempt_to_invalidate_cache(
  288. "get_unread_event_push_actions_by_room_for_user", (room_id,)
  289. )
  290. self._attempt_to_invalidate_cache("_get_membership_from_event_id", None)
  291. self._attempt_to_invalidate_cache("get_relations_for_event", None)
  292. self._attempt_to_invalidate_cache("get_applicable_edit", None)
  293. self._attempt_to_invalidate_cache("get_thread_id", None)
  294. self._attempt_to_invalidate_cache("get_thread_id_for_receipts", None)
  295. self._attempt_to_invalidate_cache("get_invited_rooms_for_local_user", None)
  296. self._attempt_to_invalidate_cache(
  297. "get_rooms_for_user_with_stream_ordering", None
  298. )
  299. self._attempt_to_invalidate_cache("get_rooms_for_user", None)
  300. self._attempt_to_invalidate_cache("did_forget", None)
  301. self._attempt_to_invalidate_cache("get_forgotten_rooms_for_user", None)
  302. self._attempt_to_invalidate_cache("get_references_for_event", None)
  303. self._attempt_to_invalidate_cache("get_thread_summary", None)
  304. self._attempt_to_invalidate_cache("get_thread_participated", None)
  305. self._attempt_to_invalidate_cache("get_threads", (room_id,))
  306. self._attempt_to_invalidate_cache("_get_state_group_for_event", None)
  307. self._attempt_to_invalidate_cache("get_event_ordering", None)
  308. self._attempt_to_invalidate_cache("is_partial_state_event", None)
  309. self._attempt_to_invalidate_cache("_get_joined_profile_from_event_id", None)
  310. def _invalidate_caches_for_room_and_stream(
  311. self, txn: LoggingTransaction, room_id: str
  312. ) -> None:
  313. """Invalidate caches associated with rooms, and stream to replication.
  314. Used when we delete rooms.
  315. """
  316. self._send_invalidation_to_replication(txn, DELETE_ROOM_CACHE_NAME, [room_id])
  317. txn.call_after(self._invalidate_caches_for_room, room_id)
  318. def _invalidate_caches_for_room(self, room_id: str) -> None:
  319. """Invalidate caches associated with rooms.
  320. Used when we delete rooms.
  321. """
  322. # If we've deleted the room then we also need to purge all event caches.
  323. self._invalidate_caches_for_room_events(room_id)
  324. self._attempt_to_invalidate_cache("get_account_data_for_room", None)
  325. self._attempt_to_invalidate_cache("get_account_data_for_room_and_type", None)
  326. self._attempt_to_invalidate_cache("get_aliases_for_room", (room_id,))
  327. self._attempt_to_invalidate_cache("get_latest_event_ids_in_room", (room_id,))
  328. self._attempt_to_invalidate_cache("_get_forward_extremeties_for_room", None)
  329. self._attempt_to_invalidate_cache(
  330. "get_unread_event_push_actions_by_room_for_user", (room_id,)
  331. )
  332. self._attempt_to_invalidate_cache(
  333. "_get_linearized_receipts_for_room", (room_id,)
  334. )
  335. self._attempt_to_invalidate_cache("is_room_blocked", (room_id,))
  336. self._attempt_to_invalidate_cache("get_retention_policy_for_room", (room_id,))
  337. self._attempt_to_invalidate_cache(
  338. "_get_partial_state_servers_at_join", (room_id,)
  339. )
  340. self._attempt_to_invalidate_cache("is_partial_state_room", (room_id,))
  341. self._attempt_to_invalidate_cache("get_invited_rooms_for_local_user", None)
  342. self._attempt_to_invalidate_cache(
  343. "get_current_hosts_in_room_ordered", (room_id,)
  344. )
  345. self._attempt_to_invalidate_cache("did_forget", None)
  346. self._attempt_to_invalidate_cache("get_forgotten_rooms_for_user", None)
  347. self._attempt_to_invalidate_cache("_get_membership_from_event_id", None)
  348. self._attempt_to_invalidate_cache("get_room_version_id", (room_id,))
  349. # And delete state caches.
  350. self._invalidate_state_caches_all(room_id)
  351. async def invalidate_cache_and_stream(
  352. self, cache_name: str, keys: Tuple[Any, ...]
  353. ) -> None:
  354. """Invalidates the cache and adds it to the cache stream so other workers
  355. will know to invalidate their caches.
  356. This should only be used to invalidate caches where other workers won't
  357. otherwise have known from other replication streams that the cache should
  358. be invalidated.
  359. """
  360. cache_func = getattr(self, cache_name, None)
  361. if not cache_func:
  362. return
  363. cache_func.invalidate(keys)
  364. await self.send_invalidation_to_replication(
  365. cache_func.__name__,
  366. keys,
  367. )
  368. def _invalidate_cache_and_stream(
  369. self,
  370. txn: LoggingTransaction,
  371. cache_func: CachedFunction,
  372. keys: Tuple[Any, ...],
  373. ) -> None:
  374. """Invalidates the cache and adds it to the cache stream so other workers
  375. will know to invalidate their caches.
  376. This should only be used to invalidate caches where other workers won't
  377. otherwise have known from other replication streams that the cache should
  378. be invalidated.
  379. """
  380. txn.call_after(cache_func.invalidate, keys)
  381. self._send_invalidation_to_replication(txn, cache_func.__name__, keys)
  382. def _invalidate_all_cache_and_stream(
  383. self, txn: LoggingTransaction, cache_func: CachedFunction
  384. ) -> None:
  385. """Invalidates the entire cache and adds it to the cache stream so other workers
  386. will know to invalidate their caches.
  387. """
  388. txn.call_after(cache_func.invalidate_all)
  389. self._send_invalidation_to_replication(txn, cache_func.__name__, None)
  390. def _invalidate_state_caches_and_stream(
  391. self, txn: LoggingTransaction, room_id: str, members_changed: Collection[str]
  392. ) -> None:
  393. """Special case invalidation of caches based on current state.
  394. We special case this so that we can batch the cache invalidations into a
  395. single replication poke.
  396. Args:
  397. txn
  398. room_id: Room where state changed
  399. members_changed: The user_ids of members that have changed
  400. """
  401. txn.call_after(self._invalidate_state_caches, room_id, members_changed)
  402. if members_changed:
  403. # We need to be careful that the size of the `members_changed` list
  404. # isn't so large that it causes problems sending over replication, so we
  405. # send them in chunks.
  406. # Max line length is 16K, and max user ID length is 255, so 50 should
  407. # be safe.
  408. for chunk in batch_iter(members_changed, 50):
  409. keys = itertools.chain([room_id], chunk)
  410. self._send_invalidation_to_replication(
  411. txn, CURRENT_STATE_CACHE_NAME, keys
  412. )
  413. else:
  414. # if no members changed, we still need to invalidate the other caches.
  415. self._send_invalidation_to_replication(
  416. txn, CURRENT_STATE_CACHE_NAME, [room_id]
  417. )
  418. async def send_invalidation_to_replication(
  419. self, cache_name: str, keys: Optional[Collection[Any]]
  420. ) -> None:
  421. await self.db_pool.runInteraction(
  422. "send_invalidation_to_replication",
  423. self._send_invalidation_to_replication,
  424. cache_name,
  425. keys,
  426. )
  427. def _send_invalidation_to_replication(
  428. self, txn: LoggingTransaction, cache_name: str, keys: Optional[Iterable[Any]]
  429. ) -> None:
  430. """Notifies replication that given cache has been invalidated.
  431. Note that this does *not* invalidate the cache locally.
  432. Args:
  433. txn
  434. cache_name
  435. keys: Entry to invalidate. If None will invalidate all.
  436. """
  437. if cache_name == CURRENT_STATE_CACHE_NAME and keys is None:
  438. raise Exception(
  439. "Can't stream invalidate all with magic current state cache"
  440. )
  441. if cache_name == PURGE_HISTORY_CACHE_NAME and keys is None:
  442. raise Exception(
  443. "Can't stream invalidate all with magic purge history cache"
  444. )
  445. if cache_name == DELETE_ROOM_CACHE_NAME and keys is None:
  446. raise Exception("Can't stream invalidate all with magic delete room cache")
  447. if isinstance(self.database_engine, PostgresEngine):
  448. assert self._cache_id_gen is not None
  449. # get_next() returns a context manager which is designed to wrap
  450. # the transaction. However, we want to only get an ID when we want
  451. # to use it, here, so we need to call __enter__ manually, and have
  452. # __exit__ called after the transaction finishes.
  453. stream_id = self._cache_id_gen.get_next_txn(txn)
  454. txn.call_after(self.hs.get_notifier().on_new_replication_data)
  455. if keys is not None:
  456. keys = list(keys)
  457. self.db_pool.simple_insert_txn(
  458. txn,
  459. table="cache_invalidation_stream_by_instance",
  460. values={
  461. "stream_id": stream_id,
  462. "instance_name": self._instance_name,
  463. "cache_func": cache_name,
  464. "keys": keys,
  465. "invalidation_ts": self._clock.time_msec(),
  466. },
  467. )
  468. def get_cache_stream_token_for_writer(self, instance_name: str) -> int:
  469. if self._cache_id_gen:
  470. return self._cache_id_gen.get_current_token_for_writer(instance_name)
  471. else:
  472. return 0