state.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. from collections import namedtuple
  16. import logging
  17. from six import iteritems, itervalues
  18. from six.moves import range
  19. from twisted.internet import defer
  20. from synapse.storage.background_updates import BackgroundUpdateStore
  21. from synapse.storage.engines import PostgresEngine
  22. from synapse.util.caches import intern_string, CACHE_SIZE_FACTOR
  23. from synapse.util.caches.descriptors import cached, cachedList
  24. from synapse.util.caches.dictionary_cache import DictionaryCache
  25. from synapse.util.stringutils import to_ascii
  26. from ._base import SQLBaseStore
  27. logger = logging.getLogger(__name__)
  28. MAX_STATE_DELTA_HOPS = 100
  29. class _GetStateGroupDelta(namedtuple("_GetStateGroupDelta", ("prev_group", "delta_ids"))):
  30. """Return type of get_state_group_delta that implements __len__, which lets
  31. us use the itrable flag when caching
  32. """
  33. __slots__ = []
  34. def __len__(self):
  35. return len(self.delta_ids) if self.delta_ids else 0
  36. class StateGroupWorkerStore(SQLBaseStore):
  37. """The parts of StateGroupStore that can be called from workers.
  38. """
  39. STATE_GROUP_DEDUPLICATION_UPDATE_NAME = "state_group_state_deduplication"
  40. STATE_GROUP_INDEX_UPDATE_NAME = "state_group_state_type_index"
  41. CURRENT_STATE_INDEX_UPDATE_NAME = "current_state_members_idx"
  42. def __init__(self, db_conn, hs):
  43. super(StateGroupWorkerStore, self).__init__(db_conn, hs)
  44. self._state_group_cache = DictionaryCache(
  45. "*stateGroupCache*", 100000 * CACHE_SIZE_FACTOR
  46. )
  47. @cached(max_entries=100000, iterable=True)
  48. def get_current_state_ids(self, room_id):
  49. """Get the current state event ids for a room based on the
  50. current_state_events table.
  51. Args:
  52. room_id (str)
  53. Returns:
  54. deferred: dict of (type, state_key) -> event_id
  55. """
  56. def _get_current_state_ids_txn(txn):
  57. txn.execute(
  58. """SELECT type, state_key, event_id FROM current_state_events
  59. WHERE room_id = ?
  60. """,
  61. (room_id,)
  62. )
  63. return {
  64. (intern_string(r[0]), intern_string(r[1])): to_ascii(r[2]) for r in txn
  65. }
  66. return self.runInteraction(
  67. "get_current_state_ids",
  68. _get_current_state_ids_txn,
  69. )
  70. @cached(max_entries=10000, iterable=True)
  71. def get_state_group_delta(self, state_group):
  72. """Given a state group try to return a previous group and a delta between
  73. the old and the new.
  74. Returns:
  75. (prev_group, delta_ids), where both may be None.
  76. """
  77. def _get_state_group_delta_txn(txn):
  78. prev_group = self._simple_select_one_onecol_txn(
  79. txn,
  80. table="state_group_edges",
  81. keyvalues={
  82. "state_group": state_group,
  83. },
  84. retcol="prev_state_group",
  85. allow_none=True,
  86. )
  87. if not prev_group:
  88. return _GetStateGroupDelta(None, None)
  89. delta_ids = self._simple_select_list_txn(
  90. txn,
  91. table="state_groups_state",
  92. keyvalues={
  93. "state_group": state_group,
  94. },
  95. retcols=("type", "state_key", "event_id",)
  96. )
  97. return _GetStateGroupDelta(prev_group, {
  98. (row["type"], row["state_key"]): row["event_id"]
  99. for row in delta_ids
  100. })
  101. return self.runInteraction(
  102. "get_state_group_delta",
  103. _get_state_group_delta_txn,
  104. )
  105. @defer.inlineCallbacks
  106. def get_state_groups_ids(self, room_id, event_ids):
  107. if not event_ids:
  108. defer.returnValue({})
  109. event_to_groups = yield self._get_state_group_for_events(
  110. event_ids,
  111. )
  112. groups = set(itervalues(event_to_groups))
  113. group_to_state = yield self._get_state_for_groups(groups)
  114. defer.returnValue(group_to_state)
  115. @defer.inlineCallbacks
  116. def get_state_ids_for_group(self, state_group):
  117. """Get the state IDs for the given state group
  118. Args:
  119. state_group (int)
  120. Returns:
  121. Deferred[dict]: Resolves to a map of (type, state_key) -> event_id
  122. """
  123. group_to_state = yield self._get_state_for_groups((state_group,))
  124. defer.returnValue(group_to_state[state_group])
  125. @defer.inlineCallbacks
  126. def get_state_groups(self, room_id, event_ids):
  127. """ Get the state groups for the given list of event_ids
  128. The return value is a dict mapping group names to lists of events.
  129. """
  130. if not event_ids:
  131. defer.returnValue({})
  132. group_to_ids = yield self.get_state_groups_ids(room_id, event_ids)
  133. state_event_map = yield self.get_events(
  134. [
  135. ev_id for group_ids in itervalues(group_to_ids)
  136. for ev_id in itervalues(group_ids)
  137. ],
  138. get_prev_content=False
  139. )
  140. defer.returnValue({
  141. group: [
  142. state_event_map[v] for v in itervalues(event_id_map)
  143. if v in state_event_map
  144. ]
  145. for group, event_id_map in iteritems(group_to_ids)
  146. })
  147. @defer.inlineCallbacks
  148. def _get_state_groups_from_groups(self, groups, types):
  149. """Returns dictionary state_group -> (dict of (type, state_key) -> event id)
  150. """
  151. results = {}
  152. chunks = [groups[i:i + 100] for i in range(0, len(groups), 100)]
  153. for chunk in chunks:
  154. res = yield self.runInteraction(
  155. "_get_state_groups_from_groups",
  156. self._get_state_groups_from_groups_txn, chunk, types,
  157. )
  158. results.update(res)
  159. defer.returnValue(results)
  160. def _get_state_groups_from_groups_txn(self, txn, groups, types=None):
  161. results = {group: {} for group in groups}
  162. if types is not None:
  163. types = list(set(types)) # deduplicate types list
  164. if isinstance(self.database_engine, PostgresEngine):
  165. # Temporarily disable sequential scans in this transaction. This is
  166. # a temporary hack until we can add the right indices in
  167. txn.execute("SET LOCAL enable_seqscan=off")
  168. # The below query walks the state_group tree so that the "state"
  169. # table includes all state_groups in the tree. It then joins
  170. # against `state_groups_state` to fetch the latest state.
  171. # It assumes that previous state groups are always numerically
  172. # lesser.
  173. # The PARTITION is used to get the event_id in the greatest state
  174. # group for the given type, state_key.
  175. # This may return multiple rows per (type, state_key), but last_value
  176. # should be the same.
  177. sql = ("""
  178. WITH RECURSIVE state(state_group) AS (
  179. VALUES(?::bigint)
  180. UNION ALL
  181. SELECT prev_state_group FROM state_group_edges e, state s
  182. WHERE s.state_group = e.state_group
  183. )
  184. SELECT type, state_key, last_value(event_id) OVER (
  185. PARTITION BY type, state_key ORDER BY state_group ASC
  186. ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
  187. ) AS event_id FROM state_groups_state
  188. WHERE state_group IN (
  189. SELECT state_group FROM state
  190. )
  191. %s
  192. """)
  193. # Turns out that postgres doesn't like doing a list of OR's and
  194. # is about 1000x slower, so we just issue a query for each specific
  195. # type seperately.
  196. if types:
  197. clause_to_args = [
  198. (
  199. "AND type = ? AND state_key = ?",
  200. (etype, state_key)
  201. ) if state_key is not None else (
  202. "AND type = ?",
  203. (etype,)
  204. )
  205. for etype, state_key in types
  206. ]
  207. else:
  208. # If types is None we fetch all the state, and so just use an
  209. # empty where clause with no extra args.
  210. clause_to_args = [("", [])]
  211. for where_clause, where_args in clause_to_args:
  212. for group in groups:
  213. args = [group]
  214. args.extend(where_args)
  215. txn.execute(sql % (where_clause,), args)
  216. for row in txn:
  217. typ, state_key, event_id = row
  218. key = (typ, state_key)
  219. results[group][key] = event_id
  220. else:
  221. where_args = []
  222. where_clauses = []
  223. wildcard_types = False
  224. if types is not None:
  225. for typ in types:
  226. if typ[1] is None:
  227. where_clauses.append("(type = ?)")
  228. where_args.extend(typ[0])
  229. wildcard_types = True
  230. else:
  231. where_clauses.append("(type = ? AND state_key = ?)")
  232. where_args.extend([typ[0], typ[1]])
  233. where_clause = "AND (%s)" % (" OR ".join(where_clauses))
  234. else:
  235. where_clause = ""
  236. # We don't use WITH RECURSIVE on sqlite3 as there are distributions
  237. # that ship with an sqlite3 version that doesn't support it (e.g. wheezy)
  238. for group in groups:
  239. next_group = group
  240. while next_group:
  241. # We did this before by getting the list of group ids, and
  242. # then passing that list to sqlite to get latest event for
  243. # each (type, state_key). However, that was terribly slow
  244. # without the right indices (which we can't add until
  245. # after we finish deduping state, which requires this func)
  246. args = [next_group]
  247. if types:
  248. args.extend(where_args)
  249. txn.execute(
  250. "SELECT type, state_key, event_id FROM state_groups_state"
  251. " WHERE state_group = ? %s" % (where_clause,),
  252. args
  253. )
  254. results[group].update(
  255. ((typ, state_key), event_id)
  256. for typ, state_key, event_id in txn
  257. if (typ, state_key) not in results[group]
  258. )
  259. # If the number of entries in the (type,state_key)->event_id dict
  260. # matches the number of (type,state_keys) types we were searching
  261. # for, then we must have found them all, so no need to go walk
  262. # further down the tree... UNLESS our types filter contained
  263. # wildcards (i.e. Nones) in which case we have to do an exhaustive
  264. # search
  265. if (
  266. types is not None and
  267. not wildcard_types and
  268. len(results[group]) == len(types)
  269. ):
  270. break
  271. next_group = self._simple_select_one_onecol_txn(
  272. txn,
  273. table="state_group_edges",
  274. keyvalues={"state_group": next_group},
  275. retcol="prev_state_group",
  276. allow_none=True,
  277. )
  278. return results
  279. @defer.inlineCallbacks
  280. def get_state_for_events(self, event_ids, types):
  281. """Given a list of event_ids and type tuples, return a list of state
  282. dicts for each event. The state dicts will only have the type/state_keys
  283. that are in the `types` list.
  284. Args:
  285. event_ids (list)
  286. types (list): List of (type, state_key) tuples which are used to
  287. filter the state fetched. `state_key` may be None, which matches
  288. any `state_key`
  289. Returns:
  290. deferred: A list of dicts corresponding to the event_ids given.
  291. The dicts are mappings from (type, state_key) -> state_events
  292. """
  293. event_to_groups = yield self._get_state_group_for_events(
  294. event_ids,
  295. )
  296. groups = set(itervalues(event_to_groups))
  297. group_to_state = yield self._get_state_for_groups(groups, types)
  298. state_event_map = yield self.get_events(
  299. [ev_id for sd in itervalues(group_to_state) for ev_id in itervalues(sd)],
  300. get_prev_content=False
  301. )
  302. event_to_state = {
  303. event_id: {
  304. k: state_event_map[v]
  305. for k, v in iteritems(group_to_state[group])
  306. if v in state_event_map
  307. }
  308. for event_id, group in iteritems(event_to_groups)
  309. }
  310. defer.returnValue({event: event_to_state[event] for event in event_ids})
  311. @defer.inlineCallbacks
  312. def get_state_ids_for_events(self, event_ids, types=None):
  313. """
  314. Get the state dicts corresponding to a list of events
  315. Args:
  316. event_ids(list(str)): events whose state should be returned
  317. types(list[(str, str)]|None): List of (type, state_key) tuples
  318. which are used to filter the state fetched. May be None, which
  319. matches any key
  320. Returns:
  321. A deferred dict from event_id -> (type, state_key) -> state_event
  322. """
  323. event_to_groups = yield self._get_state_group_for_events(
  324. event_ids,
  325. )
  326. groups = set(itervalues(event_to_groups))
  327. group_to_state = yield self._get_state_for_groups(groups, types)
  328. event_to_state = {
  329. event_id: group_to_state[group]
  330. for event_id, group in iteritems(event_to_groups)
  331. }
  332. defer.returnValue({event: event_to_state[event] for event in event_ids})
  333. @defer.inlineCallbacks
  334. def get_state_for_event(self, event_id, types=None):
  335. """
  336. Get the state dict corresponding to a particular event
  337. Args:
  338. event_id(str): event whose state should be returned
  339. types(list[(str, str)]|None): List of (type, state_key) tuples
  340. which are used to filter the state fetched. May be None, which
  341. matches any key
  342. Returns:
  343. A deferred dict from (type, state_key) -> state_event
  344. """
  345. state_map = yield self.get_state_for_events([event_id], types)
  346. defer.returnValue(state_map[event_id])
  347. @defer.inlineCallbacks
  348. def get_state_ids_for_event(self, event_id, types=None):
  349. """
  350. Get the state dict corresponding to a particular event
  351. Args:
  352. event_id(str): event whose state should be returned
  353. types(list[(str, str)]|None): List of (type, state_key) tuples
  354. which are used to filter the state fetched. May be None, which
  355. matches any key
  356. Returns:
  357. A deferred dict from (type, state_key) -> state_event
  358. """
  359. state_map = yield self.get_state_ids_for_events([event_id], types)
  360. defer.returnValue(state_map[event_id])
  361. @cached(max_entries=50000)
  362. def _get_state_group_for_event(self, event_id):
  363. return self._simple_select_one_onecol(
  364. table="event_to_state_groups",
  365. keyvalues={
  366. "event_id": event_id,
  367. },
  368. retcol="state_group",
  369. allow_none=True,
  370. desc="_get_state_group_for_event",
  371. )
  372. @cachedList(cached_method_name="_get_state_group_for_event",
  373. list_name="event_ids", num_args=1, inlineCallbacks=True)
  374. def _get_state_group_for_events(self, event_ids):
  375. """Returns mapping event_id -> state_group
  376. """
  377. rows = yield self._simple_select_many_batch(
  378. table="event_to_state_groups",
  379. column="event_id",
  380. iterable=event_ids,
  381. keyvalues={},
  382. retcols=("event_id", "state_group",),
  383. desc="_get_state_group_for_events",
  384. )
  385. defer.returnValue({row["event_id"]: row["state_group"] for row in rows})
  386. def _get_some_state_from_cache(self, group, types):
  387. """Checks if group is in cache. See `_get_state_for_groups`
  388. Returns 3-tuple (`state_dict`, `missing_types`, `got_all`).
  389. `missing_types` is the list of types that aren't in the cache for that
  390. group. `got_all` is a bool indicating if we successfully retrieved all
  391. requests state from the cache, if False we need to query the DB for the
  392. missing state.
  393. Args:
  394. group: The state group to lookup
  395. types (list): List of 2-tuples of the form (`type`, `state_key`),
  396. where a `state_key` of `None` matches all state_keys for the
  397. `type`.
  398. """
  399. is_all, known_absent, state_dict_ids = self._state_group_cache.get(group)
  400. type_to_key = {}
  401. missing_types = set()
  402. for typ, state_key in types:
  403. key = (typ, state_key)
  404. if state_key is None:
  405. type_to_key[typ] = None
  406. missing_types.add(key)
  407. else:
  408. if type_to_key.get(typ, object()) is not None:
  409. type_to_key.setdefault(typ, set()).add(state_key)
  410. if key not in state_dict_ids and key not in known_absent:
  411. missing_types.add(key)
  412. sentinel = object()
  413. def include(typ, state_key):
  414. valid_state_keys = type_to_key.get(typ, sentinel)
  415. if valid_state_keys is sentinel:
  416. return False
  417. if valid_state_keys is None:
  418. return True
  419. if state_key in valid_state_keys:
  420. return True
  421. return False
  422. got_all = is_all or not missing_types
  423. return {
  424. k: v for k, v in iteritems(state_dict_ids)
  425. if include(k[0], k[1])
  426. }, missing_types, got_all
  427. def _get_all_state_from_cache(self, group):
  428. """Checks if group is in cache. See `_get_state_for_groups`
  429. Returns 2-tuple (`state_dict`, `got_all`). `got_all` is a bool
  430. indicating if we successfully retrieved all requests state from the
  431. cache, if False we need to query the DB for the missing state.
  432. Args:
  433. group: The state group to lookup
  434. """
  435. is_all, _, state_dict_ids = self._state_group_cache.get(group)
  436. return state_dict_ids, is_all
  437. @defer.inlineCallbacks
  438. def _get_state_for_groups(self, groups, types=None):
  439. """Given list of groups returns dict of group -> list of state events
  440. with matching types. `types` is a list of `(type, state_key)`, where
  441. a `state_key` of None matches all state_keys. If `types` is None then
  442. all events are returned.
  443. """
  444. if types:
  445. types = frozenset(types)
  446. results = {}
  447. missing_groups = []
  448. if types is not None:
  449. for group in set(groups):
  450. state_dict_ids, _, got_all = self._get_some_state_from_cache(
  451. group, types
  452. )
  453. results[group] = state_dict_ids
  454. if not got_all:
  455. missing_groups.append(group)
  456. else:
  457. for group in set(groups):
  458. state_dict_ids, got_all = self._get_all_state_from_cache(
  459. group
  460. )
  461. results[group] = state_dict_ids
  462. if not got_all:
  463. missing_groups.append(group)
  464. if missing_groups:
  465. # Okay, so we have some missing_types, lets fetch them.
  466. cache_seq_num = self._state_group_cache.sequence
  467. group_to_state_dict = yield self._get_state_groups_from_groups(
  468. missing_groups, types
  469. )
  470. # Now we want to update the cache with all the things we fetched
  471. # from the database.
  472. for group, group_state_dict in iteritems(group_to_state_dict):
  473. state_dict = results[group]
  474. state_dict.update(
  475. ((intern_string(k[0]), intern_string(k[1])), to_ascii(v))
  476. for k, v in iteritems(group_state_dict)
  477. )
  478. self._state_group_cache.update(
  479. cache_seq_num,
  480. key=group,
  481. value=state_dict,
  482. full=(types is None),
  483. known_absent=types,
  484. )
  485. defer.returnValue(results)
  486. def store_state_group(self, event_id, room_id, prev_group, delta_ids,
  487. current_state_ids):
  488. """Store a new set of state, returning a newly assigned state group.
  489. Args:
  490. event_id (str): The event ID for which the state was calculated
  491. room_id (str)
  492. prev_group (int|None): A previous state group for the room, optional.
  493. delta_ids (dict|None): The delta between state at `prev_group` and
  494. `current_state_ids`, if `prev_group` was given. Same format as
  495. `current_state_ids`.
  496. current_state_ids (dict): The state to store. Map of (type, state_key)
  497. to event_id.
  498. Returns:
  499. Deferred[int]: The state group ID
  500. """
  501. def _store_state_group_txn(txn):
  502. if current_state_ids is None:
  503. # AFAIK, this can never happen
  504. raise Exception("current_state_ids cannot be None")
  505. state_group = self.database_engine.get_next_state_group_id(txn)
  506. self._simple_insert_txn(
  507. txn,
  508. table="state_groups",
  509. values={
  510. "id": state_group,
  511. "room_id": room_id,
  512. "event_id": event_id,
  513. },
  514. )
  515. # We persist as a delta if we can, while also ensuring the chain
  516. # of deltas isn't tooo long, as otherwise read performance degrades.
  517. if prev_group:
  518. is_in_db = self._simple_select_one_onecol_txn(
  519. txn,
  520. table="state_groups",
  521. keyvalues={"id": prev_group},
  522. retcol="id",
  523. allow_none=True,
  524. )
  525. if not is_in_db:
  526. raise Exception(
  527. "Trying to persist state with unpersisted prev_group: %r"
  528. % (prev_group,)
  529. )
  530. potential_hops = self._count_state_group_hops_txn(
  531. txn, prev_group
  532. )
  533. if prev_group and potential_hops < MAX_STATE_DELTA_HOPS:
  534. self._simple_insert_txn(
  535. txn,
  536. table="state_group_edges",
  537. values={
  538. "state_group": state_group,
  539. "prev_state_group": prev_group,
  540. },
  541. )
  542. self._simple_insert_many_txn(
  543. txn,
  544. table="state_groups_state",
  545. values=[
  546. {
  547. "state_group": state_group,
  548. "room_id": room_id,
  549. "type": key[0],
  550. "state_key": key[1],
  551. "event_id": state_id,
  552. }
  553. for key, state_id in iteritems(delta_ids)
  554. ],
  555. )
  556. else:
  557. self._simple_insert_many_txn(
  558. txn,
  559. table="state_groups_state",
  560. values=[
  561. {
  562. "state_group": state_group,
  563. "room_id": room_id,
  564. "type": key[0],
  565. "state_key": key[1],
  566. "event_id": state_id,
  567. }
  568. for key, state_id in iteritems(current_state_ids)
  569. ],
  570. )
  571. # Prefill the state group cache with this group.
  572. # It's fine to use the sequence like this as the state group map
  573. # is immutable. (If the map wasn't immutable then this prefill could
  574. # race with another update)
  575. txn.call_after(
  576. self._state_group_cache.update,
  577. self._state_group_cache.sequence,
  578. key=state_group,
  579. value=dict(current_state_ids),
  580. full=True,
  581. )
  582. return state_group
  583. return self.runInteraction("store_state_group", _store_state_group_txn)
  584. def _count_state_group_hops_txn(self, txn, state_group):
  585. """Given a state group, count how many hops there are in the tree.
  586. This is used to ensure the delta chains don't get too long.
  587. """
  588. if isinstance(self.database_engine, PostgresEngine):
  589. sql = ("""
  590. WITH RECURSIVE state(state_group) AS (
  591. VALUES(?::bigint)
  592. UNION ALL
  593. SELECT prev_state_group FROM state_group_edges e, state s
  594. WHERE s.state_group = e.state_group
  595. )
  596. SELECT count(*) FROM state;
  597. """)
  598. txn.execute(sql, (state_group,))
  599. row = txn.fetchone()
  600. if row and row[0]:
  601. return row[0]
  602. else:
  603. return 0
  604. else:
  605. # We don't use WITH RECURSIVE on sqlite3 as there are distributions
  606. # that ship with an sqlite3 version that doesn't support it (e.g. wheezy)
  607. next_group = state_group
  608. count = 0
  609. while next_group:
  610. next_group = self._simple_select_one_onecol_txn(
  611. txn,
  612. table="state_group_edges",
  613. keyvalues={"state_group": next_group},
  614. retcol="prev_state_group",
  615. allow_none=True,
  616. )
  617. if next_group:
  618. count += 1
  619. return count
  620. class StateStore(StateGroupWorkerStore, BackgroundUpdateStore):
  621. """ Keeps track of the state at a given event.
  622. This is done by the concept of `state groups`. Every event is a assigned
  623. a state group (identified by an arbitrary string), which references a
  624. collection of state events. The current state of an event is then the
  625. collection of state events referenced by the event's state group.
  626. Hence, every change in the current state causes a new state group to be
  627. generated. However, if no change happens (e.g., if we get a message event
  628. with only one parent it inherits the state group from its parent.)
  629. There are three tables:
  630. * `state_groups`: Stores group name, first event with in the group and
  631. room id.
  632. * `event_to_state_groups`: Maps events to state groups.
  633. * `state_groups_state`: Maps state group to state events.
  634. """
  635. STATE_GROUP_DEDUPLICATION_UPDATE_NAME = "state_group_state_deduplication"
  636. STATE_GROUP_INDEX_UPDATE_NAME = "state_group_state_type_index"
  637. CURRENT_STATE_INDEX_UPDATE_NAME = "current_state_members_idx"
  638. def __init__(self, db_conn, hs):
  639. super(StateStore, self).__init__(db_conn, hs)
  640. self.register_background_update_handler(
  641. self.STATE_GROUP_DEDUPLICATION_UPDATE_NAME,
  642. self._background_deduplicate_state,
  643. )
  644. self.register_background_update_handler(
  645. self.STATE_GROUP_INDEX_UPDATE_NAME,
  646. self._background_index_state,
  647. )
  648. self.register_background_index_update(
  649. self.CURRENT_STATE_INDEX_UPDATE_NAME,
  650. index_name="current_state_events_member_index",
  651. table="current_state_events",
  652. columns=["state_key"],
  653. where_clause="type='m.room.member'",
  654. )
  655. def _store_event_state_mappings_txn(self, txn, events_and_contexts):
  656. state_groups = {}
  657. for event, context in events_and_contexts:
  658. if event.internal_metadata.is_outlier():
  659. continue
  660. # if the event was rejected, just give it the same state as its
  661. # predecessor.
  662. if context.rejected:
  663. state_groups[event.event_id] = context.prev_group
  664. continue
  665. state_groups[event.event_id] = context.state_group
  666. self._simple_insert_many_txn(
  667. txn,
  668. table="event_to_state_groups",
  669. values=[
  670. {
  671. "state_group": state_group_id,
  672. "event_id": event_id,
  673. }
  674. for event_id, state_group_id in iteritems(state_groups)
  675. ],
  676. )
  677. for event_id, state_group_id in iteritems(state_groups):
  678. txn.call_after(
  679. self._get_state_group_for_event.prefill,
  680. (event_id,), state_group_id
  681. )
  682. @defer.inlineCallbacks
  683. def _background_deduplicate_state(self, progress, batch_size):
  684. """This background update will slowly deduplicate state by reencoding
  685. them as deltas.
  686. """
  687. last_state_group = progress.get("last_state_group", 0)
  688. rows_inserted = progress.get("rows_inserted", 0)
  689. max_group = progress.get("max_group", None)
  690. BATCH_SIZE_SCALE_FACTOR = 100
  691. batch_size = max(1, int(batch_size / BATCH_SIZE_SCALE_FACTOR))
  692. if max_group is None:
  693. rows = yield self._execute(
  694. "_background_deduplicate_state", None,
  695. "SELECT coalesce(max(id), 0) FROM state_groups",
  696. )
  697. max_group = rows[0][0]
  698. def reindex_txn(txn):
  699. new_last_state_group = last_state_group
  700. for count in range(batch_size):
  701. txn.execute(
  702. "SELECT id, room_id FROM state_groups"
  703. " WHERE ? < id AND id <= ?"
  704. " ORDER BY id ASC"
  705. " LIMIT 1",
  706. (new_last_state_group, max_group,)
  707. )
  708. row = txn.fetchone()
  709. if row:
  710. state_group, room_id = row
  711. if not row or not state_group:
  712. return True, count
  713. txn.execute(
  714. "SELECT state_group FROM state_group_edges"
  715. " WHERE state_group = ?",
  716. (state_group,)
  717. )
  718. # If we reach a point where we've already started inserting
  719. # edges we should stop.
  720. if txn.fetchall():
  721. return True, count
  722. txn.execute(
  723. "SELECT coalesce(max(id), 0) FROM state_groups"
  724. " WHERE id < ? AND room_id = ?",
  725. (state_group, room_id,)
  726. )
  727. prev_group, = txn.fetchone()
  728. new_last_state_group = state_group
  729. if prev_group:
  730. potential_hops = self._count_state_group_hops_txn(
  731. txn, prev_group
  732. )
  733. if potential_hops >= MAX_STATE_DELTA_HOPS:
  734. # We want to ensure chains are at most this long,#
  735. # otherwise read performance degrades.
  736. continue
  737. prev_state = self._get_state_groups_from_groups_txn(
  738. txn, [prev_group], types=None
  739. )
  740. prev_state = prev_state[prev_group]
  741. curr_state = self._get_state_groups_from_groups_txn(
  742. txn, [state_group], types=None
  743. )
  744. curr_state = curr_state[state_group]
  745. if not set(prev_state.keys()) - set(curr_state.keys()):
  746. # We can only do a delta if the current has a strict super set
  747. # of keys
  748. delta_state = {
  749. key: value for key, value in iteritems(curr_state)
  750. if prev_state.get(key, None) != value
  751. }
  752. self._simple_delete_txn(
  753. txn,
  754. table="state_group_edges",
  755. keyvalues={
  756. "state_group": state_group,
  757. }
  758. )
  759. self._simple_insert_txn(
  760. txn,
  761. table="state_group_edges",
  762. values={
  763. "state_group": state_group,
  764. "prev_state_group": prev_group,
  765. }
  766. )
  767. self._simple_delete_txn(
  768. txn,
  769. table="state_groups_state",
  770. keyvalues={
  771. "state_group": state_group,
  772. }
  773. )
  774. self._simple_insert_many_txn(
  775. txn,
  776. table="state_groups_state",
  777. values=[
  778. {
  779. "state_group": state_group,
  780. "room_id": room_id,
  781. "type": key[0],
  782. "state_key": key[1],
  783. "event_id": state_id,
  784. }
  785. for key, state_id in iteritems(delta_state)
  786. ],
  787. )
  788. progress = {
  789. "last_state_group": state_group,
  790. "rows_inserted": rows_inserted + batch_size,
  791. "max_group": max_group,
  792. }
  793. self._background_update_progress_txn(
  794. txn, self.STATE_GROUP_DEDUPLICATION_UPDATE_NAME, progress
  795. )
  796. return False, batch_size
  797. finished, result = yield self.runInteraction(
  798. self.STATE_GROUP_DEDUPLICATION_UPDATE_NAME, reindex_txn
  799. )
  800. if finished:
  801. yield self._end_background_update(self.STATE_GROUP_DEDUPLICATION_UPDATE_NAME)
  802. defer.returnValue(result * BATCH_SIZE_SCALE_FACTOR)
  803. @defer.inlineCallbacks
  804. def _background_index_state(self, progress, batch_size):
  805. def reindex_txn(conn):
  806. conn.rollback()
  807. if isinstance(self.database_engine, PostgresEngine):
  808. # postgres insists on autocommit for the index
  809. conn.set_session(autocommit=True)
  810. try:
  811. txn = conn.cursor()
  812. txn.execute(
  813. "CREATE INDEX CONCURRENTLY state_groups_state_type_idx"
  814. " ON state_groups_state(state_group, type, state_key)"
  815. )
  816. txn.execute(
  817. "DROP INDEX IF EXISTS state_groups_state_id"
  818. )
  819. finally:
  820. conn.set_session(autocommit=False)
  821. else:
  822. txn = conn.cursor()
  823. txn.execute(
  824. "CREATE INDEX state_groups_state_type_idx"
  825. " ON state_groups_state(state_group, type, state_key)"
  826. )
  827. txn.execute(
  828. "DROP INDEX IF EXISTS state_groups_state_id"
  829. )
  830. yield self.runWithConnection(reindex_txn)
  831. yield self._end_background_update(self.STATE_GROUP_INDEX_UPDATE_NAME)
  832. defer.returnValue(1)