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.
 
 
 
 
 
 

944 line
35 KiB

  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 itertools
  16. import logging
  17. from queue import Empty, PriorityQueue
  18. from typing import Dict, Iterable, List, Set, Tuple
  19. from synapse.api.errors import StoreError
  20. from synapse.events import EventBase
  21. from synapse.metrics.background_process_metrics import wrap_as_background_process
  22. from synapse.storage._base import SQLBaseStore, make_in_list_sql_clause
  23. from synapse.storage.database import DatabasePool, LoggingTransaction
  24. from synapse.storage.databases.main.events_worker import EventsWorkerStore
  25. from synapse.storage.databases.main.signatures import SignatureWorkerStore
  26. from synapse.storage.engines import PostgresEngine
  27. from synapse.storage.types import Cursor
  28. from synapse.types import Collection
  29. from synapse.util.caches.descriptors import cached
  30. from synapse.util.caches.lrucache import LruCache
  31. from synapse.util.iterutils import batch_iter
  32. logger = logging.getLogger(__name__)
  33. class _NoChainCoverIndex(Exception):
  34. def __init__(self, room_id: str):
  35. super().__init__("Unexpectedly no chain cover for events in %s" % (room_id,))
  36. class EventFederationWorkerStore(EventsWorkerStore, SignatureWorkerStore, SQLBaseStore):
  37. def __init__(self, database: DatabasePool, db_conn, hs):
  38. super().__init__(database, db_conn, hs)
  39. if hs.config.run_background_tasks:
  40. hs.get_clock().looping_call(
  41. self._delete_old_forward_extrem_cache, 60 * 60 * 1000
  42. )
  43. # Cache of event ID to list of auth event IDs and their depths.
  44. self._event_auth_cache = LruCache(
  45. 500000, "_event_auth_cache", size_callback=len
  46. ) # type: LruCache[str, List[Tuple[str, int]]]
  47. async def get_auth_chain(
  48. self, event_ids: Collection[str], include_given: bool = False
  49. ) -> List[EventBase]:
  50. """Get auth events for given event_ids. The events *must* be state events.
  51. Args:
  52. event_ids: state events
  53. include_given: include the given events in result
  54. Returns:
  55. list of events
  56. """
  57. event_ids = await self.get_auth_chain_ids(
  58. event_ids, include_given=include_given
  59. )
  60. return await self.get_events_as_list(event_ids)
  61. async def get_auth_chain_ids(
  62. self, event_ids: Collection[str], include_given: bool = False,
  63. ) -> List[str]:
  64. """Get auth events for given event_ids. The events *must* be state events.
  65. Args:
  66. event_ids: state events
  67. include_given: include the given events in result
  68. Returns:
  69. An awaitable which resolve to a list of event_ids
  70. """
  71. return await self.db_pool.runInteraction(
  72. "get_auth_chain_ids",
  73. self._get_auth_chain_ids_txn,
  74. event_ids,
  75. include_given,
  76. )
  77. def _get_auth_chain_ids_txn(
  78. self, txn: LoggingTransaction, event_ids: Collection[str], include_given: bool
  79. ) -> List[str]:
  80. if include_given:
  81. results = set(event_ids)
  82. else:
  83. results = set()
  84. # We pull out the depth simply so that we can populate the
  85. # `_event_auth_cache` cache.
  86. base_sql = """
  87. SELECT a.event_id, auth_id, depth
  88. FROM event_auth AS a
  89. INNER JOIN events AS e ON (e.event_id = a.auth_id)
  90. WHERE
  91. """
  92. front = set(event_ids)
  93. while front:
  94. new_front = set()
  95. for chunk in batch_iter(front, 100):
  96. # Pull the auth events either from the cache or DB.
  97. to_fetch = [] # Event IDs to fetch from DB # type: List[str]
  98. for event_id in chunk:
  99. res = self._event_auth_cache.get(event_id)
  100. if res is None:
  101. to_fetch.append(event_id)
  102. else:
  103. new_front.update(auth_id for auth_id, depth in res)
  104. if to_fetch:
  105. clause, args = make_in_list_sql_clause(
  106. txn.database_engine, "a.event_id", to_fetch
  107. )
  108. txn.execute(base_sql + clause, args)
  109. # Note we need to batch up the results by event ID before
  110. # adding to the cache.
  111. to_cache = {}
  112. for event_id, auth_event_id, auth_event_depth in txn:
  113. to_cache.setdefault(event_id, []).append(
  114. (auth_event_id, auth_event_depth)
  115. )
  116. new_front.add(auth_event_id)
  117. for event_id, auth_events in to_cache.items():
  118. self._event_auth_cache.set(event_id, auth_events)
  119. new_front -= results
  120. front = new_front
  121. results.update(front)
  122. return list(results)
  123. async def get_auth_chain_difference(
  124. self, room_id: str, state_sets: List[Set[str]]
  125. ) -> Set[str]:
  126. """Given sets of state events figure out the auth chain difference (as
  127. per state res v2 algorithm).
  128. This equivalent to fetching the full auth chain for each set of state
  129. and returning the events that don't appear in each and every auth
  130. chain.
  131. Returns:
  132. The set of the difference in auth chains.
  133. """
  134. # Check if we have indexed the room so we can use the chain cover
  135. # algorithm.
  136. room = await self.get_room(room_id)
  137. if room["has_auth_chain_index"]:
  138. try:
  139. return await self.db_pool.runInteraction(
  140. "get_auth_chain_difference_chains",
  141. self._get_auth_chain_difference_using_cover_index_txn,
  142. room_id,
  143. state_sets,
  144. )
  145. except _NoChainCoverIndex:
  146. # For whatever reason we don't actually have a chain cover index
  147. # for the events in question, so we fall back to the old method.
  148. pass
  149. return await self.db_pool.runInteraction(
  150. "get_auth_chain_difference",
  151. self._get_auth_chain_difference_txn,
  152. state_sets,
  153. )
  154. def _get_auth_chain_difference_using_cover_index_txn(
  155. self, txn: Cursor, room_id: str, state_sets: List[Set[str]]
  156. ) -> Set[str]:
  157. """Calculates the auth chain difference using the chain index.
  158. See docs/auth_chain_difference_algorithm.md for details
  159. """
  160. # First we look up the chain ID/sequence numbers for all the events, and
  161. # work out the chain/sequence numbers reachable from each state set.
  162. initial_events = set(state_sets[0]).union(*state_sets[1:])
  163. # Map from event_id -> (chain ID, seq no)
  164. chain_info = {} # type: Dict[str, Tuple[int, int]]
  165. # Map from chain ID -> seq no -> event Id
  166. chain_to_event = {} # type: Dict[int, Dict[int, str]]
  167. # All the chains that we've found that are reachable from the state
  168. # sets.
  169. seen_chains = set() # type: Set[int]
  170. sql = """
  171. SELECT event_id, chain_id, sequence_number
  172. FROM event_auth_chains
  173. WHERE %s
  174. """
  175. for batch in batch_iter(initial_events, 1000):
  176. clause, args = make_in_list_sql_clause(
  177. txn.database_engine, "event_id", batch
  178. )
  179. txn.execute(sql % (clause,), args)
  180. for event_id, chain_id, sequence_number in txn:
  181. chain_info[event_id] = (chain_id, sequence_number)
  182. seen_chains.add(chain_id)
  183. chain_to_event.setdefault(chain_id, {})[sequence_number] = event_id
  184. # Check that we actually have a chain ID for all the events.
  185. events_missing_chain_info = initial_events.difference(chain_info)
  186. if events_missing_chain_info:
  187. # This can happen due to e.g. downgrade/upgrade of the server. We
  188. # raise an exception and fall back to the previous algorithm.
  189. logger.info(
  190. "Unexpectedly found that events don't have chain IDs in room %s: %s",
  191. room_id,
  192. events_missing_chain_info,
  193. )
  194. raise _NoChainCoverIndex(room_id)
  195. # Corresponds to `state_sets`, except as a map from chain ID to max
  196. # sequence number reachable from the state set.
  197. set_to_chain = [] # type: List[Dict[int, int]]
  198. for state_set in state_sets:
  199. chains = {} # type: Dict[int, int]
  200. set_to_chain.append(chains)
  201. for event_id in state_set:
  202. chain_id, seq_no = chain_info[event_id]
  203. chains[chain_id] = max(seq_no, chains.get(chain_id, 0))
  204. # Now we look up all links for the chains we have, adding chains to
  205. # set_to_chain that are reachable from each set.
  206. sql = """
  207. SELECT
  208. origin_chain_id, origin_sequence_number,
  209. target_chain_id, target_sequence_number
  210. FROM event_auth_chain_links
  211. WHERE %s
  212. """
  213. # (We need to take a copy of `seen_chains` as we want to mutate it in
  214. # the loop)
  215. for batch in batch_iter(set(seen_chains), 1000):
  216. clause, args = make_in_list_sql_clause(
  217. txn.database_engine, "origin_chain_id", batch
  218. )
  219. txn.execute(sql % (clause,), args)
  220. for (
  221. origin_chain_id,
  222. origin_sequence_number,
  223. target_chain_id,
  224. target_sequence_number,
  225. ) in txn:
  226. for chains in set_to_chain:
  227. # chains are only reachable if the origin sequence number of
  228. # the link is less than the max sequence number in the
  229. # origin chain.
  230. if origin_sequence_number <= chains.get(origin_chain_id, 0):
  231. chains[target_chain_id] = max(
  232. target_sequence_number, chains.get(target_chain_id, 0),
  233. )
  234. seen_chains.add(target_chain_id)
  235. # Now for each chain we figure out the maximum sequence number reachable
  236. # from *any* state set and the minimum sequence number reachable from
  237. # *all* state sets. Events in that range are in the auth chain
  238. # difference.
  239. result = set()
  240. # Mapping from chain ID to the range of sequence numbers that should be
  241. # pulled from the database.
  242. chain_to_gap = {} # type: Dict[int, Tuple[int, int]]
  243. for chain_id in seen_chains:
  244. min_seq_no = min(chains.get(chain_id, 0) for chains in set_to_chain)
  245. max_seq_no = max(chains.get(chain_id, 0) for chains in set_to_chain)
  246. if min_seq_no < max_seq_no:
  247. # We have a non empty gap, try and fill it from the events that
  248. # we have, otherwise add them to the list of gaps to pull out
  249. # from the DB.
  250. for seq_no in range(min_seq_no + 1, max_seq_no + 1):
  251. event_id = chain_to_event.get(chain_id, {}).get(seq_no)
  252. if event_id:
  253. result.add(event_id)
  254. else:
  255. chain_to_gap[chain_id] = (min_seq_no, max_seq_no)
  256. break
  257. if not chain_to_gap:
  258. # If there are no gaps to fetch, we're done!
  259. return result
  260. if isinstance(self.database_engine, PostgresEngine):
  261. # We can use `execute_values` to efficiently fetch the gaps when
  262. # using postgres.
  263. sql = """
  264. SELECT event_id
  265. FROM event_auth_chains AS c, (VALUES ?) AS l(chain_id, min_seq, max_seq)
  266. WHERE
  267. c.chain_id = l.chain_id
  268. AND min_seq < sequence_number AND sequence_number <= max_seq
  269. """
  270. args = [
  271. (chain_id, min_no, max_no)
  272. for chain_id, (min_no, max_no) in chain_to_gap.items()
  273. ]
  274. rows = txn.execute_values(sql, args)
  275. result.update(r for r, in rows)
  276. else:
  277. # For SQLite we just fall back to doing a noddy for loop.
  278. sql = """
  279. SELECT event_id FROM event_auth_chains
  280. WHERE chain_id = ? AND ? < sequence_number AND sequence_number <= ?
  281. """
  282. for chain_id, (min_no, max_no) in chain_to_gap.items():
  283. txn.execute(sql, (chain_id, min_no, max_no))
  284. result.update(r for r, in txn)
  285. return result
  286. def _get_auth_chain_difference_txn(
  287. self, txn, state_sets: List[Set[str]]
  288. ) -> Set[str]:
  289. """Calculates the auth chain difference using a breadth first search.
  290. This is used when we don't have a cover index for the room.
  291. """
  292. # Algorithm Description
  293. # ~~~~~~~~~~~~~~~~~~~~~
  294. #
  295. # The idea here is to basically walk the auth graph of each state set in
  296. # tandem, keeping track of which auth events are reachable by each state
  297. # set. If we reach an auth event we've already visited (via a different
  298. # state set) then we mark that auth event and all ancestors as reachable
  299. # by the state set. This requires that we keep track of the auth chains
  300. # in memory.
  301. #
  302. # Doing it in a such a way means that we can stop early if all auth
  303. # events we're currently walking are reachable by all state sets.
  304. #
  305. # *Note*: We can't stop walking an event's auth chain if it is reachable
  306. # by all state sets. This is because other auth chains we're walking
  307. # might be reachable only via the original auth chain. For example,
  308. # given the following auth chain:
  309. #
  310. # A -> C -> D -> E
  311. # / /
  312. # B -´---------´
  313. #
  314. # and state sets {A} and {B} then walking the auth chains of A and B
  315. # would immediately show that C is reachable by both. However, if we
  316. # stopped at C then we'd only reach E via the auth chain of B and so E
  317. # would errornously get included in the returned difference.
  318. #
  319. # The other thing that we do is limit the number of auth chains we walk
  320. # at once, due to practical limits (i.e. we can only query the database
  321. # with a limited set of parameters). We pick the auth chains we walk
  322. # each iteration based on their depth, in the hope that events with a
  323. # lower depth are likely reachable by those with higher depths.
  324. #
  325. # We could use any ordering that we believe would give a rough
  326. # topological ordering, e.g. origin server timestamp. If the ordering
  327. # chosen is not topological then the algorithm still produces the right
  328. # result, but perhaps a bit more inefficiently. This is why it is safe
  329. # to use "depth" here.
  330. initial_events = set(state_sets[0]).union(*state_sets[1:])
  331. # Dict from events in auth chains to which sets *cannot* reach them.
  332. # I.e. if the set is empty then all sets can reach the event.
  333. event_to_missing_sets = {
  334. event_id: {i for i, a in enumerate(state_sets) if event_id not in a}
  335. for event_id in initial_events
  336. }
  337. # The sorted list of events whose auth chains we should walk.
  338. search = [] # type: List[Tuple[int, str]]
  339. # We need to get the depth of the initial events for sorting purposes.
  340. sql = """
  341. SELECT depth, event_id FROM events
  342. WHERE %s
  343. """
  344. # the list can be huge, so let's avoid looking them all up in one massive
  345. # query.
  346. for batch in batch_iter(initial_events, 1000):
  347. clause, args = make_in_list_sql_clause(
  348. txn.database_engine, "event_id", batch
  349. )
  350. txn.execute(sql % (clause,), args)
  351. # I think building a temporary list with fetchall is more efficient than
  352. # just `search.extend(txn)`, but this is unconfirmed
  353. search.extend(txn.fetchall())
  354. # sort by depth
  355. search.sort()
  356. # Map from event to its auth events
  357. event_to_auth_events = {} # type: Dict[str, Set[str]]
  358. base_sql = """
  359. SELECT a.event_id, auth_id, depth
  360. FROM event_auth AS a
  361. INNER JOIN events AS e ON (e.event_id = a.auth_id)
  362. WHERE
  363. """
  364. while search:
  365. # Check whether all our current walks are reachable by all state
  366. # sets. If so we can bail.
  367. if all(not event_to_missing_sets[eid] for _, eid in search):
  368. break
  369. # Fetch the auth events and their depths of the N last events we're
  370. # currently walking, either from cache or DB.
  371. search, chunk = search[:-100], search[-100:]
  372. found = [] # Results found # type: List[Tuple[str, str, int]]
  373. to_fetch = [] # Event IDs to fetch from DB # type: List[str]
  374. for _, event_id in chunk:
  375. res = self._event_auth_cache.get(event_id)
  376. if res is None:
  377. to_fetch.append(event_id)
  378. else:
  379. found.extend((event_id, auth_id, depth) for auth_id, depth in res)
  380. if to_fetch:
  381. clause, args = make_in_list_sql_clause(
  382. txn.database_engine, "a.event_id", to_fetch
  383. )
  384. txn.execute(base_sql + clause, args)
  385. # We parse the results and add the to the `found` set and the
  386. # cache (note we need to batch up the results by event ID before
  387. # adding to the cache).
  388. to_cache = {}
  389. for event_id, auth_event_id, auth_event_depth in txn:
  390. to_cache.setdefault(event_id, []).append(
  391. (auth_event_id, auth_event_depth)
  392. )
  393. found.append((event_id, auth_event_id, auth_event_depth))
  394. for event_id, auth_events in to_cache.items():
  395. self._event_auth_cache.set(event_id, auth_events)
  396. for event_id, auth_event_id, auth_event_depth in found:
  397. event_to_auth_events.setdefault(event_id, set()).add(auth_event_id)
  398. sets = event_to_missing_sets.get(auth_event_id)
  399. if sets is None:
  400. # First time we're seeing this event, so we add it to the
  401. # queue of things to fetch.
  402. search.append((auth_event_depth, auth_event_id))
  403. # Assume that this event is unreachable from any of the
  404. # state sets until proven otherwise
  405. sets = event_to_missing_sets[auth_event_id] = set(
  406. range(len(state_sets))
  407. )
  408. else:
  409. # We've previously seen this event, so look up its auth
  410. # events and recursively mark all ancestors as reachable
  411. # by the current event's state set.
  412. a_ids = event_to_auth_events.get(auth_event_id)
  413. while a_ids:
  414. new_aids = set()
  415. for a_id in a_ids:
  416. event_to_missing_sets[a_id].intersection_update(
  417. event_to_missing_sets[event_id]
  418. )
  419. b = event_to_auth_events.get(a_id)
  420. if b:
  421. new_aids.update(b)
  422. a_ids = new_aids
  423. # Mark that the auth event is reachable by the approriate sets.
  424. sets.intersection_update(event_to_missing_sets[event_id])
  425. search.sort()
  426. # Return all events where not all sets can reach them.
  427. return {eid for eid, n in event_to_missing_sets.items() if n}
  428. async def get_oldest_events_with_depth_in_room(self, room_id):
  429. return await self.db_pool.runInteraction(
  430. "get_oldest_events_with_depth_in_room",
  431. self.get_oldest_events_with_depth_in_room_txn,
  432. room_id,
  433. )
  434. def get_oldest_events_with_depth_in_room_txn(self, txn, room_id):
  435. sql = (
  436. "SELECT b.event_id, MAX(e.depth) FROM events as e"
  437. " INNER JOIN event_edges as g"
  438. " ON g.event_id = e.event_id"
  439. " INNER JOIN event_backward_extremities as b"
  440. " ON g.prev_event_id = b.event_id"
  441. " WHERE b.room_id = ? AND g.is_state is ?"
  442. " GROUP BY b.event_id"
  443. )
  444. txn.execute(sql, (room_id, False))
  445. return dict(txn)
  446. async def get_max_depth_of(self, event_ids: List[str]) -> int:
  447. """Returns the max depth of a set of event IDs
  448. Args:
  449. event_ids: The event IDs to calculate the max depth of.
  450. """
  451. rows = await self.db_pool.simple_select_many_batch(
  452. table="events",
  453. column="event_id",
  454. iterable=event_ids,
  455. retcols=("depth",),
  456. desc="get_max_depth_of",
  457. )
  458. if not rows:
  459. return 0
  460. else:
  461. return max(row["depth"] for row in rows)
  462. async def get_prev_events_for_room(self, room_id: str) -> List[str]:
  463. """
  464. Gets a subset of the current forward extremities in the given room.
  465. Limits the result to 10 extremities, so that we can avoid creating
  466. events which refer to hundreds of prev_events.
  467. Args:
  468. room_id: room_id
  469. Returns:
  470. The event ids of the forward extremities.
  471. """
  472. return await self.db_pool.runInteraction(
  473. "get_prev_events_for_room", self._get_prev_events_for_room_txn, room_id
  474. )
  475. def _get_prev_events_for_room_txn(self, txn, room_id: str):
  476. # we just use the 10 newest events. Older events will become
  477. # prev_events of future events.
  478. sql = """
  479. SELECT e.event_id FROM event_forward_extremities AS f
  480. INNER JOIN events AS e USING (event_id)
  481. WHERE f.room_id = ?
  482. ORDER BY e.depth DESC
  483. LIMIT 10
  484. """
  485. txn.execute(sql, (room_id,))
  486. return [row[0] for row in txn]
  487. async def get_rooms_with_many_extremities(
  488. self, min_count: int, limit: int, room_id_filter: Iterable[str]
  489. ) -> List[str]:
  490. """Get the top rooms with at least N extremities.
  491. Args:
  492. min_count: The minimum number of extremities
  493. limit: The maximum number of rooms to return.
  494. room_id_filter: room_ids to exclude from the results
  495. Returns:
  496. At most `limit` room IDs that have at least `min_count` extremities,
  497. sorted by extremity count.
  498. """
  499. def _get_rooms_with_many_extremities_txn(txn):
  500. where_clause = "1=1"
  501. if room_id_filter:
  502. where_clause = "room_id NOT IN (%s)" % (
  503. ",".join("?" for _ in room_id_filter),
  504. )
  505. sql = """
  506. SELECT room_id FROM event_forward_extremities
  507. WHERE %s
  508. GROUP BY room_id
  509. HAVING count(*) > ?
  510. ORDER BY count(*) DESC
  511. LIMIT ?
  512. """ % (
  513. where_clause,
  514. )
  515. query_args = list(itertools.chain(room_id_filter, [min_count, limit]))
  516. txn.execute(sql, query_args)
  517. return [room_id for room_id, in txn]
  518. return await self.db_pool.runInteraction(
  519. "get_rooms_with_many_extremities", _get_rooms_with_many_extremities_txn
  520. )
  521. @cached(max_entries=5000, iterable=True)
  522. async def get_latest_event_ids_in_room(self, room_id: str) -> List[str]:
  523. return await self.db_pool.simple_select_onecol(
  524. table="event_forward_extremities",
  525. keyvalues={"room_id": room_id},
  526. retcol="event_id",
  527. desc="get_latest_event_ids_in_room",
  528. )
  529. async def get_min_depth(self, room_id: str) -> int:
  530. """For the given room, get the minimum depth we have seen for it.
  531. """
  532. return await self.db_pool.runInteraction(
  533. "get_min_depth", self._get_min_depth_interaction, room_id
  534. )
  535. def _get_min_depth_interaction(self, txn, room_id):
  536. min_depth = self.db_pool.simple_select_one_onecol_txn(
  537. txn,
  538. table="room_depth",
  539. keyvalues={"room_id": room_id},
  540. retcol="min_depth",
  541. allow_none=True,
  542. )
  543. return int(min_depth) if min_depth is not None else None
  544. async def get_forward_extremeties_for_room(
  545. self, room_id: str, stream_ordering: int
  546. ) -> List[str]:
  547. """For a given room_id and stream_ordering, return the forward
  548. extremeties of the room at that point in "time".
  549. Throws a StoreError if we have since purged the index for
  550. stream_orderings from that point.
  551. Args:
  552. room_id:
  553. stream_ordering:
  554. Returns:
  555. A list of event_ids
  556. """
  557. # We want to make the cache more effective, so we clamp to the last
  558. # change before the given ordering.
  559. last_change = self._events_stream_cache.get_max_pos_of_last_change(room_id)
  560. # We don't always have a full stream_to_exterm_id table, e.g. after
  561. # the upgrade that introduced it, so we make sure we never ask for a
  562. # stream_ordering from before a restart
  563. last_change = max(self._stream_order_on_start, last_change)
  564. # provided the last_change is recent enough, we now clamp the requested
  565. # stream_ordering to it.
  566. if last_change > self.stream_ordering_month_ago:
  567. stream_ordering = min(last_change, stream_ordering)
  568. return await self._get_forward_extremeties_for_room(room_id, stream_ordering)
  569. @cached(max_entries=5000, num_args=2)
  570. async def _get_forward_extremeties_for_room(self, room_id, stream_ordering):
  571. """For a given room_id and stream_ordering, return the forward
  572. extremeties of the room at that point in "time".
  573. Throws a StoreError if we have since purged the index for
  574. stream_orderings from that point.
  575. """
  576. if stream_ordering <= self.stream_ordering_month_ago:
  577. raise StoreError(400, "stream_ordering too old %s" % (stream_ordering,))
  578. sql = """
  579. SELECT event_id FROM stream_ordering_to_exterm
  580. INNER JOIN (
  581. SELECT room_id, MAX(stream_ordering) AS stream_ordering
  582. FROM stream_ordering_to_exterm
  583. WHERE stream_ordering <= ? GROUP BY room_id
  584. ) AS rms USING (room_id, stream_ordering)
  585. WHERE room_id = ?
  586. """
  587. def get_forward_extremeties_for_room_txn(txn):
  588. txn.execute(sql, (stream_ordering, room_id))
  589. return [event_id for event_id, in txn]
  590. return await self.db_pool.runInteraction(
  591. "get_forward_extremeties_for_room", get_forward_extremeties_for_room_txn
  592. )
  593. async def get_backfill_events(self, room_id: str, event_list: list, limit: int):
  594. """Get a list of Events for a given topic that occurred before (and
  595. including) the events in event_list. Return a list of max size `limit`
  596. Args:
  597. room_id
  598. event_list
  599. limit
  600. """
  601. event_ids = await self.db_pool.runInteraction(
  602. "get_backfill_events",
  603. self._get_backfill_events,
  604. room_id,
  605. event_list,
  606. limit,
  607. )
  608. events = await self.get_events_as_list(event_ids)
  609. return sorted(events, key=lambda e: -e.depth)
  610. def _get_backfill_events(self, txn, room_id, event_list, limit):
  611. logger.debug("_get_backfill_events: %s, %r, %s", room_id, event_list, limit)
  612. event_results = set()
  613. # We want to make sure that we do a breadth-first, "depth" ordered
  614. # search.
  615. query = (
  616. "SELECT depth, prev_event_id FROM event_edges"
  617. " INNER JOIN events"
  618. " ON prev_event_id = events.event_id"
  619. " WHERE event_edges.event_id = ?"
  620. " AND event_edges.is_state = ?"
  621. " LIMIT ?"
  622. )
  623. queue = PriorityQueue()
  624. for event_id in event_list:
  625. depth = self.db_pool.simple_select_one_onecol_txn(
  626. txn,
  627. table="events",
  628. keyvalues={"event_id": event_id, "room_id": room_id},
  629. retcol="depth",
  630. allow_none=True,
  631. )
  632. if depth:
  633. queue.put((-depth, event_id))
  634. while not queue.empty() and len(event_results) < limit:
  635. try:
  636. _, event_id = queue.get_nowait()
  637. except Empty:
  638. break
  639. if event_id in event_results:
  640. continue
  641. event_results.add(event_id)
  642. txn.execute(query, (event_id, False, limit - len(event_results)))
  643. for row in txn:
  644. if row[1] not in event_results:
  645. queue.put((-row[0], row[1]))
  646. return event_results
  647. async def get_missing_events(self, room_id, earliest_events, latest_events, limit):
  648. ids = await self.db_pool.runInteraction(
  649. "get_missing_events",
  650. self._get_missing_events,
  651. room_id,
  652. earliest_events,
  653. latest_events,
  654. limit,
  655. )
  656. return await self.get_events_as_list(ids)
  657. def _get_missing_events(self, txn, room_id, earliest_events, latest_events, limit):
  658. seen_events = set(earliest_events)
  659. front = set(latest_events) - seen_events
  660. event_results = []
  661. query = (
  662. "SELECT prev_event_id FROM event_edges "
  663. "WHERE room_id = ? AND event_id = ? AND is_state = ? "
  664. "LIMIT ?"
  665. )
  666. while front and len(event_results) < limit:
  667. new_front = set()
  668. for event_id in front:
  669. txn.execute(
  670. query, (room_id, event_id, False, limit - len(event_results))
  671. )
  672. new_results = {t[0] for t in txn} - seen_events
  673. new_front |= new_results
  674. seen_events |= new_results
  675. event_results.extend(new_results)
  676. front = new_front
  677. # we built the list working backwards from latest_events; we now need to
  678. # reverse it so that the events are approximately chronological.
  679. event_results.reverse()
  680. return event_results
  681. async def get_successor_events(self, event_ids: Iterable[str]) -> List[str]:
  682. """Fetch all events that have the given events as a prev event
  683. Args:
  684. event_ids: The events to use as the previous events.
  685. """
  686. rows = await self.db_pool.simple_select_many_batch(
  687. table="event_edges",
  688. column="prev_event_id",
  689. iterable=event_ids,
  690. retcols=("event_id",),
  691. desc="get_successor_events",
  692. )
  693. return [row["event_id"] for row in rows]
  694. @wrap_as_background_process("delete_old_forward_extrem_cache")
  695. async def _delete_old_forward_extrem_cache(self) -> None:
  696. def _delete_old_forward_extrem_cache_txn(txn):
  697. # Delete entries older than a month, while making sure we don't delete
  698. # the only entries for a room.
  699. sql = """
  700. DELETE FROM stream_ordering_to_exterm
  701. WHERE
  702. room_id IN (
  703. SELECT room_id
  704. FROM stream_ordering_to_exterm
  705. WHERE stream_ordering > ?
  706. ) AND stream_ordering < ?
  707. """
  708. txn.execute(
  709. sql, (self.stream_ordering_month_ago, self.stream_ordering_month_ago)
  710. )
  711. await self.db_pool.runInteraction(
  712. "_delete_old_forward_extrem_cache", _delete_old_forward_extrem_cache_txn,
  713. )
  714. class EventFederationStore(EventFederationWorkerStore):
  715. """ Responsible for storing and serving up the various graphs associated
  716. with an event. Including the main event graph and the auth chains for an
  717. event.
  718. Also has methods for getting the front (latest) and back (oldest) edges
  719. of the event graphs. These are used to generate the parents for new events
  720. and backfilling from another server respectively.
  721. """
  722. EVENT_AUTH_STATE_ONLY = "event_auth_state_only"
  723. def __init__(self, database: DatabasePool, db_conn, hs):
  724. super().__init__(database, db_conn, hs)
  725. self.db_pool.updates.register_background_update_handler(
  726. self.EVENT_AUTH_STATE_ONLY, self._background_delete_non_state_event_auth
  727. )
  728. async def clean_room_for_join(self, room_id):
  729. return await self.db_pool.runInteraction(
  730. "clean_room_for_join", self._clean_room_for_join_txn, room_id
  731. )
  732. def _clean_room_for_join_txn(self, txn, room_id):
  733. query = "DELETE FROM event_forward_extremities WHERE room_id = ?"
  734. txn.execute(query, (room_id,))
  735. txn.call_after(self.get_latest_event_ids_in_room.invalidate, (room_id,))
  736. async def _background_delete_non_state_event_auth(self, progress, batch_size):
  737. def delete_event_auth(txn):
  738. target_min_stream_id = progress.get("target_min_stream_id_inclusive")
  739. max_stream_id = progress.get("max_stream_id_exclusive")
  740. if not target_min_stream_id or not max_stream_id:
  741. txn.execute("SELECT COALESCE(MIN(stream_ordering), 0) FROM events")
  742. rows = txn.fetchall()
  743. target_min_stream_id = rows[0][0]
  744. txn.execute("SELECT COALESCE(MAX(stream_ordering), 0) FROM events")
  745. rows = txn.fetchall()
  746. max_stream_id = rows[0][0]
  747. min_stream_id = max_stream_id - batch_size
  748. sql = """
  749. DELETE FROM event_auth
  750. WHERE event_id IN (
  751. SELECT event_id FROM events
  752. LEFT JOIN state_events USING (room_id, event_id)
  753. WHERE ? <= stream_ordering AND stream_ordering < ?
  754. AND state_key IS null
  755. )
  756. """
  757. txn.execute(sql, (min_stream_id, max_stream_id))
  758. new_progress = {
  759. "target_min_stream_id_inclusive": target_min_stream_id,
  760. "max_stream_id_exclusive": min_stream_id,
  761. }
  762. self.db_pool.updates._background_update_progress_txn(
  763. txn, self.EVENT_AUTH_STATE_ONLY, new_progress
  764. )
  765. return min_stream_id >= target_min_stream_id
  766. result = await self.db_pool.runInteraction(
  767. self.EVENT_AUTH_STATE_ONLY, delete_event_auth
  768. )
  769. if not result:
  770. await self.db_pool.updates._end_background_update(
  771. self.EVENT_AUTH_STATE_ONLY
  772. )
  773. return batch_size