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.
 
 
 
 
 
 

2460 lines
95 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018-2019 New Vector Ltd
  3. # Copyright 2019-2021 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import itertools
  17. import logging
  18. from collections import OrderedDict
  19. from typing import (
  20. TYPE_CHECKING,
  21. Any,
  22. Collection,
  23. Dict,
  24. Generator,
  25. Iterable,
  26. List,
  27. Optional,
  28. Set,
  29. Tuple,
  30. cast,
  31. )
  32. import attr
  33. from prometheus_client import Counter
  34. import synapse.metrics
  35. from synapse.api.constants import EventContentFields, EventTypes, RelationTypes
  36. from synapse.api.errors import PartialStateConflictError
  37. from synapse.api.room_versions import RoomVersions
  38. from synapse.events import EventBase, relation_from_event
  39. from synapse.events.snapshot import EventContext
  40. from synapse.logging.opentracing import trace
  41. from synapse.storage._base import db_to_json, make_in_list_sql_clause
  42. from synapse.storage.database import (
  43. DatabasePool,
  44. LoggingDatabaseConnection,
  45. LoggingTransaction,
  46. )
  47. from synapse.storage.databases.main.events_worker import EventCacheEntry
  48. from synapse.storage.databases.main.search import SearchEntry
  49. from synapse.storage.engines import PostgresEngine
  50. from synapse.storage.util.id_generators import AbstractStreamIdGenerator
  51. from synapse.storage.util.sequence import SequenceGenerator
  52. from synapse.types import JsonDict, StateMap, StrCollection, get_domain_from_id
  53. from synapse.util import json_encoder
  54. from synapse.util.iterutils import batch_iter, sorted_topologically
  55. from synapse.util.stringutils import non_null_str_or_none
  56. if TYPE_CHECKING:
  57. from synapse.server import HomeServer
  58. from synapse.storage.databases.main import DataStore
  59. logger = logging.getLogger(__name__)
  60. persist_event_counter = Counter("synapse_storage_events_persisted_events", "")
  61. event_counter = Counter(
  62. "synapse_storage_events_persisted_events_sep",
  63. "",
  64. ["type", "origin_type", "origin_entity"],
  65. )
  66. @attr.s(slots=True, auto_attribs=True)
  67. class DeltaState:
  68. """Deltas to use to update the `current_state_events` table.
  69. Attributes:
  70. to_delete: List of type/state_keys to delete from current state
  71. to_insert: Map of state to upsert into current state
  72. no_longer_in_room: The server is not longer in the room, so the room
  73. should e.g. be removed from `current_state_events` table.
  74. """
  75. to_delete: List[Tuple[str, str]]
  76. to_insert: StateMap[str]
  77. no_longer_in_room: bool = False
  78. class PersistEventsStore:
  79. """Contains all the functions for writing events to the database.
  80. Should only be instantiated on one process (when using a worker mode setup).
  81. Note: This is not part of the `DataStore` mixin.
  82. """
  83. def __init__(
  84. self,
  85. hs: "HomeServer",
  86. db: DatabasePool,
  87. main_data_store: "DataStore",
  88. db_conn: LoggingDatabaseConnection,
  89. ):
  90. self.hs = hs
  91. self.db_pool = db
  92. self.store = main_data_store
  93. self.database_engine = db.engine
  94. self._clock = hs.get_clock()
  95. self._instance_name = hs.get_instance_name()
  96. self._ephemeral_messages_enabled = hs.config.server.enable_ephemeral_messages
  97. self.is_mine_id = hs.is_mine_id
  98. # This should only exist on instances that are configured to write
  99. assert (
  100. hs.get_instance_name() in hs.config.worker.writers.events
  101. ), "Can only instantiate EventsStore on master"
  102. # Since we have been configured to write, we ought to have id generators,
  103. # rather than id trackers.
  104. assert isinstance(self.store._backfill_id_gen, AbstractStreamIdGenerator)
  105. assert isinstance(self.store._stream_id_gen, AbstractStreamIdGenerator)
  106. # Ideally we'd move these ID gens here, unfortunately some other ID
  107. # generators are chained off them so doing so is a bit of a PITA.
  108. self._backfill_id_gen: AbstractStreamIdGenerator = self.store._backfill_id_gen
  109. self._stream_id_gen: AbstractStreamIdGenerator = self.store._stream_id_gen
  110. @trace
  111. async def _persist_events_and_state_updates(
  112. self,
  113. events_and_contexts: List[Tuple[EventBase, EventContext]],
  114. *,
  115. state_delta_for_room: Dict[str, DeltaState],
  116. new_forward_extremities: Dict[str, Set[str]],
  117. use_negative_stream_ordering: bool = False,
  118. inhibit_local_membership_updates: bool = False,
  119. ) -> None:
  120. """Persist a set of events alongside updates to the current state and
  121. forward extremities tables.
  122. Args:
  123. events_and_contexts:
  124. state_delta_for_room: Map from room_id to the delta to apply to
  125. room state
  126. new_forward_extremities: Map from room_id to set of event IDs
  127. that are the new forward extremities of the room.
  128. use_negative_stream_ordering: Whether to start stream_ordering on
  129. the negative side and decrement. This should be set as True
  130. for backfilled events because backfilled events get a negative
  131. stream ordering so they don't come down incremental `/sync`.
  132. inhibit_local_membership_updates: Stop the local_current_membership
  133. from being updated by these events. This should be set to True
  134. for backfilled events because backfilled events in the past do
  135. not affect the current local state.
  136. Returns:
  137. Resolves when the events have been persisted
  138. Raises:
  139. PartialStateConflictError: if attempting to persist a partial state event in
  140. a room that has been un-partial stated.
  141. """
  142. # We want to calculate the stream orderings as late as possible, as
  143. # we only notify after all events with a lesser stream ordering have
  144. # been persisted. I.e. if we spend 10s inside the with block then
  145. # that will delay all subsequent events from being notified about.
  146. # Hence why we do it down here rather than wrapping the entire
  147. # function.
  148. #
  149. # Its safe to do this after calculating the state deltas etc as we
  150. # only need to protect the *persistence* of the events. This is to
  151. # ensure that queries of the form "fetch events since X" don't
  152. # return events and stream positions after events that are still in
  153. # flight, as otherwise subsequent requests "fetch event since Y"
  154. # will not return those events.
  155. #
  156. # Note: Multiple instances of this function cannot be in flight at
  157. # the same time for the same room.
  158. if use_negative_stream_ordering:
  159. stream_ordering_manager = self._backfill_id_gen.get_next_mult(
  160. len(events_and_contexts)
  161. )
  162. else:
  163. stream_ordering_manager = self._stream_id_gen.get_next_mult(
  164. len(events_and_contexts)
  165. )
  166. async with stream_ordering_manager as stream_orderings:
  167. for (event, _), stream in zip(events_and_contexts, stream_orderings):
  168. event.internal_metadata.stream_ordering = stream
  169. await self.db_pool.runInteraction(
  170. "persist_events",
  171. self._persist_events_txn,
  172. events_and_contexts=events_and_contexts,
  173. inhibit_local_membership_updates=inhibit_local_membership_updates,
  174. state_delta_for_room=state_delta_for_room,
  175. new_forward_extremities=new_forward_extremities,
  176. )
  177. persist_event_counter.inc(len(events_and_contexts))
  178. if not use_negative_stream_ordering:
  179. # we don't want to set the event_persisted_position to a negative
  180. # stream_ordering.
  181. synapse.metrics.event_persisted_position.set(stream)
  182. for event, context in events_and_contexts:
  183. if context.app_service:
  184. origin_type = "local"
  185. origin_entity = context.app_service.id
  186. elif self.hs.is_mine_id(event.sender):
  187. origin_type = "local"
  188. origin_entity = "*client*"
  189. else:
  190. origin_type = "remote"
  191. origin_entity = get_domain_from_id(event.sender)
  192. event_counter.labels(event.type, origin_type, origin_entity).inc()
  193. for room_id, latest_event_ids in new_forward_extremities.items():
  194. self.store.get_latest_event_ids_in_room.prefill(
  195. (room_id,), frozenset(latest_event_ids)
  196. )
  197. async def _get_events_which_are_prevs(self, event_ids: Iterable[str]) -> List[str]:
  198. """Filter the supplied list of event_ids to get those which are prev_events of
  199. existing (non-outlier/rejected) events.
  200. Args:
  201. event_ids: event ids to filter
  202. Returns:
  203. Filtered event ids
  204. """
  205. results: List[str] = []
  206. def _get_events_which_are_prevs_txn(
  207. txn: LoggingTransaction, batch: Collection[str]
  208. ) -> None:
  209. sql = """
  210. SELECT prev_event_id, internal_metadata
  211. FROM event_edges
  212. INNER JOIN events USING (event_id)
  213. LEFT JOIN rejections USING (event_id)
  214. LEFT JOIN event_json USING (event_id)
  215. WHERE
  216. NOT events.outlier
  217. AND rejections.event_id IS NULL
  218. AND
  219. """
  220. clause, args = make_in_list_sql_clause(
  221. self.database_engine, "prev_event_id", batch
  222. )
  223. txn.execute(sql + clause, args)
  224. results.extend(r[0] for r in txn if not db_to_json(r[1]).get("soft_failed"))
  225. for chunk in batch_iter(event_ids, 100):
  226. await self.db_pool.runInteraction(
  227. "_get_events_which_are_prevs", _get_events_which_are_prevs_txn, chunk
  228. )
  229. return results
  230. async def _get_prevs_before_rejected(self, event_ids: Iterable[str]) -> Set[str]:
  231. """Get soft-failed ancestors to remove from the extremities.
  232. Given a set of events, find all those that have been soft-failed or
  233. rejected. Returns those soft failed/rejected events and their prev
  234. events (whether soft-failed/rejected or not), and recurses up the
  235. prev-event graph until it finds no more soft-failed/rejected events.
  236. This is used to find extremities that are ancestors of new events, but
  237. are separated by soft failed events.
  238. Args:
  239. event_ids: Events to find prev events for. Note that these must have
  240. already been persisted.
  241. Returns:
  242. The previous events.
  243. """
  244. # The set of event_ids to return. This includes all soft-failed events
  245. # and their prev events.
  246. existing_prevs: Set[str] = set()
  247. def _get_prevs_before_rejected_txn(
  248. txn: LoggingTransaction, batch: Collection[str]
  249. ) -> None:
  250. to_recursively_check = batch
  251. while to_recursively_check:
  252. sql = """
  253. SELECT
  254. event_id, prev_event_id, internal_metadata,
  255. rejections.event_id IS NOT NULL
  256. FROM event_edges
  257. INNER JOIN events USING (event_id)
  258. LEFT JOIN rejections USING (event_id)
  259. LEFT JOIN event_json USING (event_id)
  260. WHERE
  261. NOT events.outlier
  262. AND
  263. """
  264. clause, args = make_in_list_sql_clause(
  265. self.database_engine, "event_id", to_recursively_check
  266. )
  267. txn.execute(sql + clause, args)
  268. to_recursively_check = []
  269. for _, prev_event_id, metadata, rejected in txn:
  270. if prev_event_id in existing_prevs:
  271. continue
  272. soft_failed = db_to_json(metadata).get("soft_failed")
  273. if soft_failed or rejected:
  274. to_recursively_check.append(prev_event_id)
  275. existing_prevs.add(prev_event_id)
  276. for chunk in batch_iter(event_ids, 100):
  277. await self.db_pool.runInteraction(
  278. "_get_prevs_before_rejected", _get_prevs_before_rejected_txn, chunk
  279. )
  280. return existing_prevs
  281. def _persist_events_txn(
  282. self,
  283. txn: LoggingTransaction,
  284. *,
  285. events_and_contexts: List[Tuple[EventBase, EventContext]],
  286. inhibit_local_membership_updates: bool,
  287. state_delta_for_room: Dict[str, DeltaState],
  288. new_forward_extremities: Dict[str, Set[str]],
  289. ) -> None:
  290. """Insert some number of room events into the necessary database tables.
  291. Rejected events are only inserted into the events table, the events_json table,
  292. and the rejections table. Things reading from those table will need to check
  293. whether the event was rejected.
  294. Args:
  295. txn
  296. events_and_contexts: events to persist
  297. inhibit_local_membership_updates: Stop the local_current_membership
  298. from being updated by these events. This should be set to True
  299. for backfilled events because backfilled events in the past do
  300. not affect the current local state.
  301. delete_existing True to purge existing table rows for the events
  302. from the database. This is useful when retrying due to
  303. IntegrityError.
  304. state_delta_for_room: The current-state delta for each room.
  305. new_forward_extremities: The new forward extremities for each room.
  306. For each room, a list of the event ids which are the forward
  307. extremities.
  308. Raises:
  309. PartialStateConflictError: if attempting to persist a partial state event in
  310. a room that has been un-partial stated.
  311. """
  312. all_events_and_contexts = events_and_contexts
  313. min_stream_order = events_and_contexts[0][0].internal_metadata.stream_ordering
  314. max_stream_order = events_and_contexts[-1][0].internal_metadata.stream_ordering
  315. # We check that the room still exists for events we're trying to
  316. # persist. This is to protect against races with deleting a room.
  317. #
  318. # Annoyingly SQLite doesn't support row level locking.
  319. if isinstance(self.database_engine, PostgresEngine):
  320. for room_id in {e.room_id for e, _ in events_and_contexts}:
  321. txn.execute(
  322. "SELECT room_version FROM rooms WHERE room_id = ? FOR SHARE",
  323. (room_id,),
  324. )
  325. row = txn.fetchone()
  326. if row is None:
  327. raise Exception(f"Room does not exist {room_id}")
  328. # stream orderings should have been assigned by now
  329. assert min_stream_order
  330. assert max_stream_order
  331. # Once the txn completes, invalidate all of the relevant caches. Note that we do this
  332. # up here because it captures all the events_and_contexts before any are removed.
  333. for event, _ in events_and_contexts:
  334. self.store.invalidate_get_event_cache_after_txn(txn, event.event_id)
  335. if event.redacts:
  336. self.store.invalidate_get_event_cache_after_txn(txn, event.redacts)
  337. relates_to = None
  338. relation = relation_from_event(event)
  339. if relation:
  340. relates_to = relation.parent_id
  341. assert event.internal_metadata.stream_ordering is not None
  342. txn.call_after(
  343. self.store._invalidate_caches_for_event,
  344. event.internal_metadata.stream_ordering,
  345. event.event_id,
  346. event.room_id,
  347. event.type,
  348. getattr(event, "state_key", None),
  349. event.redacts,
  350. relates_to,
  351. backfilled=False,
  352. )
  353. # Ensure that we don't have the same event twice.
  354. events_and_contexts = self._filter_events_and_contexts_for_duplicates(
  355. events_and_contexts
  356. )
  357. self._update_room_depths_txn(txn, events_and_contexts=events_and_contexts)
  358. # _update_outliers_txn filters out any events which have already been
  359. # persisted, and returns the filtered list.
  360. events_and_contexts = self._update_outliers_txn(
  361. txn, events_and_contexts=events_and_contexts
  362. )
  363. # From this point onwards the events are only events that we haven't
  364. # seen before.
  365. self._store_event_txn(txn, events_and_contexts=events_and_contexts)
  366. self._update_forward_extremities_txn(
  367. txn,
  368. new_forward_extremities=new_forward_extremities,
  369. max_stream_order=max_stream_order,
  370. )
  371. self._persist_transaction_ids_txn(txn, events_and_contexts)
  372. # Insert into event_to_state_groups.
  373. self._store_event_state_mappings_txn(txn, events_and_contexts)
  374. self._persist_event_auth_chain_txn(txn, [e for e, _ in events_and_contexts])
  375. # _store_rejected_events_txn filters out any events which were
  376. # rejected, and returns the filtered list.
  377. events_and_contexts = self._store_rejected_events_txn(
  378. txn, events_and_contexts=events_and_contexts
  379. )
  380. # From this point onwards the events are only ones that weren't
  381. # rejected.
  382. self._update_metadata_tables_txn(
  383. txn,
  384. events_and_contexts=events_and_contexts,
  385. all_events_and_contexts=all_events_and_contexts,
  386. inhibit_local_membership_updates=inhibit_local_membership_updates,
  387. )
  388. # We call this last as it assumes we've inserted the events into
  389. # room_memberships, where applicable.
  390. # NB: This function invalidates all state related caches
  391. self._update_current_state_txn(txn, state_delta_for_room, min_stream_order)
  392. def _persist_event_auth_chain_txn(
  393. self,
  394. txn: LoggingTransaction,
  395. events: List[EventBase],
  396. ) -> None:
  397. # We only care about state events, so this if there are no state events.
  398. if not any(e.is_state() for e in events):
  399. return
  400. # We want to store event_auth mappings for rejected events, as they're
  401. # used in state res v2.
  402. # This is only necessary if the rejected event appears in an accepted
  403. # event's auth chain, but its easier for now just to store them (and
  404. # it doesn't take much storage compared to storing the entire event
  405. # anyway).
  406. self.db_pool.simple_insert_many_txn(
  407. txn,
  408. table="event_auth",
  409. keys=("event_id", "room_id", "auth_id"),
  410. values=[
  411. (event.event_id, event.room_id, auth_id)
  412. for event in events
  413. for auth_id in event.auth_event_ids()
  414. if event.is_state()
  415. ],
  416. )
  417. # We now calculate chain ID/sequence numbers for any state events we're
  418. # persisting. We ignore out of band memberships as we're not in the room
  419. # and won't have their auth chain (we'll fix it up later if we join the
  420. # room).
  421. #
  422. # See: docs/auth_chain_difference_algorithm.md
  423. # We ignore legacy rooms that we aren't filling the chain cover index
  424. # for.
  425. rows = self.db_pool.simple_select_many_txn(
  426. txn,
  427. table="rooms",
  428. column="room_id",
  429. iterable={event.room_id for event in events if event.is_state()},
  430. keyvalues={},
  431. retcols=("room_id", "has_auth_chain_index"),
  432. )
  433. rooms_using_chain_index = {
  434. row["room_id"] for row in rows if row["has_auth_chain_index"]
  435. }
  436. state_events = {
  437. event.event_id: event
  438. for event in events
  439. if event.is_state() and event.room_id in rooms_using_chain_index
  440. }
  441. if not state_events:
  442. return
  443. # We need to know the type/state_key and auth events of the events we're
  444. # calculating chain IDs for. We don't rely on having the full Event
  445. # instances as we'll potentially be pulling more events from the DB and
  446. # we don't need the overhead of fetching/parsing the full event JSON.
  447. event_to_types = {
  448. e.event_id: (e.type, e.state_key) for e in state_events.values()
  449. }
  450. event_to_auth_chain = {
  451. e.event_id: e.auth_event_ids() for e in state_events.values()
  452. }
  453. event_to_room_id = {e.event_id: e.room_id for e in state_events.values()}
  454. self._add_chain_cover_index(
  455. txn,
  456. self.db_pool,
  457. self.store.event_chain_id_gen,
  458. event_to_room_id,
  459. event_to_types,
  460. event_to_auth_chain,
  461. )
  462. @classmethod
  463. def _add_chain_cover_index(
  464. cls,
  465. txn: LoggingTransaction,
  466. db_pool: DatabasePool,
  467. event_chain_id_gen: SequenceGenerator,
  468. event_to_room_id: Dict[str, str],
  469. event_to_types: Dict[str, Tuple[str, str]],
  470. event_to_auth_chain: Dict[str, StrCollection],
  471. ) -> None:
  472. """Calculate the chain cover index for the given events.
  473. Args:
  474. event_to_room_id: Event ID to the room ID of the event
  475. event_to_types: Event ID to type and state_key of the event
  476. event_to_auth_chain: Event ID to list of auth event IDs of the
  477. event (events with no auth events can be excluded).
  478. """
  479. # Map from event ID to chain ID/sequence number.
  480. chain_map: Dict[str, Tuple[int, int]] = {}
  481. # Set of event IDs to calculate chain ID/seq numbers for.
  482. events_to_calc_chain_id_for = set(event_to_room_id)
  483. # We check if there are any events that need to be handled in the rooms
  484. # we're looking at. These should just be out of band memberships, where
  485. # we didn't have the auth chain when we first persisted.
  486. rows = db_pool.simple_select_many_txn(
  487. txn,
  488. table="event_auth_chain_to_calculate",
  489. keyvalues={},
  490. column="room_id",
  491. iterable=set(event_to_room_id.values()),
  492. retcols=("event_id", "type", "state_key"),
  493. )
  494. for row in rows:
  495. event_id = row["event_id"]
  496. event_type = row["type"]
  497. state_key = row["state_key"]
  498. # (We could pull out the auth events for all rows at once using
  499. # simple_select_many, but this case happens rarely and almost always
  500. # with a single row.)
  501. auth_events = db_pool.simple_select_onecol_txn(
  502. txn,
  503. "event_auth",
  504. keyvalues={"event_id": event_id},
  505. retcol="auth_id",
  506. )
  507. events_to_calc_chain_id_for.add(event_id)
  508. event_to_types[event_id] = (event_type, state_key)
  509. event_to_auth_chain[event_id] = auth_events
  510. # First we get the chain ID and sequence numbers for the events'
  511. # auth events (that aren't also currently being persisted).
  512. #
  513. # Note that there there is an edge case here where we might not have
  514. # calculated chains and sequence numbers for events that were "out
  515. # of band". We handle this case by fetching the necessary info and
  516. # adding it to the set of events to calculate chain IDs for.
  517. missing_auth_chains = {
  518. a_id
  519. for auth_events in event_to_auth_chain.values()
  520. for a_id in auth_events
  521. if a_id not in events_to_calc_chain_id_for
  522. }
  523. # We loop here in case we find an out of band membership and need to
  524. # fetch their auth event info.
  525. while missing_auth_chains:
  526. sql = """
  527. SELECT event_id, events.type, se.state_key, chain_id, sequence_number
  528. FROM events
  529. INNER JOIN state_events AS se USING (event_id)
  530. LEFT JOIN event_auth_chains USING (event_id)
  531. WHERE
  532. """
  533. clause, args = make_in_list_sql_clause(
  534. txn.database_engine,
  535. "event_id",
  536. missing_auth_chains,
  537. )
  538. txn.execute(sql + clause, args)
  539. missing_auth_chains.clear()
  540. for (
  541. auth_id,
  542. event_type,
  543. state_key,
  544. chain_id,
  545. sequence_number,
  546. ) in txn.fetchall():
  547. event_to_types[auth_id] = (event_type, state_key)
  548. if chain_id is None:
  549. # No chain ID, so the event was persisted out of band.
  550. # We add to list of events to calculate auth chains for.
  551. events_to_calc_chain_id_for.add(auth_id)
  552. event_to_auth_chain[auth_id] = db_pool.simple_select_onecol_txn(
  553. txn,
  554. "event_auth",
  555. keyvalues={"event_id": auth_id},
  556. retcol="auth_id",
  557. )
  558. missing_auth_chains.update(
  559. e
  560. for e in event_to_auth_chain[auth_id]
  561. if e not in event_to_types
  562. )
  563. else:
  564. chain_map[auth_id] = (chain_id, sequence_number)
  565. # Now we check if we have any events where we don't have auth chain,
  566. # this should only be out of band memberships.
  567. for event_id in sorted_topologically(event_to_auth_chain, event_to_auth_chain):
  568. for auth_id in event_to_auth_chain[event_id]:
  569. if (
  570. auth_id not in chain_map
  571. and auth_id not in events_to_calc_chain_id_for
  572. ):
  573. events_to_calc_chain_id_for.discard(event_id)
  574. # If this is an event we're trying to persist we add it to
  575. # the list of events to calculate chain IDs for next time
  576. # around. (Otherwise we will have already added it to the
  577. # table).
  578. room_id = event_to_room_id.get(event_id)
  579. if room_id:
  580. e_type, state_key = event_to_types[event_id]
  581. db_pool.simple_insert_txn(
  582. txn,
  583. table="event_auth_chain_to_calculate",
  584. values={
  585. "event_id": event_id,
  586. "room_id": room_id,
  587. "type": e_type,
  588. "state_key": state_key,
  589. },
  590. )
  591. # We stop checking the event's auth events since we've
  592. # discarded it.
  593. break
  594. if not events_to_calc_chain_id_for:
  595. return
  596. # Allocate chain ID/sequence numbers to each new event.
  597. new_chain_tuples = cls._allocate_chain_ids(
  598. txn,
  599. db_pool,
  600. event_chain_id_gen,
  601. event_to_room_id,
  602. event_to_types,
  603. event_to_auth_chain,
  604. events_to_calc_chain_id_for,
  605. chain_map,
  606. )
  607. chain_map.update(new_chain_tuples)
  608. db_pool.simple_insert_many_txn(
  609. txn,
  610. table="event_auth_chains",
  611. keys=("event_id", "chain_id", "sequence_number"),
  612. values=[
  613. (event_id, c_id, seq)
  614. for event_id, (c_id, seq) in new_chain_tuples.items()
  615. ],
  616. )
  617. db_pool.simple_delete_many_txn(
  618. txn,
  619. table="event_auth_chain_to_calculate",
  620. keyvalues={},
  621. column="event_id",
  622. values=new_chain_tuples,
  623. )
  624. # Now we need to calculate any new links between chains caused by
  625. # the new events.
  626. #
  627. # Links are pairs of chain ID/sequence numbers such that for any
  628. # event A (CA, SA) and any event B (CB, SB), B is in A's auth chain
  629. # if and only if there is at least one link (CA, S1) -> (CB, S2)
  630. # where SA >= S1 and S2 >= SB.
  631. #
  632. # We try and avoid adding redundant links to the table, e.g. if we
  633. # have two links between two chains which both start/end at the
  634. # sequence number event (or cross) then one can be safely dropped.
  635. #
  636. # To calculate new links we look at every new event and:
  637. # 1. Fetch the chain ID/sequence numbers of its auth events,
  638. # discarding any that are reachable by other auth events, or
  639. # that have the same chain ID as the event.
  640. # 2. For each retained auth event we:
  641. # a. Add a link from the event's to the auth event's chain
  642. # ID/sequence number; and
  643. # b. Add a link from the event to every chain reachable by the
  644. # auth event.
  645. # Step 1, fetch all existing links from all the chains we've seen
  646. # referenced.
  647. chain_links = _LinkMap()
  648. rows = db_pool.simple_select_many_txn(
  649. txn,
  650. table="event_auth_chain_links",
  651. column="origin_chain_id",
  652. iterable={chain_id for chain_id, _ in chain_map.values()},
  653. keyvalues={},
  654. retcols=(
  655. "origin_chain_id",
  656. "origin_sequence_number",
  657. "target_chain_id",
  658. "target_sequence_number",
  659. ),
  660. )
  661. for row in rows:
  662. chain_links.add_link(
  663. (row["origin_chain_id"], row["origin_sequence_number"]),
  664. (row["target_chain_id"], row["target_sequence_number"]),
  665. new=False,
  666. )
  667. # We do this in toplogical order to avoid adding redundant links.
  668. for event_id in sorted_topologically(
  669. events_to_calc_chain_id_for, event_to_auth_chain
  670. ):
  671. chain_id, sequence_number = chain_map[event_id]
  672. # Filter out auth events that are reachable by other auth
  673. # events. We do this by looking at every permutation of pairs of
  674. # auth events (A, B) to check if B is reachable from A.
  675. reduction = {
  676. a_id
  677. for a_id in event_to_auth_chain.get(event_id, [])
  678. if chain_map[a_id][0] != chain_id
  679. }
  680. for start_auth_id, end_auth_id in itertools.permutations(
  681. event_to_auth_chain.get(event_id, []),
  682. r=2,
  683. ):
  684. if chain_links.exists_path_from(
  685. chain_map[start_auth_id], chain_map[end_auth_id]
  686. ):
  687. reduction.discard(end_auth_id)
  688. # Step 2, figure out what the new links are from the reduced
  689. # list of auth events.
  690. for auth_id in reduction:
  691. auth_chain_id, auth_sequence_number = chain_map[auth_id]
  692. # Step 2a, add link between the event and auth event
  693. chain_links.add_link(
  694. (chain_id, sequence_number), (auth_chain_id, auth_sequence_number)
  695. )
  696. # Step 2b, add a link to chains reachable from the auth
  697. # event.
  698. for target_id, target_seq in chain_links.get_links_from(
  699. (auth_chain_id, auth_sequence_number)
  700. ):
  701. if target_id == chain_id:
  702. continue
  703. chain_links.add_link(
  704. (chain_id, sequence_number), (target_id, target_seq)
  705. )
  706. db_pool.simple_insert_many_txn(
  707. txn,
  708. table="event_auth_chain_links",
  709. keys=(
  710. "origin_chain_id",
  711. "origin_sequence_number",
  712. "target_chain_id",
  713. "target_sequence_number",
  714. ),
  715. values=[
  716. (source_id, source_seq, target_id, target_seq)
  717. for (
  718. source_id,
  719. source_seq,
  720. target_id,
  721. target_seq,
  722. ) in chain_links.get_additions()
  723. ],
  724. )
  725. @staticmethod
  726. def _allocate_chain_ids(
  727. txn: LoggingTransaction,
  728. db_pool: DatabasePool,
  729. event_chain_id_gen: SequenceGenerator,
  730. event_to_room_id: Dict[str, str],
  731. event_to_types: Dict[str, Tuple[str, str]],
  732. event_to_auth_chain: Dict[str, StrCollection],
  733. events_to_calc_chain_id_for: Set[str],
  734. chain_map: Dict[str, Tuple[int, int]],
  735. ) -> Dict[str, Tuple[int, int]]:
  736. """Allocates, but does not persist, chain ID/sequence numbers for the
  737. events in `events_to_calc_chain_id_for`. (c.f. _add_chain_cover_index
  738. for info on args)
  739. """
  740. # We now calculate the chain IDs/sequence numbers for the events. We do
  741. # this by looking at the chain ID and sequence number of any auth event
  742. # with the same type/state_key and incrementing the sequence number by
  743. # one. If there was no match or the chain ID/sequence number is already
  744. # taken we generate a new chain.
  745. #
  746. # We try to reduce the number of times that we hit the database by
  747. # batching up calls, to make this more efficient when persisting large
  748. # numbers of state events (e.g. during joins).
  749. #
  750. # We do this by:
  751. # 1. Calculating for each event which auth event will be used to
  752. # inherit the chain ID, i.e. converting the auth chain graph to a
  753. # tree that we can allocate chains on. We also keep track of which
  754. # existing chain IDs have been referenced.
  755. # 2. Fetching the max allocated sequence number for each referenced
  756. # existing chain ID, generating a map from chain ID to the max
  757. # allocated sequence number.
  758. # 3. Iterating over the tree and allocating a chain ID/seq no. to the
  759. # new event, by incrementing the sequence number from the
  760. # referenced event's chain ID/seq no. and checking that the
  761. # incremented sequence number hasn't already been allocated (by
  762. # looking in the map generated in the previous step). We generate a
  763. # new chain if the sequence number has already been allocated.
  764. #
  765. existing_chains: Set[int] = set()
  766. tree: List[Tuple[str, Optional[str]]] = []
  767. # We need to do this in a topologically sorted order as we want to
  768. # generate chain IDs/sequence numbers of an event's auth events before
  769. # the event itself.
  770. for event_id in sorted_topologically(
  771. events_to_calc_chain_id_for, event_to_auth_chain
  772. ):
  773. for auth_id in event_to_auth_chain.get(event_id, []):
  774. if event_to_types.get(event_id) == event_to_types.get(auth_id):
  775. existing_chain_id = chain_map.get(auth_id)
  776. if existing_chain_id:
  777. existing_chains.add(existing_chain_id[0])
  778. tree.append((event_id, auth_id))
  779. break
  780. else:
  781. tree.append((event_id, None))
  782. # Fetch the current max sequence number for each existing referenced chain.
  783. sql = """
  784. SELECT chain_id, MAX(sequence_number) FROM event_auth_chains
  785. WHERE %s
  786. GROUP BY chain_id
  787. """
  788. clause, args = make_in_list_sql_clause(
  789. db_pool.engine, "chain_id", existing_chains
  790. )
  791. txn.execute(sql % (clause,), args)
  792. chain_to_max_seq_no: Dict[Any, int] = {row[0]: row[1] for row in txn}
  793. # Allocate the new events chain ID/sequence numbers.
  794. #
  795. # To reduce the number of calls to the database we don't allocate a
  796. # chain ID number in the loop, instead we use a temporary `object()` for
  797. # each new chain ID. Once we've done the loop we generate the necessary
  798. # number of new chain IDs in one call, replacing all temporary
  799. # objects with real allocated chain IDs.
  800. unallocated_chain_ids: Set[object] = set()
  801. new_chain_tuples: Dict[str, Tuple[Any, int]] = {}
  802. for event_id, auth_event_id in tree:
  803. # If we reference an auth_event_id we fetch the allocated chain ID,
  804. # either from the existing `chain_map` or the newly generated
  805. # `new_chain_tuples` map.
  806. existing_chain_id = None
  807. if auth_event_id:
  808. existing_chain_id = new_chain_tuples.get(auth_event_id)
  809. if not existing_chain_id:
  810. existing_chain_id = chain_map[auth_event_id]
  811. new_chain_tuple: Optional[Tuple[Any, int]] = None
  812. if existing_chain_id:
  813. # We found a chain ID/sequence number candidate, check its
  814. # not already taken.
  815. proposed_new_id = existing_chain_id[0]
  816. proposed_new_seq = existing_chain_id[1] + 1
  817. if chain_to_max_seq_no[proposed_new_id] < proposed_new_seq:
  818. new_chain_tuple = (
  819. proposed_new_id,
  820. proposed_new_seq,
  821. )
  822. # If we need to start a new chain we allocate a temporary chain ID.
  823. if not new_chain_tuple:
  824. new_chain_tuple = (object(), 1)
  825. unallocated_chain_ids.add(new_chain_tuple[0])
  826. new_chain_tuples[event_id] = new_chain_tuple
  827. chain_to_max_seq_no[new_chain_tuple[0]] = new_chain_tuple[1]
  828. # Generate new chain IDs for all unallocated chain IDs.
  829. newly_allocated_chain_ids = event_chain_id_gen.get_next_mult_txn(
  830. txn, len(unallocated_chain_ids)
  831. )
  832. # Map from potentially temporary chain ID to real chain ID
  833. chain_id_to_allocated_map: Dict[Any, int] = dict(
  834. zip(unallocated_chain_ids, newly_allocated_chain_ids)
  835. )
  836. chain_id_to_allocated_map.update((c, c) for c in existing_chains)
  837. return {
  838. event_id: (chain_id_to_allocated_map[chain_id], seq)
  839. for event_id, (chain_id, seq) in new_chain_tuples.items()
  840. }
  841. def _persist_transaction_ids_txn(
  842. self,
  843. txn: LoggingTransaction,
  844. events_and_contexts: List[Tuple[EventBase, EventContext]],
  845. ) -> None:
  846. """Persist the mapping from transaction IDs to event IDs (if defined)."""
  847. inserted_ts = self._clock.time_msec()
  848. to_insert_device_id: List[Tuple[str, str, str, str, str, int]] = []
  849. for event, _ in events_and_contexts:
  850. txn_id = getattr(event.internal_metadata, "txn_id", None)
  851. device_id = getattr(event.internal_metadata, "device_id", None)
  852. if txn_id is not None:
  853. if device_id is not None:
  854. to_insert_device_id.append(
  855. (
  856. event.event_id,
  857. event.room_id,
  858. event.sender,
  859. device_id,
  860. txn_id,
  861. inserted_ts,
  862. )
  863. )
  864. # Synapse relies on the device_id to scope transactions for events..
  865. if to_insert_device_id:
  866. self.db_pool.simple_insert_many_txn(
  867. txn,
  868. table="event_txn_id_device_id",
  869. keys=(
  870. "event_id",
  871. "room_id",
  872. "user_id",
  873. "device_id",
  874. "txn_id",
  875. "inserted_ts",
  876. ),
  877. values=to_insert_device_id,
  878. )
  879. async def update_current_state(
  880. self,
  881. room_id: str,
  882. state_delta: DeltaState,
  883. ) -> None:
  884. """Update the current state stored in the datatabase for the given room"""
  885. async with self._stream_id_gen.get_next() as stream_ordering:
  886. await self.db_pool.runInteraction(
  887. "update_current_state",
  888. self._update_current_state_txn,
  889. state_delta_by_room={room_id: state_delta},
  890. stream_id=stream_ordering,
  891. )
  892. def _update_current_state_txn(
  893. self,
  894. txn: LoggingTransaction,
  895. state_delta_by_room: Dict[str, DeltaState],
  896. stream_id: int,
  897. ) -> None:
  898. for room_id, delta_state in state_delta_by_room.items():
  899. to_delete = delta_state.to_delete
  900. to_insert = delta_state.to_insert
  901. # Figure out the changes of membership to invalidate the
  902. # `get_rooms_for_user` cache.
  903. # We find out which membership events we may have deleted
  904. # and which we have added, then we invalidate the caches for all
  905. # those users.
  906. members_changed = {
  907. state_key
  908. for ev_type, state_key in itertools.chain(to_delete, to_insert)
  909. if ev_type == EventTypes.Member
  910. }
  911. if delta_state.no_longer_in_room:
  912. # Server is no longer in the room so we delete the room from
  913. # current_state_events, being careful we've already updated the
  914. # rooms.room_version column (which gets populated in a
  915. # background task).
  916. self._upsert_room_version_txn(txn, room_id)
  917. # Before deleting we populate the current_state_delta_stream
  918. # so that async background tasks get told what happened.
  919. sql = """
  920. INSERT INTO current_state_delta_stream
  921. (stream_id, instance_name, room_id, type, state_key, event_id, prev_event_id)
  922. SELECT ?, ?, room_id, type, state_key, null, event_id
  923. FROM current_state_events
  924. WHERE room_id = ?
  925. """
  926. txn.execute(sql, (stream_id, self._instance_name, room_id))
  927. # We also want to invalidate the membership caches for users
  928. # that were in the room.
  929. users_in_room = self.store.get_users_in_room_txn(txn, room_id)
  930. members_changed.update(users_in_room)
  931. self.db_pool.simple_delete_txn(
  932. txn,
  933. table="current_state_events",
  934. keyvalues={"room_id": room_id},
  935. )
  936. else:
  937. # We're still in the room, so we update the current state as normal.
  938. # First we add entries to the current_state_delta_stream. We
  939. # do this before updating the current_state_events table so
  940. # that we can use it to calculate the `prev_event_id`. (This
  941. # allows us to not have to pull out the existing state
  942. # unnecessarily).
  943. #
  944. # The stream_id for the update is chosen to be the minimum of the stream_ids
  945. # for the batch of the events that we are persisting; that means we do not
  946. # end up in a situation where workers see events before the
  947. # current_state_delta updates.
  948. #
  949. sql = """
  950. INSERT INTO current_state_delta_stream
  951. (stream_id, instance_name, room_id, type, state_key, event_id, prev_event_id)
  952. SELECT ?, ?, ?, ?, ?, ?, (
  953. SELECT event_id FROM current_state_events
  954. WHERE room_id = ? AND type = ? AND state_key = ?
  955. )
  956. """
  957. txn.execute_batch(
  958. sql,
  959. (
  960. (
  961. stream_id,
  962. self._instance_name,
  963. room_id,
  964. etype,
  965. state_key,
  966. to_insert.get((etype, state_key)),
  967. room_id,
  968. etype,
  969. state_key,
  970. )
  971. for etype, state_key in itertools.chain(to_delete, to_insert)
  972. ),
  973. )
  974. # Now we actually update the current_state_events table
  975. txn.execute_batch(
  976. "DELETE FROM current_state_events"
  977. " WHERE room_id = ? AND type = ? AND state_key = ?",
  978. (
  979. (room_id, etype, state_key)
  980. for etype, state_key in itertools.chain(to_delete, to_insert)
  981. ),
  982. )
  983. # We include the membership in the current state table, hence we do
  984. # a lookup when we insert. This assumes that all events have already
  985. # been inserted into room_memberships.
  986. txn.execute_batch(
  987. """INSERT INTO current_state_events
  988. (room_id, type, state_key, event_id, membership, event_stream_ordering)
  989. VALUES (
  990. ?, ?, ?, ?,
  991. (SELECT membership FROM room_memberships WHERE event_id = ?),
  992. (SELECT stream_ordering FROM events WHERE event_id = ?)
  993. )
  994. """,
  995. [
  996. (room_id, key[0], key[1], ev_id, ev_id, ev_id)
  997. for key, ev_id in to_insert.items()
  998. ],
  999. )
  1000. # We now update `local_current_membership`. We do this regardless
  1001. # of whether we're still in the room or not to handle the case where
  1002. # e.g. we just got banned (where we need to record that fact here).
  1003. # Note: Do we really want to delete rows here (that we do not
  1004. # subsequently reinsert below)? While technically correct it means
  1005. # we have no record of the fact the user *was* a member of the
  1006. # room but got, say, state reset out of it.
  1007. if to_delete or to_insert:
  1008. txn.execute_batch(
  1009. "DELETE FROM local_current_membership"
  1010. " WHERE room_id = ? AND user_id = ?",
  1011. (
  1012. (room_id, state_key)
  1013. for etype, state_key in itertools.chain(to_delete, to_insert)
  1014. if etype == EventTypes.Member and self.is_mine_id(state_key)
  1015. ),
  1016. )
  1017. if to_insert:
  1018. txn.execute_batch(
  1019. """INSERT INTO local_current_membership
  1020. (room_id, user_id, event_id, membership, event_stream_ordering)
  1021. VALUES (
  1022. ?, ?, ?,
  1023. (SELECT membership FROM room_memberships WHERE event_id = ?),
  1024. (SELECT stream_ordering FROM events WHERE event_id = ?)
  1025. )
  1026. """,
  1027. [
  1028. (room_id, key[1], ev_id, ev_id, ev_id)
  1029. for key, ev_id in to_insert.items()
  1030. if key[0] == EventTypes.Member and self.is_mine_id(key[1])
  1031. ],
  1032. )
  1033. txn.call_after(
  1034. self.store._curr_state_delta_stream_cache.entity_has_changed,
  1035. room_id,
  1036. stream_id,
  1037. )
  1038. # Invalidate the various caches
  1039. self.store._invalidate_state_caches_and_stream(
  1040. txn, room_id, members_changed
  1041. )
  1042. # Check if any of the remote membership changes requires us to
  1043. # unsubscribe from their device lists.
  1044. self.store.handle_potentially_left_users_txn(
  1045. txn, {m for m in members_changed if not self.hs.is_mine_id(m)}
  1046. )
  1047. def _upsert_room_version_txn(self, txn: LoggingTransaction, room_id: str) -> None:
  1048. """Update the room version in the database based off current state
  1049. events.
  1050. This is used when we're about to delete current state and we want to
  1051. ensure that the `rooms.room_version` column is up to date.
  1052. """
  1053. sql = """
  1054. SELECT json FROM event_json
  1055. INNER JOIN current_state_events USING (room_id, event_id)
  1056. WHERE room_id = ? AND type = ? AND state_key = ?
  1057. """
  1058. txn.execute(sql, (room_id, EventTypes.Create, ""))
  1059. row = txn.fetchone()
  1060. if row:
  1061. event_json = db_to_json(row[0])
  1062. content = event_json.get("content", {})
  1063. creator = content.get("creator")
  1064. room_version_id = content.get("room_version", RoomVersions.V1.identifier)
  1065. self.db_pool.simple_upsert_txn(
  1066. txn,
  1067. table="rooms",
  1068. keyvalues={"room_id": room_id},
  1069. values={"room_version": room_version_id},
  1070. insertion_values={"is_public": False, "creator": creator},
  1071. )
  1072. def _update_forward_extremities_txn(
  1073. self,
  1074. txn: LoggingTransaction,
  1075. new_forward_extremities: Dict[str, Set[str]],
  1076. max_stream_order: int,
  1077. ) -> None:
  1078. for room_id in new_forward_extremities.keys():
  1079. self.db_pool.simple_delete_txn(
  1080. txn, table="event_forward_extremities", keyvalues={"room_id": room_id}
  1081. )
  1082. self.db_pool.simple_insert_many_txn(
  1083. txn,
  1084. table="event_forward_extremities",
  1085. keys=("event_id", "room_id"),
  1086. values=[
  1087. (ev_id, room_id)
  1088. for room_id, new_extrem in new_forward_extremities.items()
  1089. for ev_id in new_extrem
  1090. ],
  1091. )
  1092. # We now insert into stream_ordering_to_exterm a mapping from room_id,
  1093. # new stream_ordering to new forward extremeties in the room.
  1094. # This allows us to later efficiently look up the forward extremeties
  1095. # for a room before a given stream_ordering
  1096. self.db_pool.simple_insert_many_txn(
  1097. txn,
  1098. table="stream_ordering_to_exterm",
  1099. keys=("room_id", "event_id", "stream_ordering"),
  1100. values=[
  1101. (room_id, event_id, max_stream_order)
  1102. for room_id, new_extrem in new_forward_extremities.items()
  1103. for event_id in new_extrem
  1104. ],
  1105. )
  1106. @classmethod
  1107. def _filter_events_and_contexts_for_duplicates(
  1108. cls, events_and_contexts: List[Tuple[EventBase, EventContext]]
  1109. ) -> List[Tuple[EventBase, EventContext]]:
  1110. """Ensure that we don't have the same event twice.
  1111. Pick the earliest non-outlier if there is one, else the earliest one.
  1112. Args:
  1113. events_and_contexts:
  1114. Returns:
  1115. filtered list
  1116. """
  1117. new_events_and_contexts: OrderedDict[
  1118. str, Tuple[EventBase, EventContext]
  1119. ] = OrderedDict()
  1120. for event, context in events_and_contexts:
  1121. prev_event_context = new_events_and_contexts.get(event.event_id)
  1122. if prev_event_context:
  1123. if not event.internal_metadata.is_outlier():
  1124. if prev_event_context[0].internal_metadata.is_outlier():
  1125. # To ensure correct ordering we pop, as OrderedDict is
  1126. # ordered by first insertion.
  1127. new_events_and_contexts.pop(event.event_id, None)
  1128. new_events_and_contexts[event.event_id] = (event, context)
  1129. else:
  1130. new_events_and_contexts[event.event_id] = (event, context)
  1131. return list(new_events_and_contexts.values())
  1132. def _update_room_depths_txn(
  1133. self,
  1134. txn: LoggingTransaction,
  1135. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1136. ) -> None:
  1137. """Update min_depth for each room
  1138. Args:
  1139. txn: db connection
  1140. events_and_contexts: events we are persisting
  1141. """
  1142. depth_updates: Dict[str, int] = {}
  1143. for event, context in events_and_contexts:
  1144. # Then update the `stream_ordering` position to mark the latest
  1145. # event as the front of the room. This should not be done for
  1146. # backfilled events because backfilled events have negative
  1147. # stream_ordering and happened in the past so we know that we don't
  1148. # need to update the stream_ordering tip/front for the room.
  1149. assert event.internal_metadata.stream_ordering is not None
  1150. if event.internal_metadata.stream_ordering >= 0:
  1151. txn.call_after(
  1152. self.store._events_stream_cache.entity_has_changed,
  1153. event.room_id,
  1154. event.internal_metadata.stream_ordering,
  1155. )
  1156. if not event.internal_metadata.is_outlier() and not context.rejected:
  1157. depth_updates[event.room_id] = max(
  1158. event.depth, depth_updates.get(event.room_id, event.depth)
  1159. )
  1160. for room_id, depth in depth_updates.items():
  1161. self._update_min_depth_for_room_txn(txn, room_id, depth)
  1162. def _update_outliers_txn(
  1163. self,
  1164. txn: LoggingTransaction,
  1165. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1166. ) -> List[Tuple[EventBase, EventContext]]:
  1167. """Update any outliers with new event info.
  1168. This turns outliers into ex-outliers (unless the new event was rejected), and
  1169. also removes any other events we have already seen from the list.
  1170. Args:
  1171. txn: db connection
  1172. events_and_contexts: events we are persisting
  1173. Returns:
  1174. new list, without events which are already in the events table.
  1175. Raises:
  1176. PartialStateConflictError: if attempting to persist a partial state event in
  1177. a room that has been un-partial stated.
  1178. """
  1179. txn.execute(
  1180. "SELECT event_id, outlier FROM events WHERE event_id in (%s)"
  1181. % (",".join(["?"] * len(events_and_contexts)),),
  1182. [event.event_id for event, _ in events_and_contexts],
  1183. )
  1184. have_persisted = dict(cast(Iterable[Tuple[str, bool]], txn))
  1185. logger.debug(
  1186. "_update_outliers_txn: events=%s have_persisted=%s",
  1187. [ev.event_id for ev, _ in events_and_contexts],
  1188. have_persisted,
  1189. )
  1190. to_remove = set()
  1191. for event, context in events_and_contexts:
  1192. outlier_persisted = have_persisted.get(event.event_id)
  1193. logger.debug(
  1194. "_update_outliers_txn: event=%s outlier=%s outlier_persisted=%s",
  1195. event.event_id,
  1196. event.internal_metadata.is_outlier(),
  1197. outlier_persisted,
  1198. )
  1199. # Ignore events which we haven't persisted at all
  1200. if outlier_persisted is None:
  1201. continue
  1202. to_remove.add(event)
  1203. if context.rejected:
  1204. # If the incoming event is rejected then we don't care if the event
  1205. # was an outlier or not - what we have is at least as good.
  1206. continue
  1207. if not event.internal_metadata.is_outlier() and outlier_persisted:
  1208. # We received a copy of an event that we had already stored as
  1209. # an outlier in the database. We now have some state at that event
  1210. # so we need to update the state_groups table with that state.
  1211. #
  1212. # Note that we do not update the stream_ordering of the event in this
  1213. # scenario. XXX: does this cause bugs? It will mean we won't send such
  1214. # events down /sync. In general they will be historical events, so that
  1215. # doesn't matter too much, but that is not always the case.
  1216. logger.info(
  1217. "_update_outliers_txn: Updating state for ex-outlier event %s",
  1218. event.event_id,
  1219. )
  1220. # insert into event_to_state_groups.
  1221. try:
  1222. self._store_event_state_mappings_txn(txn, ((event, context),))
  1223. except Exception:
  1224. logger.exception("")
  1225. raise
  1226. # Add an entry to the ex_outlier_stream table to replicate the
  1227. # change in outlier status to our workers.
  1228. stream_order = event.internal_metadata.stream_ordering
  1229. state_group_id = context.state_group
  1230. self.db_pool.simple_insert_txn(
  1231. txn,
  1232. table="ex_outlier_stream",
  1233. values={
  1234. "event_stream_ordering": stream_order,
  1235. "event_id": event.event_id,
  1236. "state_group": state_group_id,
  1237. "instance_name": self._instance_name,
  1238. },
  1239. )
  1240. sql = "UPDATE events SET outlier = FALSE WHERE event_id = ?"
  1241. txn.execute(sql, (event.event_id,))
  1242. # Update the event_backward_extremities table now that this
  1243. # event isn't an outlier any more.
  1244. self._update_backward_extremeties(txn, [event])
  1245. return [ec for ec in events_and_contexts if ec[0] not in to_remove]
  1246. def _store_event_txn(
  1247. self,
  1248. txn: LoggingTransaction,
  1249. events_and_contexts: Collection[Tuple[EventBase, EventContext]],
  1250. ) -> None:
  1251. """Insert new events into the event, event_json, redaction and
  1252. state_events tables.
  1253. """
  1254. if not events_and_contexts:
  1255. # nothing to do here
  1256. return
  1257. def event_dict(event: EventBase) -> JsonDict:
  1258. d = event.get_dict()
  1259. d.pop("redacted", None)
  1260. d.pop("redacted_because", None)
  1261. return d
  1262. self.db_pool.simple_insert_many_txn(
  1263. txn,
  1264. table="event_json",
  1265. keys=("event_id", "room_id", "internal_metadata", "json", "format_version"),
  1266. values=(
  1267. (
  1268. event.event_id,
  1269. event.room_id,
  1270. json_encoder.encode(event.internal_metadata.get_dict()),
  1271. json_encoder.encode(event_dict(event)),
  1272. event.format_version,
  1273. )
  1274. for event, _ in events_and_contexts
  1275. ),
  1276. )
  1277. self.db_pool.simple_insert_many_txn(
  1278. txn,
  1279. table="events",
  1280. keys=(
  1281. "instance_name",
  1282. "stream_ordering",
  1283. "topological_ordering",
  1284. "depth",
  1285. "event_id",
  1286. "room_id",
  1287. "type",
  1288. "processed",
  1289. "outlier",
  1290. "origin_server_ts",
  1291. "received_ts",
  1292. "sender",
  1293. "contains_url",
  1294. "state_key",
  1295. "rejection_reason",
  1296. ),
  1297. values=(
  1298. (
  1299. self._instance_name,
  1300. event.internal_metadata.stream_ordering,
  1301. event.depth, # topological_ordering
  1302. event.depth, # depth
  1303. event.event_id,
  1304. event.room_id,
  1305. event.type,
  1306. True, # processed
  1307. event.internal_metadata.is_outlier(),
  1308. int(event.origin_server_ts),
  1309. self._clock.time_msec(),
  1310. event.sender,
  1311. "url" in event.content and isinstance(event.content["url"], str),
  1312. event.get_state_key(),
  1313. context.rejected,
  1314. )
  1315. for event, context in events_and_contexts
  1316. ),
  1317. )
  1318. # If we're persisting an unredacted event we go and ensure
  1319. # that we mark any redactions that reference this event as
  1320. # requiring censoring.
  1321. unredacted_events = [
  1322. event.event_id
  1323. for event, _ in events_and_contexts
  1324. if not event.internal_metadata.is_redacted()
  1325. ]
  1326. sql = "UPDATE redactions SET have_censored = FALSE WHERE "
  1327. clause, args = make_in_list_sql_clause(
  1328. self.database_engine,
  1329. "redacts",
  1330. unredacted_events,
  1331. )
  1332. txn.execute(sql + clause, args)
  1333. self.db_pool.simple_insert_many_txn(
  1334. txn,
  1335. table="state_events",
  1336. keys=("event_id", "room_id", "type", "state_key"),
  1337. values=(
  1338. (event.event_id, event.room_id, event.type, event.state_key)
  1339. for event, _ in events_and_contexts
  1340. if event.is_state()
  1341. ),
  1342. )
  1343. def _store_rejected_events_txn(
  1344. self,
  1345. txn: LoggingTransaction,
  1346. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1347. ) -> List[Tuple[EventBase, EventContext]]:
  1348. """Add rows to the 'rejections' table for received events which were
  1349. rejected
  1350. Args:
  1351. txn: db connection
  1352. events_and_contexts: events we are persisting
  1353. Returns:
  1354. new list, without the rejected events.
  1355. """
  1356. # Remove the rejected events from the list now that we've added them
  1357. # to the events table and the events_json table.
  1358. to_remove = set()
  1359. for event, context in events_and_contexts:
  1360. if context.rejected:
  1361. # Insert the event_id into the rejections table
  1362. # (events.rejection_reason has already been done)
  1363. self._store_rejections_txn(txn, event.event_id, context.rejected)
  1364. to_remove.add(event)
  1365. return [ec for ec in events_and_contexts if ec[0] not in to_remove]
  1366. def _update_metadata_tables_txn(
  1367. self,
  1368. txn: LoggingTransaction,
  1369. *,
  1370. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1371. all_events_and_contexts: List[Tuple[EventBase, EventContext]],
  1372. inhibit_local_membership_updates: bool = False,
  1373. ) -> None:
  1374. """Update all the miscellaneous tables for new events
  1375. Args:
  1376. txn: db connection
  1377. events_and_contexts: events we are persisting
  1378. all_events_and_contexts: all events that we were going to persist.
  1379. This includes events we've already persisted, etc, that wouldn't
  1380. appear in events_and_context.
  1381. inhibit_local_membership_updates: Stop the local_current_membership
  1382. from being updated by these events. This should be set to True
  1383. for backfilled events because backfilled events in the past do
  1384. not affect the current local state.
  1385. """
  1386. # Insert all the push actions into the event_push_actions table.
  1387. self._set_push_actions_for_event_and_users_txn(
  1388. txn,
  1389. events_and_contexts=events_and_contexts,
  1390. all_events_and_contexts=all_events_and_contexts,
  1391. )
  1392. if not events_and_contexts:
  1393. # nothing to do here
  1394. return
  1395. for event, _ in events_and_contexts:
  1396. if event.type == EventTypes.Redaction and event.redacts is not None:
  1397. # Remove the entries in the event_push_actions table for the
  1398. # redacted event.
  1399. self._remove_push_actions_for_event_id_txn(
  1400. txn, event.room_id, event.redacts
  1401. )
  1402. # Remove from relations table.
  1403. self._handle_redact_relations(txn, event.room_id, event.redacts)
  1404. # Update the event_forward_extremities, event_backward_extremities and
  1405. # event_edges tables.
  1406. self._handle_mult_prev_events(
  1407. txn, events=[event for event, _ in events_and_contexts]
  1408. )
  1409. for event, _ in events_and_contexts:
  1410. if event.type == EventTypes.Name:
  1411. # Insert into the event_search table.
  1412. self._store_room_name_txn(txn, event)
  1413. elif event.type == EventTypes.Topic:
  1414. # Insert into the event_search table.
  1415. self._store_room_topic_txn(txn, event)
  1416. elif event.type == EventTypes.Message:
  1417. # Insert into the event_search table.
  1418. self._store_room_message_txn(txn, event)
  1419. elif event.type == EventTypes.Redaction and event.redacts is not None:
  1420. # Insert into the redactions table.
  1421. self._store_redaction(txn, event)
  1422. elif event.type == EventTypes.Retention:
  1423. # Update the room_retention table.
  1424. self._store_retention_policy_for_room_txn(txn, event)
  1425. self._handle_event_relations(txn, event)
  1426. # Store the labels for this event.
  1427. labels = event.content.get(EventContentFields.LABELS)
  1428. if labels:
  1429. self.insert_labels_for_event_txn(
  1430. txn, event.event_id, labels, event.room_id, event.depth
  1431. )
  1432. if self._ephemeral_messages_enabled:
  1433. # If there's an expiry timestamp on the event, store it.
  1434. expiry_ts = event.content.get(EventContentFields.SELF_DESTRUCT_AFTER)
  1435. if type(expiry_ts) is int and not event.is_state(): # noqa: E721
  1436. self._insert_event_expiry_txn(txn, event.event_id, expiry_ts)
  1437. # Insert into the room_memberships table.
  1438. self._store_room_members_txn(
  1439. txn,
  1440. [
  1441. event
  1442. for event, _ in events_and_contexts
  1443. if event.type == EventTypes.Member
  1444. ],
  1445. inhibit_local_membership_updates=inhibit_local_membership_updates,
  1446. )
  1447. # Prefill the event cache
  1448. self._add_to_cache(txn, events_and_contexts)
  1449. def _add_to_cache(
  1450. self,
  1451. txn: LoggingTransaction,
  1452. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1453. ) -> None:
  1454. to_prefill = []
  1455. rows = []
  1456. ev_map = {e.event_id: e for e, _ in events_and_contexts}
  1457. if not ev_map:
  1458. return
  1459. sql = (
  1460. "SELECT "
  1461. " e.event_id as event_id, "
  1462. " r.redacts as redacts,"
  1463. " rej.event_id as rejects "
  1464. " FROM events as e"
  1465. " LEFT JOIN rejections as rej USING (event_id)"
  1466. " LEFT JOIN redactions as r ON e.event_id = r.redacts"
  1467. " WHERE "
  1468. )
  1469. clause, args = make_in_list_sql_clause(
  1470. self.database_engine, "e.event_id", list(ev_map)
  1471. )
  1472. txn.execute(sql + clause, args)
  1473. rows = self.db_pool.cursor_to_dict(txn)
  1474. for row in rows:
  1475. event = ev_map[row["event_id"]]
  1476. if not row["rejects"] and not row["redacts"]:
  1477. to_prefill.append(EventCacheEntry(event=event, redacted_event=None))
  1478. async def external_prefill() -> None:
  1479. for cache_entry in to_prefill:
  1480. await self.store._get_event_cache.set_external(
  1481. (cache_entry.event.event_id,), cache_entry
  1482. )
  1483. def local_prefill() -> None:
  1484. for cache_entry in to_prefill:
  1485. self.store._get_event_cache.set_local(
  1486. (cache_entry.event.event_id,), cache_entry
  1487. )
  1488. # The order these are called here is not as important as knowing that after the
  1489. # transaction is finished, the async_call_after will run before the call_after.
  1490. txn.async_call_after(external_prefill)
  1491. txn.call_after(local_prefill)
  1492. def _store_redaction(self, txn: LoggingTransaction, event: EventBase) -> None:
  1493. assert event.redacts is not None
  1494. self.db_pool.simple_upsert_txn(
  1495. txn,
  1496. table="redactions",
  1497. keyvalues={"event_id": event.event_id},
  1498. values={
  1499. "redacts": event.redacts,
  1500. "received_ts": self._clock.time_msec(),
  1501. },
  1502. )
  1503. def insert_labels_for_event_txn(
  1504. self,
  1505. txn: LoggingTransaction,
  1506. event_id: str,
  1507. labels: List[str],
  1508. room_id: str,
  1509. topological_ordering: int,
  1510. ) -> None:
  1511. """Store the mapping between an event's ID and its labels, with one row per
  1512. (event_id, label) tuple.
  1513. Args:
  1514. txn: The transaction to execute.
  1515. event_id: The event's ID.
  1516. labels: A list of text labels.
  1517. room_id: The ID of the room the event was sent to.
  1518. topological_ordering: The position of the event in the room's topology.
  1519. """
  1520. self.db_pool.simple_insert_many_txn(
  1521. txn=txn,
  1522. table="event_labels",
  1523. keys=("event_id", "label", "room_id", "topological_ordering"),
  1524. values=[
  1525. (event_id, label, room_id, topological_ordering) for label in labels
  1526. ],
  1527. )
  1528. def _insert_event_expiry_txn(
  1529. self, txn: LoggingTransaction, event_id: str, expiry_ts: int
  1530. ) -> None:
  1531. """Save the expiry timestamp associated with a given event ID.
  1532. Args:
  1533. txn: The database transaction to use.
  1534. event_id: The event ID the expiry timestamp is associated with.
  1535. expiry_ts: The timestamp at which to expire (delete) the event.
  1536. """
  1537. self.db_pool.simple_insert_txn(
  1538. txn=txn,
  1539. table="event_expiry",
  1540. values={"event_id": event_id, "expiry_ts": expiry_ts},
  1541. )
  1542. def _store_room_members_txn(
  1543. self,
  1544. txn: LoggingTransaction,
  1545. events: List[EventBase],
  1546. *,
  1547. inhibit_local_membership_updates: bool = False,
  1548. ) -> None:
  1549. """
  1550. Store a room member in the database.
  1551. Args:
  1552. txn: The transaction to use.
  1553. events: List of events to store.
  1554. inhibit_local_membership_updates: Stop the local_current_membership
  1555. from being updated by these events. This should be set to True
  1556. for backfilled events because backfilled events in the past do
  1557. not affect the current local state.
  1558. """
  1559. self.db_pool.simple_insert_many_txn(
  1560. txn,
  1561. table="room_memberships",
  1562. keys=(
  1563. "event_id",
  1564. "event_stream_ordering",
  1565. "user_id",
  1566. "sender",
  1567. "room_id",
  1568. "membership",
  1569. "display_name",
  1570. "avatar_url",
  1571. ),
  1572. values=[
  1573. (
  1574. event.event_id,
  1575. event.internal_metadata.stream_ordering,
  1576. event.state_key,
  1577. event.user_id,
  1578. event.room_id,
  1579. event.membership,
  1580. non_null_str_or_none(event.content.get("displayname")),
  1581. non_null_str_or_none(event.content.get("avatar_url")),
  1582. )
  1583. for event in events
  1584. ],
  1585. )
  1586. for event in events:
  1587. assert event.internal_metadata.stream_ordering is not None
  1588. # We update the local_current_membership table only if the event is
  1589. # "current", i.e., its something that has just happened.
  1590. #
  1591. # This will usually get updated by the `current_state_events` handling,
  1592. # unless its an outlier, and an outlier is only "current" if it's an "out of
  1593. # band membership", like a remote invite or a rejection of a remote invite.
  1594. if (
  1595. self.is_mine_id(event.state_key)
  1596. and not inhibit_local_membership_updates
  1597. and event.internal_metadata.is_outlier()
  1598. and event.internal_metadata.is_out_of_band_membership()
  1599. ):
  1600. self.db_pool.simple_upsert_txn(
  1601. txn,
  1602. table="local_current_membership",
  1603. keyvalues={"room_id": event.room_id, "user_id": event.state_key},
  1604. values={
  1605. "event_id": event.event_id,
  1606. "event_stream_ordering": event.internal_metadata.stream_ordering,
  1607. "membership": event.membership,
  1608. },
  1609. )
  1610. def _handle_event_relations(
  1611. self, txn: LoggingTransaction, event: EventBase
  1612. ) -> None:
  1613. """Handles inserting relation data during persistence of events
  1614. Args:
  1615. txn: The current database transaction.
  1616. event: The event which might have relations.
  1617. """
  1618. relation = relation_from_event(event)
  1619. if not relation:
  1620. # No relation, nothing to do.
  1621. return
  1622. self.db_pool.simple_insert_txn(
  1623. txn,
  1624. table="event_relations",
  1625. values={
  1626. "event_id": event.event_id,
  1627. "relates_to_id": relation.parent_id,
  1628. "relation_type": relation.rel_type,
  1629. "aggregation_key": relation.aggregation_key,
  1630. },
  1631. )
  1632. if relation.rel_type == RelationTypes.THREAD:
  1633. # Upsert into the threads table, but only overwrite the value if the
  1634. # new event is of a later topological order OR if the topological
  1635. # ordering is equal, but the stream ordering is later.
  1636. sql = """
  1637. INSERT INTO threads (room_id, thread_id, latest_event_id, topological_ordering, stream_ordering)
  1638. VALUES (?, ?, ?, ?, ?)
  1639. ON CONFLICT (room_id, thread_id)
  1640. DO UPDATE SET
  1641. latest_event_id = excluded.latest_event_id,
  1642. topological_ordering = excluded.topological_ordering,
  1643. stream_ordering = excluded.stream_ordering
  1644. WHERE
  1645. threads.topological_ordering <= excluded.topological_ordering AND
  1646. threads.stream_ordering < excluded.stream_ordering
  1647. """
  1648. txn.execute(
  1649. sql,
  1650. (
  1651. event.room_id,
  1652. relation.parent_id,
  1653. event.event_id,
  1654. event.depth,
  1655. event.internal_metadata.stream_ordering,
  1656. ),
  1657. )
  1658. def _handle_redact_relations(
  1659. self, txn: LoggingTransaction, room_id: str, redacted_event_id: str
  1660. ) -> None:
  1661. """Handles receiving a redaction and checking whether the redacted event
  1662. has any relations which must be removed from the database.
  1663. Args:
  1664. txn
  1665. room_id: The room ID of the event that was redacted.
  1666. redacted_event_id: The event that was redacted.
  1667. """
  1668. # Fetch the relation of the event being redacted.
  1669. row = self.db_pool.simple_select_one_txn(
  1670. txn,
  1671. table="event_relations",
  1672. keyvalues={"event_id": redacted_event_id},
  1673. retcols=("relates_to_id", "relation_type"),
  1674. allow_none=True,
  1675. )
  1676. # Nothing to do if no relation is found.
  1677. if row is None:
  1678. return
  1679. redacted_relates_to = row["relates_to_id"]
  1680. rel_type = row["relation_type"]
  1681. self.db_pool.simple_delete_txn(
  1682. txn, table="event_relations", keyvalues={"event_id": redacted_event_id}
  1683. )
  1684. # Any relation information for the related event must be cleared.
  1685. self.store._invalidate_cache_and_stream(
  1686. txn, self.store.get_relations_for_event, (redacted_relates_to,)
  1687. )
  1688. if rel_type == RelationTypes.REFERENCE:
  1689. self.store._invalidate_cache_and_stream(
  1690. txn, self.store.get_references_for_event, (redacted_relates_to,)
  1691. )
  1692. if rel_type == RelationTypes.REPLACE:
  1693. self.store._invalidate_cache_and_stream(
  1694. txn, self.store.get_applicable_edit, (redacted_relates_to,)
  1695. )
  1696. if rel_type == RelationTypes.THREAD:
  1697. self.store._invalidate_cache_and_stream(
  1698. txn, self.store.get_thread_summary, (redacted_relates_to,)
  1699. )
  1700. self.store._invalidate_cache_and_stream(
  1701. txn, self.store.get_thread_participated, (redacted_relates_to,)
  1702. )
  1703. self.store._invalidate_cache_and_stream(
  1704. txn, self.store.get_threads, (room_id,)
  1705. )
  1706. # Find the new latest event in the thread.
  1707. sql = """
  1708. SELECT event_id, topological_ordering, stream_ordering
  1709. FROM event_relations
  1710. INNER JOIN events USING (event_id)
  1711. WHERE relates_to_id = ? AND relation_type = ?
  1712. ORDER BY topological_ordering DESC, stream_ordering DESC
  1713. LIMIT 1
  1714. """
  1715. txn.execute(sql, (redacted_relates_to, RelationTypes.THREAD))
  1716. # If a latest event is found, update the threads table, this might
  1717. # be the same current latest event (if an earlier event in the thread
  1718. # was redacted).
  1719. latest_event_row = txn.fetchone()
  1720. if latest_event_row:
  1721. self.db_pool.simple_upsert_txn(
  1722. txn,
  1723. table="threads",
  1724. keyvalues={"room_id": room_id, "thread_id": redacted_relates_to},
  1725. values={
  1726. "latest_event_id": latest_event_row[0],
  1727. "topological_ordering": latest_event_row[1],
  1728. "stream_ordering": latest_event_row[2],
  1729. },
  1730. )
  1731. # Otherwise, delete the thread: it no longer exists.
  1732. else:
  1733. self.db_pool.simple_delete_one_txn(
  1734. txn, table="threads", keyvalues={"thread_id": redacted_relates_to}
  1735. )
  1736. def _store_room_topic_txn(self, txn: LoggingTransaction, event: EventBase) -> None:
  1737. if isinstance(event.content.get("topic"), str):
  1738. self.store_event_search_txn(
  1739. txn, event, "content.topic", event.content["topic"]
  1740. )
  1741. def _store_room_name_txn(self, txn: LoggingTransaction, event: EventBase) -> None:
  1742. if isinstance(event.content.get("name"), str):
  1743. self.store_event_search_txn(
  1744. txn, event, "content.name", event.content["name"]
  1745. )
  1746. def _store_room_message_txn(
  1747. self, txn: LoggingTransaction, event: EventBase
  1748. ) -> None:
  1749. if isinstance(event.content.get("body"), str):
  1750. self.store_event_search_txn(
  1751. txn, event, "content.body", event.content["body"]
  1752. )
  1753. def _store_retention_policy_for_room_txn(
  1754. self, txn: LoggingTransaction, event: EventBase
  1755. ) -> None:
  1756. if not event.is_state():
  1757. logger.debug("Ignoring non-state m.room.retention event")
  1758. return
  1759. if hasattr(event, "content") and (
  1760. "min_lifetime" in event.content or "max_lifetime" in event.content
  1761. ):
  1762. if (
  1763. "min_lifetime" in event.content
  1764. and type(event.content["min_lifetime"]) is not int # noqa: E721
  1765. ) or (
  1766. "max_lifetime" in event.content
  1767. and type(event.content["max_lifetime"]) is not int # noqa: E721
  1768. ):
  1769. # Ignore the event if one of the value isn't an integer.
  1770. return
  1771. self.db_pool.simple_insert_txn(
  1772. txn=txn,
  1773. table="room_retention",
  1774. values={
  1775. "room_id": event.room_id,
  1776. "event_id": event.event_id,
  1777. "min_lifetime": event.content.get("min_lifetime"),
  1778. "max_lifetime": event.content.get("max_lifetime"),
  1779. },
  1780. )
  1781. self.store._invalidate_cache_and_stream(
  1782. txn, self.store.get_retention_policy_for_room, (event.room_id,)
  1783. )
  1784. def store_event_search_txn(
  1785. self, txn: LoggingTransaction, event: EventBase, key: str, value: str
  1786. ) -> None:
  1787. """Add event to the search table
  1788. Args:
  1789. txn: The database transaction.
  1790. event: The event being added to the search table.
  1791. key: A key describing the search value (one of "content.name",
  1792. "content.topic", or "content.body")
  1793. value: The value from the event's content.
  1794. """
  1795. self.store.store_search_entries_txn(
  1796. txn,
  1797. (
  1798. SearchEntry(
  1799. key=key,
  1800. value=value,
  1801. event_id=event.event_id,
  1802. room_id=event.room_id,
  1803. stream_ordering=event.internal_metadata.stream_ordering,
  1804. origin_server_ts=event.origin_server_ts,
  1805. ),
  1806. ),
  1807. )
  1808. def _set_push_actions_for_event_and_users_txn(
  1809. self,
  1810. txn: LoggingTransaction,
  1811. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1812. all_events_and_contexts: List[Tuple[EventBase, EventContext]],
  1813. ) -> None:
  1814. """Handles moving push actions from staging table to main
  1815. event_push_actions table for all events in `events_and_contexts`.
  1816. Also ensures that all events in `all_events_and_contexts` are removed
  1817. from the push action staging area.
  1818. Args:
  1819. events_and_contexts: events we are persisting
  1820. all_events_and_contexts: all events that we were going to persist.
  1821. This includes events we've already persisted, etc, that wouldn't
  1822. appear in events_and_context.
  1823. """
  1824. # Only notifiable events will have push actions associated with them,
  1825. # so let's filter them out. (This makes joining large rooms faster, as
  1826. # these queries took seconds to process all the state events).
  1827. notifiable_events = [
  1828. event
  1829. for event, _ in events_and_contexts
  1830. if event.internal_metadata.is_notifiable()
  1831. ]
  1832. sql = """
  1833. INSERT INTO event_push_actions (
  1834. room_id, event_id, user_id, actions, stream_ordering,
  1835. topological_ordering, notif, highlight, unread, thread_id
  1836. )
  1837. SELECT ?, event_id, user_id, actions, ?, ?, notif, highlight, unread, thread_id
  1838. FROM event_push_actions_staging
  1839. WHERE event_id = ?
  1840. """
  1841. if notifiable_events:
  1842. txn.execute_batch(
  1843. sql,
  1844. (
  1845. (
  1846. event.room_id,
  1847. event.internal_metadata.stream_ordering,
  1848. event.depth,
  1849. event.event_id,
  1850. )
  1851. for event in notifiable_events
  1852. ),
  1853. )
  1854. # Now we delete the staging area for *all* events that were being
  1855. # persisted.
  1856. txn.execute_batch(
  1857. "DELETE FROM event_push_actions_staging WHERE event_id = ?",
  1858. (
  1859. (event.event_id,)
  1860. for event, _ in all_events_and_contexts
  1861. if event.internal_metadata.is_notifiable()
  1862. ),
  1863. )
  1864. def _remove_push_actions_for_event_id_txn(
  1865. self, txn: LoggingTransaction, room_id: str, event_id: str
  1866. ) -> None:
  1867. txn.execute(
  1868. "DELETE FROM event_push_actions WHERE room_id = ? AND event_id = ?",
  1869. (room_id, event_id),
  1870. )
  1871. def _store_rejections_txn(
  1872. self, txn: LoggingTransaction, event_id: str, reason: str
  1873. ) -> None:
  1874. self.db_pool.simple_insert_txn(
  1875. txn,
  1876. table="rejections",
  1877. values={
  1878. "event_id": event_id,
  1879. "reason": reason,
  1880. "last_check": self._clock.time_msec(),
  1881. },
  1882. )
  1883. def _store_event_state_mappings_txn(
  1884. self,
  1885. txn: LoggingTransaction,
  1886. events_and_contexts: Collection[Tuple[EventBase, EventContext]],
  1887. ) -> None:
  1888. """
  1889. Raises:
  1890. PartialStateConflictError: if attempting to persist a partial state event in
  1891. a room that has been un-partial stated.
  1892. """
  1893. state_groups = {}
  1894. for event, context in events_and_contexts:
  1895. if event.internal_metadata.is_outlier():
  1896. # double-check that we don't have any events that claim to be outliers
  1897. # *and* have partial state (which is meaningless: we should have no
  1898. # state at all for an outlier)
  1899. if context.partial_state:
  1900. raise ValueError(
  1901. "Outlier event %s claims to have partial state", event.event_id
  1902. )
  1903. continue
  1904. # if the event was rejected, just give it the same state as its
  1905. # predecessor.
  1906. if context.rejected:
  1907. state_groups[event.event_id] = context.state_group_before_event
  1908. continue
  1909. state_groups[event.event_id] = context.state_group
  1910. # if we have partial state for these events, record the fact. (This happens
  1911. # here rather than in _store_event_txn because it also needs to happen when
  1912. # we de-outlier an event.)
  1913. try:
  1914. self.db_pool.simple_insert_many_txn(
  1915. txn,
  1916. table="partial_state_events",
  1917. keys=("room_id", "event_id"),
  1918. values=[
  1919. (
  1920. event.room_id,
  1921. event.event_id,
  1922. )
  1923. for event, ctx in events_and_contexts
  1924. if ctx.partial_state
  1925. ],
  1926. )
  1927. except self.db_pool.engine.module.IntegrityError:
  1928. logger.info(
  1929. "Cannot persist events %s in rooms %s: room has been un-partial stated",
  1930. [
  1931. event.event_id
  1932. for event, ctx in events_and_contexts
  1933. if ctx.partial_state
  1934. ],
  1935. list(
  1936. {
  1937. event.room_id
  1938. for event, ctx in events_and_contexts
  1939. if ctx.partial_state
  1940. }
  1941. ),
  1942. )
  1943. raise PartialStateConflictError()
  1944. self.db_pool.simple_upsert_many_txn(
  1945. txn,
  1946. table="event_to_state_groups",
  1947. key_names=["event_id"],
  1948. key_values=[[event_id] for event_id, _ in state_groups.items()],
  1949. value_names=["state_group"],
  1950. value_values=[
  1951. [state_group_id] for _, state_group_id in state_groups.items()
  1952. ],
  1953. )
  1954. for event_id, state_group_id in state_groups.items():
  1955. txn.call_after(
  1956. self.store._get_state_group_for_event.prefill,
  1957. (event_id,),
  1958. state_group_id,
  1959. )
  1960. def _update_min_depth_for_room_txn(
  1961. self, txn: LoggingTransaction, room_id: str, depth: int
  1962. ) -> None:
  1963. min_depth = self.store._get_min_depth_interaction(txn, room_id)
  1964. if min_depth is not None and depth >= min_depth:
  1965. return
  1966. self.db_pool.simple_upsert_txn(
  1967. txn,
  1968. table="room_depth",
  1969. keyvalues={"room_id": room_id},
  1970. values={"min_depth": depth},
  1971. )
  1972. def _handle_mult_prev_events(
  1973. self, txn: LoggingTransaction, events: List[EventBase]
  1974. ) -> None:
  1975. """
  1976. For the given event, update the event edges table and forward and
  1977. backward extremities tables.
  1978. """
  1979. self.db_pool.simple_insert_many_txn(
  1980. txn,
  1981. table="event_edges",
  1982. keys=("event_id", "prev_event_id"),
  1983. values=[
  1984. (ev.event_id, e_id) for ev in events for e_id in ev.prev_event_ids()
  1985. ],
  1986. )
  1987. self._update_backward_extremeties(txn, events)
  1988. def _update_backward_extremeties(
  1989. self, txn: LoggingTransaction, events: List[EventBase]
  1990. ) -> None:
  1991. """Updates the event_backward_extremities tables based on the new/updated
  1992. events being persisted.
  1993. This is called for new events *and* for events that were outliers, but
  1994. are now being persisted as non-outliers.
  1995. Forward extremities are handled when we first start persisting the events.
  1996. """
  1997. # From the events passed in, add all of the prev events as backwards extremities.
  1998. # Ignore any events that are already backwards extrems or outliers.
  1999. query = (
  2000. "INSERT INTO event_backward_extremities (event_id, room_id)"
  2001. " SELECT ?, ? WHERE NOT EXISTS ("
  2002. " SELECT 1 FROM event_backward_extremities"
  2003. " WHERE event_id = ? AND room_id = ?"
  2004. " )"
  2005. # 1. Don't add an event as a extremity again if we already persisted it
  2006. # as a non-outlier.
  2007. # 2. Don't add an outlier as an extremity if it has no prev_events
  2008. " AND NOT EXISTS ("
  2009. " SELECT 1 FROM events"
  2010. " LEFT JOIN event_edges edge"
  2011. " ON edge.event_id = events.event_id"
  2012. " WHERE events.event_id = ? AND events.room_id = ? AND (events.outlier = FALSE OR edge.event_id IS NULL)"
  2013. " )"
  2014. )
  2015. txn.execute_batch(
  2016. query,
  2017. [
  2018. (e_id, ev.room_id, e_id, ev.room_id, e_id, ev.room_id)
  2019. for ev in events
  2020. for e_id in ev.prev_event_ids()
  2021. if not ev.internal_metadata.is_outlier()
  2022. ],
  2023. )
  2024. # Delete all these events that we've already fetched and now know that their
  2025. # prev events are the new backwards extremeties.
  2026. query = (
  2027. "DELETE FROM event_backward_extremities"
  2028. " WHERE event_id = ? AND room_id = ?"
  2029. )
  2030. backward_extremity_tuples_to_remove = [
  2031. (ev.event_id, ev.room_id)
  2032. for ev in events
  2033. if not ev.internal_metadata.is_outlier()
  2034. # If we encountered an event with no prev_events, then we might
  2035. # as well remove it now because it won't ever have anything else
  2036. # to backfill from.
  2037. or len(ev.prev_event_ids()) == 0
  2038. ]
  2039. txn.execute_batch(
  2040. query,
  2041. backward_extremity_tuples_to_remove,
  2042. )
  2043. # Clear out the failed backfill attempts after we successfully pulled
  2044. # the event. Since we no longer need these events as backward
  2045. # extremities, it also means that they won't be backfilled from again so
  2046. # we no longer need to store the backfill attempts around it.
  2047. query = """
  2048. DELETE FROM event_failed_pull_attempts
  2049. WHERE event_id = ? and room_id = ?
  2050. """
  2051. txn.execute_batch(
  2052. query,
  2053. backward_extremity_tuples_to_remove,
  2054. )
  2055. @attr.s(slots=True, auto_attribs=True)
  2056. class _LinkMap:
  2057. """A helper type for tracking links between chains."""
  2058. # Stores the set of links as nested maps: source chain ID -> target chain ID
  2059. # -> source sequence number -> target sequence number.
  2060. maps: Dict[int, Dict[int, Dict[int, int]]] = attr.Factory(dict)
  2061. # Stores the links that have been added (with new set to true), as tuples of
  2062. # `(source chain ID, source sequence no, target chain ID, target sequence no.)`
  2063. additions: Set[Tuple[int, int, int, int]] = attr.Factory(set)
  2064. def add_link(
  2065. self,
  2066. src_tuple: Tuple[int, int],
  2067. target_tuple: Tuple[int, int],
  2068. new: bool = True,
  2069. ) -> bool:
  2070. """Add a new link between two chains, ensuring no redundant links are added.
  2071. New links should be added in topological order.
  2072. Args:
  2073. src_tuple: The chain ID/sequence number of the source of the link.
  2074. target_tuple: The chain ID/sequence number of the target of the link.
  2075. new: Whether this is a "new" link, i.e. should it be returned
  2076. by `get_additions`.
  2077. Returns:
  2078. True if a link was added, false if the given link was dropped as redundant
  2079. """
  2080. src_chain, src_seq = src_tuple
  2081. target_chain, target_seq = target_tuple
  2082. current_links = self.maps.setdefault(src_chain, {}).setdefault(target_chain, {})
  2083. assert src_chain != target_chain
  2084. if new:
  2085. # Check if the new link is redundant
  2086. for current_seq_src, current_seq_target in current_links.items():
  2087. # If a link "crosses" another link then its redundant. For example
  2088. # in the following link 1 (L1) is redundant, as any event reachable
  2089. # via L1 is *also* reachable via L2.
  2090. #
  2091. # Chain A Chain B
  2092. # | |
  2093. # L1 |------ |
  2094. # | | |
  2095. # L2 |---- | -->|
  2096. # | | |
  2097. # | |--->|
  2098. # | |
  2099. # | |
  2100. #
  2101. # So we only need to keep links which *do not* cross, i.e. links
  2102. # that both start and end above or below an existing link.
  2103. #
  2104. # Note, since we add links in topological ordering we should never
  2105. # see `src_seq` less than `current_seq_src`.
  2106. if current_seq_src <= src_seq and target_seq <= current_seq_target:
  2107. # This new link is redundant, nothing to do.
  2108. return False
  2109. self.additions.add((src_chain, src_seq, target_chain, target_seq))
  2110. current_links[src_seq] = target_seq
  2111. return True
  2112. def get_links_from(
  2113. self, src_tuple: Tuple[int, int]
  2114. ) -> Generator[Tuple[int, int], None, None]:
  2115. """Gets the chains reachable from the given chain/sequence number.
  2116. Yields:
  2117. The chain ID and sequence number the link points to.
  2118. """
  2119. src_chain, src_seq = src_tuple
  2120. for target_id, sequence_numbers in self.maps.get(src_chain, {}).items():
  2121. for link_src_seq, target_seq in sequence_numbers.items():
  2122. if link_src_seq <= src_seq:
  2123. yield target_id, target_seq
  2124. def get_links_between(
  2125. self, source_chain: int, target_chain: int
  2126. ) -> Generator[Tuple[int, int], None, None]:
  2127. """Gets the links between two chains.
  2128. Yields:
  2129. The source and target sequence numbers.
  2130. """
  2131. yield from self.maps.get(source_chain, {}).get(target_chain, {}).items()
  2132. def get_additions(self) -> Generator[Tuple[int, int, int, int], None, None]:
  2133. """Gets any newly added links.
  2134. Yields:
  2135. The source chain ID/sequence number and target chain ID/sequence number
  2136. """
  2137. for src_chain, src_seq, target_chain, _ in self.additions:
  2138. target_seq = self.maps.get(src_chain, {}).get(target_chain, {}).get(src_seq)
  2139. if target_seq is not None:
  2140. yield (src_chain, src_seq, target_chain, target_seq)
  2141. def exists_path_from(
  2142. self,
  2143. src_tuple: Tuple[int, int],
  2144. target_tuple: Tuple[int, int],
  2145. ) -> bool:
  2146. """Checks if there is a path between the source chain ID/sequence and
  2147. target chain ID/sequence.
  2148. """
  2149. src_chain, src_seq = src_tuple
  2150. target_chain, target_seq = target_tuple
  2151. if src_chain == target_chain:
  2152. return target_seq <= src_seq
  2153. links = self.get_links_between(src_chain, target_chain)
  2154. for link_start_seq, link_end_seq in links:
  2155. if link_start_seq <= src_seq and target_seq <= link_end_seq:
  2156. return True
  2157. return False