You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

399 lines
15 KiB

  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. class CacheInvalidationWorkerStore(SQLBaseStore):
  42. def __init__(
  43. self,
  44. database: DatabasePool,
  45. db_conn: LoggingDatabaseConnection,
  46. hs: "HomeServer",
  47. ):
  48. super().__init__(database, db_conn, hs)
  49. self._instance_name = hs.get_instance_name()
  50. self.db_pool.updates.register_background_index_update(
  51. update_name="cache_invalidation_index_by_instance",
  52. index_name="cache_invalidation_stream_by_instance_instance_index",
  53. table="cache_invalidation_stream_by_instance",
  54. columns=("instance_name", "stream_id"),
  55. psql_only=True, # The table is only on postgres DBs.
  56. )
  57. self._cache_id_gen: Optional[MultiWriterIdGenerator]
  58. if isinstance(self.database_engine, PostgresEngine):
  59. # We set the `writers` to an empty list here as we don't care about
  60. # missing updates over restarts, as we'll not have anything in our
  61. # caches to invalidate. (This reduces the amount of writes to the DB
  62. # that happen).
  63. self._cache_id_gen = MultiWriterIdGenerator(
  64. db_conn,
  65. database,
  66. stream_name="caches",
  67. instance_name=hs.get_instance_name(),
  68. tables=[
  69. (
  70. "cache_invalidation_stream_by_instance",
  71. "instance_name",
  72. "stream_id",
  73. )
  74. ],
  75. sequence_name="cache_invalidation_stream_seq",
  76. writers=[],
  77. )
  78. else:
  79. self._cache_id_gen = None
  80. async def get_all_updated_caches(
  81. self, instance_name: str, last_id: int, current_id: int, limit: int
  82. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  83. """Get updates for caches replication stream.
  84. Args:
  85. instance_name: The writer we want to fetch updates from. Unused
  86. here since there is only ever one writer.
  87. last_id: The token to fetch updates from. Exclusive.
  88. current_id: The token to fetch updates up to. Inclusive.
  89. limit: The requested limit for the number of rows to return. The
  90. function may return more or fewer rows.
  91. Returns:
  92. A tuple consisting of: the updates, a token to use to fetch
  93. subsequent updates, and whether we returned fewer rows than exists
  94. between the requested tokens due to the limit.
  95. The token returned can be used in a subsequent call to this
  96. function to get further updatees.
  97. The updates are a list of 2-tuples of stream ID and the row data
  98. """
  99. if last_id == current_id:
  100. return [], current_id, False
  101. def get_all_updated_caches_txn(
  102. txn: LoggingTransaction,
  103. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  104. # We purposefully don't bound by the current token, as we want to
  105. # send across cache invalidations as quickly as possible. Cache
  106. # invalidations are idempotent, so duplicates are fine.
  107. sql = """
  108. SELECT stream_id, cache_func, keys, invalidation_ts
  109. FROM cache_invalidation_stream_by_instance
  110. WHERE stream_id > ? AND instance_name = ?
  111. ORDER BY stream_id ASC
  112. LIMIT ?
  113. """
  114. txn.execute(sql, (last_id, instance_name, limit))
  115. updates = [(row[0], row[1:]) for row in txn]
  116. limited = False
  117. upto_token = current_id
  118. if len(updates) >= limit:
  119. upto_token = updates[-1][0]
  120. limited = True
  121. return updates, upto_token, limited
  122. return await self.db_pool.runInteraction(
  123. "get_all_updated_caches", get_all_updated_caches_txn
  124. )
  125. def process_replication_rows(
  126. self, stream_name: str, instance_name: str, token: int, rows: Iterable[Any]
  127. ) -> None:
  128. if stream_name == EventsStream.NAME:
  129. for row in rows:
  130. self._process_event_stream_row(token, row)
  131. elif stream_name == BackfillStream.NAME:
  132. for row in rows:
  133. self._invalidate_caches_for_event(
  134. -token,
  135. row.event_id,
  136. row.room_id,
  137. row.type,
  138. row.state_key,
  139. row.redacts,
  140. row.relates_to,
  141. backfilled=True,
  142. )
  143. elif stream_name == CachesStream.NAME:
  144. if self._cache_id_gen:
  145. self._cache_id_gen.advance(instance_name, token)
  146. for row in rows:
  147. if row.cache_func == CURRENT_STATE_CACHE_NAME:
  148. if row.keys is None:
  149. raise Exception(
  150. "Can't send an 'invalidate all' for current state cache"
  151. )
  152. room_id = row.keys[0]
  153. members_changed = set(row.keys[1:])
  154. self._invalidate_state_caches(room_id, members_changed)
  155. else:
  156. self._attempt_to_invalidate_cache(row.cache_func, row.keys)
  157. super().process_replication_rows(stream_name, instance_name, token, rows)
  158. def _process_event_stream_row(self, token: int, row: EventsStreamRow) -> None:
  159. data = row.data
  160. if row.type == EventsStreamEventRow.TypeId:
  161. assert isinstance(data, EventsStreamEventRow)
  162. self._invalidate_caches_for_event(
  163. token,
  164. data.event_id,
  165. data.room_id,
  166. data.type,
  167. data.state_key,
  168. data.redacts,
  169. data.relates_to,
  170. backfilled=False,
  171. )
  172. elif row.type == EventsStreamCurrentStateRow.TypeId:
  173. assert isinstance(data, EventsStreamCurrentStateRow)
  174. self._curr_state_delta_stream_cache.entity_has_changed(data.room_id, token)
  175. if data.type == EventTypes.Member:
  176. self.get_rooms_for_user_with_stream_ordering.invalidate(
  177. (data.state_key,)
  178. )
  179. else:
  180. raise Exception("Unknown events stream row type %s" % (row.type,))
  181. def _invalidate_caches_for_event(
  182. self,
  183. stream_ordering: int,
  184. event_id: str,
  185. room_id: str,
  186. etype: str,
  187. state_key: Optional[str],
  188. redacts: Optional[str],
  189. relates_to: Optional[str],
  190. backfilled: bool,
  191. ) -> None:
  192. # This invalidates any local in-memory cached event objects, the original
  193. # process triggering the invalidation is responsible for clearing any external
  194. # cached objects.
  195. self._invalidate_local_get_event_cache(event_id)
  196. self._attempt_to_invalidate_cache("have_seen_event", (room_id, event_id))
  197. self._attempt_to_invalidate_cache("get_latest_event_ids_in_room", (room_id,))
  198. self._attempt_to_invalidate_cache(
  199. "get_unread_event_push_actions_by_room_for_user", (room_id,)
  200. )
  201. # The `_get_membership_from_event_id` is immutable, except for the
  202. # case where we look up an event *before* persisting it.
  203. self._attempt_to_invalidate_cache("_get_membership_from_event_id", (event_id,))
  204. if not backfilled:
  205. self._events_stream_cache.entity_has_changed(room_id, stream_ordering)
  206. if redacts:
  207. self._invalidate_local_get_event_cache(redacts)
  208. # Caches which might leak edits must be invalidated for the event being
  209. # redacted.
  210. self._attempt_to_invalidate_cache("get_relations_for_event", (redacts,))
  211. self._attempt_to_invalidate_cache("get_applicable_edit", (redacts,))
  212. if etype == EventTypes.Member:
  213. self._membership_stream_cache.entity_has_changed(state_key, stream_ordering)
  214. self._attempt_to_invalidate_cache(
  215. "get_invited_rooms_for_local_user", (state_key,)
  216. )
  217. if relates_to:
  218. self._attempt_to_invalidate_cache("get_relations_for_event", (relates_to,))
  219. self._attempt_to_invalidate_cache(
  220. "get_aggregation_groups_for_event", (relates_to,)
  221. )
  222. self._attempt_to_invalidate_cache("get_applicable_edit", (relates_to,))
  223. self._attempt_to_invalidate_cache("get_thread_summary", (relates_to,))
  224. self._attempt_to_invalidate_cache("get_thread_participated", (relates_to,))
  225. self._attempt_to_invalidate_cache(
  226. "get_mutual_event_relations_for_rel_type", (relates_to,)
  227. )
  228. async def invalidate_cache_and_stream(
  229. self, cache_name: str, keys: Tuple[Any, ...]
  230. ) -> None:
  231. """Invalidates the cache and adds it to the cache stream so slaves
  232. will know to invalidate their caches.
  233. This should only be used to invalidate caches where slaves won't
  234. otherwise know from other replication streams that the cache should
  235. be invalidated.
  236. """
  237. cache_func = getattr(self, cache_name, None)
  238. if not cache_func:
  239. return
  240. cache_func.invalidate(keys)
  241. await self.send_invalidation_to_replication(
  242. cache_func.__name__,
  243. keys,
  244. )
  245. def _invalidate_cache_and_stream(
  246. self,
  247. txn: LoggingTransaction,
  248. cache_func: CachedFunction,
  249. keys: Tuple[Any, ...],
  250. ) -> None:
  251. """Invalidates the cache and adds it to the cache stream so slaves
  252. will know to invalidate their caches.
  253. This should only be used to invalidate caches where slaves won't
  254. otherwise know from other replication streams that the cache should
  255. be invalidated.
  256. """
  257. txn.call_after(cache_func.invalidate, keys)
  258. self._send_invalidation_to_replication(txn, cache_func.__name__, keys)
  259. def _invalidate_all_cache_and_stream(
  260. self, txn: LoggingTransaction, cache_func: CachedFunction
  261. ) -> None:
  262. """Invalidates the entire cache and adds it to the cache stream so slaves
  263. will know to invalidate their caches.
  264. """
  265. txn.call_after(cache_func.invalidate_all)
  266. self._send_invalidation_to_replication(txn, cache_func.__name__, None)
  267. def _invalidate_state_caches_and_stream(
  268. self, txn: LoggingTransaction, room_id: str, members_changed: Collection[str]
  269. ) -> None:
  270. """Special case invalidation of caches based on current state.
  271. We special case this so that we can batch the cache invalidations into a
  272. single replication poke.
  273. Args:
  274. txn
  275. room_id: Room where state changed
  276. members_changed: The user_ids of members that have changed
  277. """
  278. txn.call_after(self._invalidate_state_caches, room_id, members_changed)
  279. if members_changed:
  280. # We need to be careful that the size of the `members_changed` list
  281. # isn't so large that it causes problems sending over replication, so we
  282. # send them in chunks.
  283. # Max line length is 16K, and max user ID length is 255, so 50 should
  284. # be safe.
  285. for chunk in batch_iter(members_changed, 50):
  286. keys = itertools.chain([room_id], chunk)
  287. self._send_invalidation_to_replication(
  288. txn, CURRENT_STATE_CACHE_NAME, keys
  289. )
  290. else:
  291. # if no members changed, we still need to invalidate the other caches.
  292. self._send_invalidation_to_replication(
  293. txn, CURRENT_STATE_CACHE_NAME, [room_id]
  294. )
  295. async def send_invalidation_to_replication(
  296. self, cache_name: str, keys: Optional[Collection[Any]]
  297. ) -> None:
  298. await self.db_pool.runInteraction(
  299. "send_invalidation_to_replication",
  300. self._send_invalidation_to_replication,
  301. cache_name,
  302. keys,
  303. )
  304. def _send_invalidation_to_replication(
  305. self, txn: LoggingTransaction, cache_name: str, keys: Optional[Iterable[Any]]
  306. ) -> None:
  307. """Notifies replication that given cache has been invalidated.
  308. Note that this does *not* invalidate the cache locally.
  309. Args:
  310. txn
  311. cache_name
  312. keys: Entry to invalidate. If None will invalidate all.
  313. """
  314. if cache_name == CURRENT_STATE_CACHE_NAME and keys is None:
  315. raise Exception(
  316. "Can't stream invalidate all with magic current state cache"
  317. )
  318. if isinstance(self.database_engine, PostgresEngine):
  319. # get_next() returns a context manager which is designed to wrap
  320. # the transaction. However, we want to only get an ID when we want
  321. # to use it, here, so we need to call __enter__ manually, and have
  322. # __exit__ called after the transaction finishes.
  323. stream_id = self._cache_id_gen.get_next_txn(txn)
  324. txn.call_after(self.hs.get_notifier().on_new_replication_data)
  325. if keys is not None:
  326. keys = list(keys)
  327. self.db_pool.simple_insert_txn(
  328. txn,
  329. table="cache_invalidation_stream_by_instance",
  330. values={
  331. "stream_id": stream_id,
  332. "instance_name": self._instance_name,
  333. "cache_func": cache_name,
  334. "keys": keys,
  335. "invalidation_ts": self._clock.time_msec(),
  336. },
  337. )
  338. def get_cache_stream_token_for_writer(self, instance_name: str) -> int:
  339. if self._cache_id_gen:
  340. return self._cache_id_gen.get_current_token_for_writer(instance_name)
  341. else:
  342. return 0