store.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  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 logging
  16. from collections import namedtuple
  17. from typing import Dict, Iterable, List, Set, Tuple
  18. from twisted.internet import defer
  19. from synapse.api.constants import EventTypes
  20. from synapse.storage._base import SQLBaseStore
  21. from synapse.storage.data_stores.state.bg_updates import StateBackgroundUpdateStore
  22. from synapse.storage.database import Database
  23. from synapse.storage.state import StateFilter
  24. from synapse.types import StateMap
  25. from synapse.util.caches.descriptors import cached
  26. from synapse.util.caches.dictionary_cache import DictionaryCache
  27. logger = logging.getLogger(__name__)
  28. MAX_STATE_DELTA_HOPS = 100
  29. class _GetStateGroupDelta(
  30. namedtuple("_GetStateGroupDelta", ("prev_group", "delta_ids"))
  31. ):
  32. """Return type of get_state_group_delta that implements __len__, which lets
  33. us use the itrable flag when caching
  34. """
  35. __slots__ = []
  36. def __len__(self):
  37. return len(self.delta_ids) if self.delta_ids else 0
  38. class StateGroupDataStore(StateBackgroundUpdateStore, SQLBaseStore):
  39. """A data store for fetching/storing state groups.
  40. """
  41. def __init__(self, database: Database, db_conn, hs):
  42. super(StateGroupDataStore, self).__init__(database, db_conn, hs)
  43. # Originally the state store used a single DictionaryCache to cache the
  44. # event IDs for the state types in a given state group to avoid hammering
  45. # on the state_group* tables.
  46. #
  47. # The point of using a DictionaryCache is that it can cache a subset
  48. # of the state events for a given state group (i.e. a subset of the keys for a
  49. # given dict which is an entry in the cache for a given state group ID).
  50. #
  51. # However, this poses problems when performing complicated queries
  52. # on the store - for instance: "give me all the state for this group, but
  53. # limit members to this subset of users", as DictionaryCache's API isn't
  54. # rich enough to say "please cache any of these fields, apart from this subset".
  55. # This is problematic when lazy loading members, which requires this behaviour,
  56. # as without it the cache has no choice but to speculatively load all
  57. # state events for the group, which negates the efficiency being sought.
  58. #
  59. # Rather than overcomplicating DictionaryCache's API, we instead split the
  60. # state_group_cache into two halves - one for tracking non-member events,
  61. # and the other for tracking member_events. This means that lazy loading
  62. # queries can be made in a cache-friendly manner by querying both caches
  63. # separately and then merging the result. So for the example above, you
  64. # would query the members cache for a specific subset of state keys
  65. # (which DictionaryCache will handle efficiently and fine) and the non-members
  66. # cache for all state (which DictionaryCache will similarly handle fine)
  67. # and then just merge the results together.
  68. #
  69. # We size the non-members cache to be smaller than the members cache as the
  70. # vast majority of state in Matrix (today) is member events.
  71. self._state_group_cache = DictionaryCache(
  72. "*stateGroupCache*",
  73. # TODO: this hasn't been tuned yet
  74. 50000,
  75. )
  76. self._state_group_members_cache = DictionaryCache(
  77. "*stateGroupMembersCache*", 500000,
  78. )
  79. @cached(max_entries=10000, iterable=True)
  80. def get_state_group_delta(self, state_group):
  81. """Given a state group try to return a previous group and a delta between
  82. the old and the new.
  83. Returns:
  84. (prev_group, delta_ids), where both may be None.
  85. """
  86. def _get_state_group_delta_txn(txn):
  87. prev_group = self.db.simple_select_one_onecol_txn(
  88. txn,
  89. table="state_group_edges",
  90. keyvalues={"state_group": state_group},
  91. retcol="prev_state_group",
  92. allow_none=True,
  93. )
  94. if not prev_group:
  95. return _GetStateGroupDelta(None, None)
  96. delta_ids = self.db.simple_select_list_txn(
  97. txn,
  98. table="state_groups_state",
  99. keyvalues={"state_group": state_group},
  100. retcols=("type", "state_key", "event_id"),
  101. )
  102. return _GetStateGroupDelta(
  103. prev_group,
  104. {(row["type"], row["state_key"]): row["event_id"] for row in delta_ids},
  105. )
  106. return self.db.runInteraction(
  107. "get_state_group_delta", _get_state_group_delta_txn
  108. )
  109. @defer.inlineCallbacks
  110. def _get_state_groups_from_groups(
  111. self, groups: List[int], state_filter: StateFilter
  112. ):
  113. """Returns the state groups for a given set of groups from the
  114. database, filtering on types of state events.
  115. Args:
  116. groups: list of state group IDs to query
  117. state_filter: The state filter used to fetch state
  118. from the database.
  119. Returns:
  120. Deferred[Dict[int, StateMap[str]]]: Dict of state group to state map.
  121. """
  122. results = {}
  123. chunks = [groups[i : i + 100] for i in range(0, len(groups), 100)]
  124. for chunk in chunks:
  125. res = yield self.db.runInteraction(
  126. "_get_state_groups_from_groups",
  127. self._get_state_groups_from_groups_txn,
  128. chunk,
  129. state_filter,
  130. )
  131. results.update(res)
  132. return results
  133. def _get_state_for_group_using_cache(self, cache, group, state_filter):
  134. """Checks if group is in cache. See `_get_state_for_groups`
  135. Args:
  136. cache(DictionaryCache): the state group cache to use
  137. group(int): The state group to lookup
  138. state_filter (StateFilter): The state filter used to fetch state
  139. from the database.
  140. Returns 2-tuple (`state_dict`, `got_all`).
  141. `got_all` is a bool indicating if we successfully retrieved all
  142. requests state from the cache, if False we need to query the DB for the
  143. missing state.
  144. """
  145. is_all, known_absent, state_dict_ids = cache.get(group)
  146. if is_all or state_filter.is_full():
  147. # Either we have everything or want everything, either way
  148. # `is_all` tells us whether we've gotten everything.
  149. return state_filter.filter_state(state_dict_ids), is_all
  150. # tracks whether any of our requested types are missing from the cache
  151. missing_types = False
  152. if state_filter.has_wildcards():
  153. # We don't know if we fetched all the state keys for the types in
  154. # the filter that are wildcards, so we have to assume that we may
  155. # have missed some.
  156. missing_types = True
  157. else:
  158. # There aren't any wild cards, so `concrete_types()` returns the
  159. # complete list of event types we're wanting.
  160. for key in state_filter.concrete_types():
  161. if key not in state_dict_ids and key not in known_absent:
  162. missing_types = True
  163. break
  164. return state_filter.filter_state(state_dict_ids), not missing_types
  165. @defer.inlineCallbacks
  166. def _get_state_for_groups(
  167. self, groups: Iterable[int], state_filter: StateFilter = StateFilter.all()
  168. ):
  169. """Gets the state at each of a list of state groups, optionally
  170. filtering by type/state_key
  171. Args:
  172. groups: list of state groups for which we want
  173. to get the state.
  174. state_filter: The state filter used to fetch state
  175. from the database.
  176. Returns:
  177. Deferred[Dict[int, StateMap[str]]]: Dict of state group to state map.
  178. """
  179. member_filter, non_member_filter = state_filter.get_member_split()
  180. # Now we look them up in the member and non-member caches
  181. (
  182. non_member_state,
  183. incomplete_groups_nm,
  184. ) = yield self._get_state_for_groups_using_cache(
  185. groups, self._state_group_cache, state_filter=non_member_filter
  186. )
  187. (
  188. member_state,
  189. incomplete_groups_m,
  190. ) = yield self._get_state_for_groups_using_cache(
  191. groups, self._state_group_members_cache, state_filter=member_filter
  192. )
  193. state = dict(non_member_state)
  194. for group in groups:
  195. state[group].update(member_state[group])
  196. # Now fetch any missing groups from the database
  197. incomplete_groups = incomplete_groups_m | incomplete_groups_nm
  198. if not incomplete_groups:
  199. return state
  200. cache_sequence_nm = self._state_group_cache.sequence
  201. cache_sequence_m = self._state_group_members_cache.sequence
  202. # Help the cache hit ratio by expanding the filter a bit
  203. db_state_filter = state_filter.return_expanded()
  204. group_to_state_dict = yield self._get_state_groups_from_groups(
  205. list(incomplete_groups), state_filter=db_state_filter
  206. )
  207. # Now lets update the caches
  208. self._insert_into_cache(
  209. group_to_state_dict,
  210. db_state_filter,
  211. cache_seq_num_members=cache_sequence_m,
  212. cache_seq_num_non_members=cache_sequence_nm,
  213. )
  214. # And finally update the result dict, by filtering out any extra
  215. # stuff we pulled out of the database.
  216. for group, group_state_dict in group_to_state_dict.items():
  217. # We just replace any existing entries, as we will have loaded
  218. # everything we need from the database anyway.
  219. state[group] = state_filter.filter_state(group_state_dict)
  220. return state
  221. def _get_state_for_groups_using_cache(
  222. self, groups: Iterable[int], cache: DictionaryCache, state_filter: StateFilter
  223. ) -> Tuple[Dict[int, StateMap[str]], Set[int]]:
  224. """Gets the state at each of a list of state groups, optionally
  225. filtering by type/state_key, querying from a specific cache.
  226. Args:
  227. groups: list of state groups for which we want to get the state.
  228. cache: the cache of group ids to state dicts which
  229. we will pass through - either the normal state cache or the
  230. specific members state cache.
  231. state_filter: The state filter used to fetch state from the
  232. database.
  233. Returns:
  234. Tuple of dict of state_group_id to state map of entries in the
  235. cache, and the state group ids either missing from the cache or
  236. incomplete.
  237. """
  238. results = {}
  239. incomplete_groups = set()
  240. for group in set(groups):
  241. state_dict_ids, got_all = self._get_state_for_group_using_cache(
  242. cache, group, state_filter
  243. )
  244. results[group] = state_dict_ids
  245. if not got_all:
  246. incomplete_groups.add(group)
  247. return results, incomplete_groups
  248. def _insert_into_cache(
  249. self,
  250. group_to_state_dict,
  251. state_filter,
  252. cache_seq_num_members,
  253. cache_seq_num_non_members,
  254. ):
  255. """Inserts results from querying the database into the relevant cache.
  256. Args:
  257. group_to_state_dict (dict): The new entries pulled from database.
  258. Map from state group to state dict
  259. state_filter (StateFilter): The state filter used to fetch state
  260. from the database.
  261. cache_seq_num_members (int): Sequence number of member cache since
  262. last lookup in cache
  263. cache_seq_num_non_members (int): Sequence number of member cache since
  264. last lookup in cache
  265. """
  266. # We need to work out which types we've fetched from the DB for the
  267. # member vs non-member caches. This should be as accurate as possible,
  268. # but can be an underestimate (e.g. when we have wild cards)
  269. member_filter, non_member_filter = state_filter.get_member_split()
  270. if member_filter.is_full():
  271. # We fetched all member events
  272. member_types = None
  273. else:
  274. # `concrete_types()` will only return a subset when there are wild
  275. # cards in the filter, but that's fine.
  276. member_types = member_filter.concrete_types()
  277. if non_member_filter.is_full():
  278. # We fetched all non member events
  279. non_member_types = None
  280. else:
  281. non_member_types = non_member_filter.concrete_types()
  282. for group, group_state_dict in group_to_state_dict.items():
  283. state_dict_members = {}
  284. state_dict_non_members = {}
  285. for k, v in group_state_dict.items():
  286. if k[0] == EventTypes.Member:
  287. state_dict_members[k] = v
  288. else:
  289. state_dict_non_members[k] = v
  290. self._state_group_members_cache.update(
  291. cache_seq_num_members,
  292. key=group,
  293. value=state_dict_members,
  294. fetched_keys=member_types,
  295. )
  296. self._state_group_cache.update(
  297. cache_seq_num_non_members,
  298. key=group,
  299. value=state_dict_non_members,
  300. fetched_keys=non_member_types,
  301. )
  302. def store_state_group(
  303. self, event_id, room_id, prev_group, delta_ids, current_state_ids
  304. ):
  305. """Store a new set of state, returning a newly assigned state group.
  306. Args:
  307. event_id (str): The event ID for which the state was calculated
  308. room_id (str)
  309. prev_group (int|None): A previous state group for the room, optional.
  310. delta_ids (dict|None): The delta between state at `prev_group` and
  311. `current_state_ids`, if `prev_group` was given. Same format as
  312. `current_state_ids`.
  313. current_state_ids (dict): The state to store. Map of (type, state_key)
  314. to event_id.
  315. Returns:
  316. Deferred[int]: The state group ID
  317. """
  318. def _store_state_group_txn(txn):
  319. if current_state_ids is None:
  320. # AFAIK, this can never happen
  321. raise Exception("current_state_ids cannot be None")
  322. state_group = self.database_engine.get_next_state_group_id(txn)
  323. self.db.simple_insert_txn(
  324. txn,
  325. table="state_groups",
  326. values={"id": state_group, "room_id": room_id, "event_id": event_id},
  327. )
  328. # We persist as a delta if we can, while also ensuring the chain
  329. # of deltas isn't tooo long, as otherwise read performance degrades.
  330. if prev_group:
  331. is_in_db = self.db.simple_select_one_onecol_txn(
  332. txn,
  333. table="state_groups",
  334. keyvalues={"id": prev_group},
  335. retcol="id",
  336. allow_none=True,
  337. )
  338. if not is_in_db:
  339. raise Exception(
  340. "Trying to persist state with unpersisted prev_group: %r"
  341. % (prev_group,)
  342. )
  343. potential_hops = self._count_state_group_hops_txn(txn, prev_group)
  344. if prev_group and potential_hops < MAX_STATE_DELTA_HOPS:
  345. self.db.simple_insert_txn(
  346. txn,
  347. table="state_group_edges",
  348. values={"state_group": state_group, "prev_state_group": prev_group},
  349. )
  350. self.db.simple_insert_many_txn(
  351. txn,
  352. table="state_groups_state",
  353. values=[
  354. {
  355. "state_group": state_group,
  356. "room_id": room_id,
  357. "type": key[0],
  358. "state_key": key[1],
  359. "event_id": state_id,
  360. }
  361. for key, state_id in delta_ids.items()
  362. ],
  363. )
  364. else:
  365. self.db.simple_insert_many_txn(
  366. txn,
  367. table="state_groups_state",
  368. values=[
  369. {
  370. "state_group": state_group,
  371. "room_id": room_id,
  372. "type": key[0],
  373. "state_key": key[1],
  374. "event_id": state_id,
  375. }
  376. for key, state_id in current_state_ids.items()
  377. ],
  378. )
  379. # Prefill the state group caches with this group.
  380. # It's fine to use the sequence like this as the state group map
  381. # is immutable. (If the map wasn't immutable then this prefill could
  382. # race with another update)
  383. current_member_state_ids = {
  384. s: ev
  385. for (s, ev) in current_state_ids.items()
  386. if s[0] == EventTypes.Member
  387. }
  388. txn.call_after(
  389. self._state_group_members_cache.update,
  390. self._state_group_members_cache.sequence,
  391. key=state_group,
  392. value=dict(current_member_state_ids),
  393. )
  394. current_non_member_state_ids = {
  395. s: ev
  396. for (s, ev) in current_state_ids.items()
  397. if s[0] != EventTypes.Member
  398. }
  399. txn.call_after(
  400. self._state_group_cache.update,
  401. self._state_group_cache.sequence,
  402. key=state_group,
  403. value=dict(current_non_member_state_ids),
  404. )
  405. return state_group
  406. return self.db.runInteraction("store_state_group", _store_state_group_txn)
  407. def purge_unreferenced_state_groups(
  408. self, room_id: str, state_groups_to_delete
  409. ) -> defer.Deferred:
  410. """Deletes no longer referenced state groups and de-deltas any state
  411. groups that reference them.
  412. Args:
  413. room_id: The room the state groups belong to (must all be in the
  414. same room).
  415. state_groups_to_delete (Collection[int]): Set of all state groups
  416. to delete.
  417. """
  418. return self.db.runInteraction(
  419. "purge_unreferenced_state_groups",
  420. self._purge_unreferenced_state_groups,
  421. room_id,
  422. state_groups_to_delete,
  423. )
  424. def _purge_unreferenced_state_groups(self, txn, room_id, state_groups_to_delete):
  425. logger.info(
  426. "[purge] found %i state groups to delete", len(state_groups_to_delete)
  427. )
  428. rows = self.db.simple_select_many_txn(
  429. txn,
  430. table="state_group_edges",
  431. column="prev_state_group",
  432. iterable=state_groups_to_delete,
  433. keyvalues={},
  434. retcols=("state_group",),
  435. )
  436. remaining_state_groups = {
  437. row["state_group"]
  438. for row in rows
  439. if row["state_group"] not in state_groups_to_delete
  440. }
  441. logger.info(
  442. "[purge] de-delta-ing %i remaining state groups",
  443. len(remaining_state_groups),
  444. )
  445. # Now we turn the state groups that reference to-be-deleted state
  446. # groups to non delta versions.
  447. for sg in remaining_state_groups:
  448. logger.info("[purge] de-delta-ing remaining state group %s", sg)
  449. curr_state = self._get_state_groups_from_groups_txn(txn, [sg])
  450. curr_state = curr_state[sg]
  451. self.db.simple_delete_txn(
  452. txn, table="state_groups_state", keyvalues={"state_group": sg}
  453. )
  454. self.db.simple_delete_txn(
  455. txn, table="state_group_edges", keyvalues={"state_group": sg}
  456. )
  457. self.db.simple_insert_many_txn(
  458. txn,
  459. table="state_groups_state",
  460. values=[
  461. {
  462. "state_group": sg,
  463. "room_id": room_id,
  464. "type": key[0],
  465. "state_key": key[1],
  466. "event_id": state_id,
  467. }
  468. for key, state_id in curr_state.items()
  469. ],
  470. )
  471. logger.info("[purge] removing redundant state groups")
  472. txn.executemany(
  473. "DELETE FROM state_groups_state WHERE state_group = ?",
  474. ((sg,) for sg in state_groups_to_delete),
  475. )
  476. txn.executemany(
  477. "DELETE FROM state_groups WHERE id = ?",
  478. ((sg,) for sg in state_groups_to_delete),
  479. )
  480. @defer.inlineCallbacks
  481. def get_previous_state_groups(self, state_groups):
  482. """Fetch the previous groups of the given state groups.
  483. Args:
  484. state_groups (Iterable[int])
  485. Returns:
  486. Deferred[dict[int, int]]: mapping from state group to previous
  487. state group.
  488. """
  489. rows = yield self.db.simple_select_many_batch(
  490. table="state_group_edges",
  491. column="prev_state_group",
  492. iterable=state_groups,
  493. keyvalues={},
  494. retcols=("prev_state_group", "state_group"),
  495. desc="get_previous_state_groups",
  496. )
  497. return {row["state_group"]: row["prev_state_group"] for row in rows}
  498. def purge_room_state(self, room_id, state_groups_to_delete):
  499. """Deletes all record of a room from state tables
  500. Args:
  501. room_id (str):
  502. state_groups_to_delete (list[int]): State groups to delete
  503. """
  504. return self.db.runInteraction(
  505. "purge_room_state",
  506. self._purge_room_state_txn,
  507. room_id,
  508. state_groups_to_delete,
  509. )
  510. def _purge_room_state_txn(self, txn, room_id, state_groups_to_delete):
  511. # first we have to delete the state groups states
  512. logger.info("[purge] removing %s from state_groups_state", room_id)
  513. self.db.simple_delete_many_txn(
  514. txn,
  515. table="state_groups_state",
  516. column="state_group",
  517. iterable=state_groups_to_delete,
  518. keyvalues={},
  519. )
  520. # ... and the state group edges
  521. logger.info("[purge] removing %s from state_group_edges", room_id)
  522. self.db.simple_delete_many_txn(
  523. txn,
  524. table="state_group_edges",
  525. column="state_group",
  526. iterable=state_groups_to_delete,
  527. keyvalues={},
  528. )
  529. # ... and the state groups
  530. logger.info("[purge] removing %s from state_groups", room_id)
  531. self.db.simple_delete_many_txn(
  532. txn,
  533. table="state_groups",
  534. column="id",
  535. iterable=state_groups_to_delete,
  536. keyvalues={},
  537. )