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.
 
 
 
 
 
 

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