Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

2493 рядки
96 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,), list(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_token_id: List[Tuple[str, str, str, int, str, int]] = []
  849. to_insert_device_id: List[Tuple[str, str, str, str, str, int]] = []
  850. for event, _ in events_and_contexts:
  851. txn_id = getattr(event.internal_metadata, "txn_id", None)
  852. token_id = getattr(event.internal_metadata, "token_id", None)
  853. device_id = getattr(event.internal_metadata, "device_id", None)
  854. if txn_id is not None:
  855. if token_id is not None:
  856. to_insert_token_id.append(
  857. (
  858. event.event_id,
  859. event.room_id,
  860. event.sender,
  861. token_id,
  862. txn_id,
  863. inserted_ts,
  864. )
  865. )
  866. if device_id is not None:
  867. to_insert_device_id.append(
  868. (
  869. event.event_id,
  870. event.room_id,
  871. event.sender,
  872. device_id,
  873. txn_id,
  874. inserted_ts,
  875. )
  876. )
  877. # Synapse usually relies on the device_id to scope transactions for events,
  878. # except for users without device IDs (appservice, guests, and access
  879. # tokens minted with the admin API) which use the access token ID instead.
  880. #
  881. # TODO https://github.com/matrix-org/synapse/issues/16042
  882. if to_insert_token_id:
  883. self.db_pool.simple_insert_many_txn(
  884. txn,
  885. table="event_txn_id",
  886. keys=(
  887. "event_id",
  888. "room_id",
  889. "user_id",
  890. "token_id",
  891. "txn_id",
  892. "inserted_ts",
  893. ),
  894. values=to_insert_token_id,
  895. )
  896. if to_insert_device_id:
  897. self.db_pool.simple_insert_many_txn(
  898. txn,
  899. table="event_txn_id_device_id",
  900. keys=(
  901. "event_id",
  902. "room_id",
  903. "user_id",
  904. "device_id",
  905. "txn_id",
  906. "inserted_ts",
  907. ),
  908. values=to_insert_device_id,
  909. )
  910. async def update_current_state(
  911. self,
  912. room_id: str,
  913. state_delta: DeltaState,
  914. ) -> None:
  915. """Update the current state stored in the datatabase for the given room"""
  916. async with self._stream_id_gen.get_next() as stream_ordering:
  917. await self.db_pool.runInteraction(
  918. "update_current_state",
  919. self._update_current_state_txn,
  920. state_delta_by_room={room_id: state_delta},
  921. stream_id=stream_ordering,
  922. )
  923. def _update_current_state_txn(
  924. self,
  925. txn: LoggingTransaction,
  926. state_delta_by_room: Dict[str, DeltaState],
  927. stream_id: int,
  928. ) -> None:
  929. for room_id, delta_state in state_delta_by_room.items():
  930. to_delete = delta_state.to_delete
  931. to_insert = delta_state.to_insert
  932. # Figure out the changes of membership to invalidate the
  933. # `get_rooms_for_user` cache.
  934. # We find out which membership events we may have deleted
  935. # and which we have added, then we invalidate the caches for all
  936. # those users.
  937. members_changed = {
  938. state_key
  939. for ev_type, state_key in itertools.chain(to_delete, to_insert)
  940. if ev_type == EventTypes.Member
  941. }
  942. if delta_state.no_longer_in_room:
  943. # Server is no longer in the room so we delete the room from
  944. # current_state_events, being careful we've already updated the
  945. # rooms.room_version column (which gets populated in a
  946. # background task).
  947. self._upsert_room_version_txn(txn, room_id)
  948. # Before deleting we populate the current_state_delta_stream
  949. # so that async background tasks get told what happened.
  950. sql = """
  951. INSERT INTO current_state_delta_stream
  952. (stream_id, instance_name, room_id, type, state_key, event_id, prev_event_id)
  953. SELECT ?, ?, room_id, type, state_key, null, event_id
  954. FROM current_state_events
  955. WHERE room_id = ?
  956. """
  957. txn.execute(sql, (stream_id, self._instance_name, room_id))
  958. # We also want to invalidate the membership caches for users
  959. # that were in the room.
  960. users_in_room = self.store.get_users_in_room_txn(txn, room_id)
  961. members_changed.update(users_in_room)
  962. self.db_pool.simple_delete_txn(
  963. txn,
  964. table="current_state_events",
  965. keyvalues={"room_id": room_id},
  966. )
  967. else:
  968. # We're still in the room, so we update the current state as normal.
  969. # First we add entries to the current_state_delta_stream. We
  970. # do this before updating the current_state_events table so
  971. # that we can use it to calculate the `prev_event_id`. (This
  972. # allows us to not have to pull out the existing state
  973. # unnecessarily).
  974. #
  975. # The stream_id for the update is chosen to be the minimum of the stream_ids
  976. # for the batch of the events that we are persisting; that means we do not
  977. # end up in a situation where workers see events before the
  978. # current_state_delta updates.
  979. #
  980. sql = """
  981. INSERT INTO current_state_delta_stream
  982. (stream_id, instance_name, room_id, type, state_key, event_id, prev_event_id)
  983. SELECT ?, ?, ?, ?, ?, ?, (
  984. SELECT event_id FROM current_state_events
  985. WHERE room_id = ? AND type = ? AND state_key = ?
  986. )
  987. """
  988. txn.execute_batch(
  989. sql,
  990. (
  991. (
  992. stream_id,
  993. self._instance_name,
  994. room_id,
  995. etype,
  996. state_key,
  997. to_insert.get((etype, state_key)),
  998. room_id,
  999. etype,
  1000. state_key,
  1001. )
  1002. for etype, state_key in itertools.chain(to_delete, to_insert)
  1003. ),
  1004. )
  1005. # Now we actually update the current_state_events table
  1006. txn.execute_batch(
  1007. "DELETE FROM current_state_events"
  1008. " WHERE room_id = ? AND type = ? AND state_key = ?",
  1009. (
  1010. (room_id, etype, state_key)
  1011. for etype, state_key in itertools.chain(to_delete, to_insert)
  1012. ),
  1013. )
  1014. # We include the membership in the current state table, hence we do
  1015. # a lookup when we insert. This assumes that all events have already
  1016. # been inserted into room_memberships.
  1017. txn.execute_batch(
  1018. """INSERT INTO current_state_events
  1019. (room_id, type, state_key, event_id, membership, event_stream_ordering)
  1020. VALUES (
  1021. ?, ?, ?, ?,
  1022. (SELECT membership FROM room_memberships WHERE event_id = ?),
  1023. (SELECT stream_ordering FROM events WHERE event_id = ?)
  1024. )
  1025. """,
  1026. [
  1027. (room_id, key[0], key[1], ev_id, ev_id, ev_id)
  1028. for key, ev_id in to_insert.items()
  1029. ],
  1030. )
  1031. # We now update `local_current_membership`. We do this regardless
  1032. # of whether we're still in the room or not to handle the case where
  1033. # e.g. we just got banned (where we need to record that fact here).
  1034. # Note: Do we really want to delete rows here (that we do not
  1035. # subsequently reinsert below)? While technically correct it means
  1036. # we have no record of the fact the user *was* a member of the
  1037. # room but got, say, state reset out of it.
  1038. if to_delete or to_insert:
  1039. txn.execute_batch(
  1040. "DELETE FROM local_current_membership"
  1041. " WHERE room_id = ? AND user_id = ?",
  1042. (
  1043. (room_id, state_key)
  1044. for etype, state_key in itertools.chain(to_delete, to_insert)
  1045. if etype == EventTypes.Member and self.is_mine_id(state_key)
  1046. ),
  1047. )
  1048. if to_insert:
  1049. txn.execute_batch(
  1050. """INSERT INTO local_current_membership
  1051. (room_id, user_id, event_id, membership, event_stream_ordering)
  1052. VALUES (
  1053. ?, ?, ?,
  1054. (SELECT membership FROM room_memberships WHERE event_id = ?),
  1055. (SELECT stream_ordering FROM events WHERE event_id = ?)
  1056. )
  1057. """,
  1058. [
  1059. (room_id, key[1], ev_id, ev_id, ev_id)
  1060. for key, ev_id in to_insert.items()
  1061. if key[0] == EventTypes.Member and self.is_mine_id(key[1])
  1062. ],
  1063. )
  1064. txn.call_after(
  1065. self.store._curr_state_delta_stream_cache.entity_has_changed,
  1066. room_id,
  1067. stream_id,
  1068. )
  1069. # Invalidate the various caches
  1070. self.store._invalidate_state_caches_and_stream(
  1071. txn, room_id, members_changed
  1072. )
  1073. # Check if any of the remote membership changes requires us to
  1074. # unsubscribe from their device lists.
  1075. self.store.handle_potentially_left_users_txn(
  1076. txn, {m for m in members_changed if not self.hs.is_mine_id(m)}
  1077. )
  1078. def _upsert_room_version_txn(self, txn: LoggingTransaction, room_id: str) -> None:
  1079. """Update the room version in the database based off current state
  1080. events.
  1081. This is used when we're about to delete current state and we want to
  1082. ensure that the `rooms.room_version` column is up to date.
  1083. """
  1084. sql = """
  1085. SELECT json FROM event_json
  1086. INNER JOIN current_state_events USING (room_id, event_id)
  1087. WHERE room_id = ? AND type = ? AND state_key = ?
  1088. """
  1089. txn.execute(sql, (room_id, EventTypes.Create, ""))
  1090. row = txn.fetchone()
  1091. if row:
  1092. event_json = db_to_json(row[0])
  1093. content = event_json.get("content", {})
  1094. creator = content.get("creator")
  1095. room_version_id = content.get("room_version", RoomVersions.V1.identifier)
  1096. self.db_pool.simple_upsert_txn(
  1097. txn,
  1098. table="rooms",
  1099. keyvalues={"room_id": room_id},
  1100. values={"room_version": room_version_id},
  1101. insertion_values={"is_public": False, "creator": creator},
  1102. )
  1103. def _update_forward_extremities_txn(
  1104. self,
  1105. txn: LoggingTransaction,
  1106. new_forward_extremities: Dict[str, Set[str]],
  1107. max_stream_order: int,
  1108. ) -> None:
  1109. for room_id in new_forward_extremities.keys():
  1110. self.db_pool.simple_delete_txn(
  1111. txn, table="event_forward_extremities", keyvalues={"room_id": room_id}
  1112. )
  1113. self.db_pool.simple_insert_many_txn(
  1114. txn,
  1115. table="event_forward_extremities",
  1116. keys=("event_id", "room_id"),
  1117. values=[
  1118. (ev_id, room_id)
  1119. for room_id, new_extrem in new_forward_extremities.items()
  1120. for ev_id in new_extrem
  1121. ],
  1122. )
  1123. # We now insert into stream_ordering_to_exterm a mapping from room_id,
  1124. # new stream_ordering to new forward extremeties in the room.
  1125. # This allows us to later efficiently look up the forward extremeties
  1126. # for a room before a given stream_ordering
  1127. self.db_pool.simple_insert_many_txn(
  1128. txn,
  1129. table="stream_ordering_to_exterm",
  1130. keys=("room_id", "event_id", "stream_ordering"),
  1131. values=[
  1132. (room_id, event_id, max_stream_order)
  1133. for room_id, new_extrem in new_forward_extremities.items()
  1134. for event_id in new_extrem
  1135. ],
  1136. )
  1137. @classmethod
  1138. def _filter_events_and_contexts_for_duplicates(
  1139. cls, events_and_contexts: List[Tuple[EventBase, EventContext]]
  1140. ) -> List[Tuple[EventBase, EventContext]]:
  1141. """Ensure that we don't have the same event twice.
  1142. Pick the earliest non-outlier if there is one, else the earliest one.
  1143. Args:
  1144. events_and_contexts:
  1145. Returns:
  1146. filtered list
  1147. """
  1148. new_events_and_contexts: OrderedDict[
  1149. str, Tuple[EventBase, EventContext]
  1150. ] = OrderedDict()
  1151. for event, context in events_and_contexts:
  1152. prev_event_context = new_events_and_contexts.get(event.event_id)
  1153. if prev_event_context:
  1154. if not event.internal_metadata.is_outlier():
  1155. if prev_event_context[0].internal_metadata.is_outlier():
  1156. # To ensure correct ordering we pop, as OrderedDict is
  1157. # ordered by first insertion.
  1158. new_events_and_contexts.pop(event.event_id, None)
  1159. new_events_and_contexts[event.event_id] = (event, context)
  1160. else:
  1161. new_events_and_contexts[event.event_id] = (event, context)
  1162. return list(new_events_and_contexts.values())
  1163. def _update_room_depths_txn(
  1164. self,
  1165. txn: LoggingTransaction,
  1166. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1167. ) -> None:
  1168. """Update min_depth for each room
  1169. Args:
  1170. txn: db connection
  1171. events_and_contexts: events we are persisting
  1172. """
  1173. depth_updates: Dict[str, int] = {}
  1174. for event, context in events_and_contexts:
  1175. # Then update the `stream_ordering` position to mark the latest
  1176. # event as the front of the room. This should not be done for
  1177. # backfilled events because backfilled events have negative
  1178. # stream_ordering and happened in the past so we know that we don't
  1179. # need to update the stream_ordering tip/front for the room.
  1180. assert event.internal_metadata.stream_ordering is not None
  1181. if event.internal_metadata.stream_ordering >= 0:
  1182. txn.call_after(
  1183. self.store._events_stream_cache.entity_has_changed,
  1184. event.room_id,
  1185. event.internal_metadata.stream_ordering,
  1186. )
  1187. if not event.internal_metadata.is_outlier() and not context.rejected:
  1188. depth_updates[event.room_id] = max(
  1189. event.depth, depth_updates.get(event.room_id, event.depth)
  1190. )
  1191. for room_id, depth in depth_updates.items():
  1192. self._update_min_depth_for_room_txn(txn, room_id, depth)
  1193. def _update_outliers_txn(
  1194. self,
  1195. txn: LoggingTransaction,
  1196. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1197. ) -> List[Tuple[EventBase, EventContext]]:
  1198. """Update any outliers with new event info.
  1199. This turns outliers into ex-outliers (unless the new event was rejected), and
  1200. also removes any other events we have already seen from the list.
  1201. Args:
  1202. txn: db connection
  1203. events_and_contexts: events we are persisting
  1204. Returns:
  1205. new list, without events which are already in the events table.
  1206. Raises:
  1207. PartialStateConflictError: if attempting to persist a partial state event in
  1208. a room that has been un-partial stated.
  1209. """
  1210. txn.execute(
  1211. "SELECT event_id, outlier FROM events WHERE event_id in (%s)"
  1212. % (",".join(["?"] * len(events_and_contexts)),),
  1213. [event.event_id for event, _ in events_and_contexts],
  1214. )
  1215. have_persisted = dict(cast(Iterable[Tuple[str, bool]], txn))
  1216. logger.debug(
  1217. "_update_outliers_txn: events=%s have_persisted=%s",
  1218. [ev.event_id for ev, _ in events_and_contexts],
  1219. have_persisted,
  1220. )
  1221. to_remove = set()
  1222. for event, context in events_and_contexts:
  1223. outlier_persisted = have_persisted.get(event.event_id)
  1224. logger.debug(
  1225. "_update_outliers_txn: event=%s outlier=%s outlier_persisted=%s",
  1226. event.event_id,
  1227. event.internal_metadata.is_outlier(),
  1228. outlier_persisted,
  1229. )
  1230. # Ignore events which we haven't persisted at all
  1231. if outlier_persisted is None:
  1232. continue
  1233. to_remove.add(event)
  1234. if context.rejected:
  1235. # If the incoming event is rejected then we don't care if the event
  1236. # was an outlier or not - what we have is at least as good.
  1237. continue
  1238. if not event.internal_metadata.is_outlier() and outlier_persisted:
  1239. # We received a copy of an event that we had already stored as
  1240. # an outlier in the database. We now have some state at that event
  1241. # so we need to update the state_groups table with that state.
  1242. #
  1243. # Note that we do not update the stream_ordering of the event in this
  1244. # scenario. XXX: does this cause bugs? It will mean we won't send such
  1245. # events down /sync. In general they will be historical events, so that
  1246. # doesn't matter too much, but that is not always the case.
  1247. logger.info(
  1248. "_update_outliers_txn: Updating state for ex-outlier event %s",
  1249. event.event_id,
  1250. )
  1251. # insert into event_to_state_groups.
  1252. try:
  1253. self._store_event_state_mappings_txn(txn, ((event, context),))
  1254. except Exception:
  1255. logger.exception("")
  1256. raise
  1257. # Add an entry to the ex_outlier_stream table to replicate the
  1258. # change in outlier status to our workers.
  1259. stream_order = event.internal_metadata.stream_ordering
  1260. state_group_id = context.state_group
  1261. self.db_pool.simple_insert_txn(
  1262. txn,
  1263. table="ex_outlier_stream",
  1264. values={
  1265. "event_stream_ordering": stream_order,
  1266. "event_id": event.event_id,
  1267. "state_group": state_group_id,
  1268. "instance_name": self._instance_name,
  1269. },
  1270. )
  1271. sql = "UPDATE events SET outlier = FALSE WHERE event_id = ?"
  1272. txn.execute(sql, (event.event_id,))
  1273. # Update the event_backward_extremities table now that this
  1274. # event isn't an outlier any more.
  1275. self._update_backward_extremeties(txn, [event])
  1276. return [ec for ec in events_and_contexts if ec[0] not in to_remove]
  1277. def _store_event_txn(
  1278. self,
  1279. txn: LoggingTransaction,
  1280. events_and_contexts: Collection[Tuple[EventBase, EventContext]],
  1281. ) -> None:
  1282. """Insert new events into the event, event_json, redaction and
  1283. state_events tables.
  1284. """
  1285. if not events_and_contexts:
  1286. # nothing to do here
  1287. return
  1288. def event_dict(event: EventBase) -> JsonDict:
  1289. d = event.get_dict()
  1290. d.pop("redacted", None)
  1291. d.pop("redacted_because", None)
  1292. return d
  1293. self.db_pool.simple_insert_many_txn(
  1294. txn,
  1295. table="event_json",
  1296. keys=("event_id", "room_id", "internal_metadata", "json", "format_version"),
  1297. values=(
  1298. (
  1299. event.event_id,
  1300. event.room_id,
  1301. json_encoder.encode(event.internal_metadata.get_dict()),
  1302. json_encoder.encode(event_dict(event)),
  1303. event.format_version,
  1304. )
  1305. for event, _ in events_and_contexts
  1306. ),
  1307. )
  1308. self.db_pool.simple_insert_many_txn(
  1309. txn,
  1310. table="events",
  1311. keys=(
  1312. "instance_name",
  1313. "stream_ordering",
  1314. "topological_ordering",
  1315. "depth",
  1316. "event_id",
  1317. "room_id",
  1318. "type",
  1319. "processed",
  1320. "outlier",
  1321. "origin_server_ts",
  1322. "received_ts",
  1323. "sender",
  1324. "contains_url",
  1325. "state_key",
  1326. "rejection_reason",
  1327. ),
  1328. values=(
  1329. (
  1330. self._instance_name,
  1331. event.internal_metadata.stream_ordering,
  1332. event.depth, # topological_ordering
  1333. event.depth, # depth
  1334. event.event_id,
  1335. event.room_id,
  1336. event.type,
  1337. True, # processed
  1338. event.internal_metadata.is_outlier(),
  1339. int(event.origin_server_ts),
  1340. self._clock.time_msec(),
  1341. event.sender,
  1342. "url" in event.content and isinstance(event.content["url"], str),
  1343. event.get_state_key(),
  1344. context.rejected,
  1345. )
  1346. for event, context in events_and_contexts
  1347. ),
  1348. )
  1349. # If we're persisting an unredacted event we go and ensure
  1350. # that we mark any redactions that reference this event as
  1351. # requiring censoring.
  1352. unredacted_events = [
  1353. event.event_id
  1354. for event, _ in events_and_contexts
  1355. if not event.internal_metadata.is_redacted()
  1356. ]
  1357. sql = "UPDATE redactions SET have_censored = FALSE WHERE "
  1358. clause, args = make_in_list_sql_clause(
  1359. self.database_engine,
  1360. "redacts",
  1361. unredacted_events,
  1362. )
  1363. txn.execute(sql + clause, args)
  1364. self.db_pool.simple_insert_many_txn(
  1365. txn,
  1366. table="state_events",
  1367. keys=("event_id", "room_id", "type", "state_key"),
  1368. values=(
  1369. (event.event_id, event.room_id, event.type, event.state_key)
  1370. for event, _ in events_and_contexts
  1371. if event.is_state()
  1372. ),
  1373. )
  1374. def _store_rejected_events_txn(
  1375. self,
  1376. txn: LoggingTransaction,
  1377. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1378. ) -> List[Tuple[EventBase, EventContext]]:
  1379. """Add rows to the 'rejections' table for received events which were
  1380. rejected
  1381. Args:
  1382. txn: db connection
  1383. events_and_contexts: events we are persisting
  1384. Returns:
  1385. new list, without the rejected events.
  1386. """
  1387. # Remove the rejected events from the list now that we've added them
  1388. # to the events table and the events_json table.
  1389. to_remove = set()
  1390. for event, context in events_and_contexts:
  1391. if context.rejected:
  1392. # Insert the event_id into the rejections table
  1393. # (events.rejection_reason has already been done)
  1394. self._store_rejections_txn(txn, event.event_id, context.rejected)
  1395. to_remove.add(event)
  1396. return [ec for ec in events_and_contexts if ec[0] not in to_remove]
  1397. def _update_metadata_tables_txn(
  1398. self,
  1399. txn: LoggingTransaction,
  1400. *,
  1401. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1402. all_events_and_contexts: List[Tuple[EventBase, EventContext]],
  1403. inhibit_local_membership_updates: bool = False,
  1404. ) -> None:
  1405. """Update all the miscellaneous tables for new events
  1406. Args:
  1407. txn: db connection
  1408. events_and_contexts: events we are persisting
  1409. all_events_and_contexts: all events that we were going to persist.
  1410. This includes events we've already persisted, etc, that wouldn't
  1411. appear in events_and_context.
  1412. inhibit_local_membership_updates: Stop the local_current_membership
  1413. from being updated by these events. This should be set to True
  1414. for backfilled events because backfilled events in the past do
  1415. not affect the current local state.
  1416. """
  1417. # Insert all the push actions into the event_push_actions table.
  1418. self._set_push_actions_for_event_and_users_txn(
  1419. txn,
  1420. events_and_contexts=events_and_contexts,
  1421. all_events_and_contexts=all_events_and_contexts,
  1422. )
  1423. if not events_and_contexts:
  1424. # nothing to do here
  1425. return
  1426. for event, _ in events_and_contexts:
  1427. if event.type == EventTypes.Redaction and event.redacts is not None:
  1428. # Remove the entries in the event_push_actions table for the
  1429. # redacted event.
  1430. self._remove_push_actions_for_event_id_txn(
  1431. txn, event.room_id, event.redacts
  1432. )
  1433. # Remove from relations table.
  1434. self._handle_redact_relations(txn, event.room_id, event.redacts)
  1435. # Update the event_forward_extremities, event_backward_extremities and
  1436. # event_edges tables.
  1437. self._handle_mult_prev_events(
  1438. txn, events=[event for event, _ in events_and_contexts]
  1439. )
  1440. for event, _ in events_and_contexts:
  1441. if event.type == EventTypes.Name:
  1442. # Insert into the event_search table.
  1443. self._store_room_name_txn(txn, event)
  1444. elif event.type == EventTypes.Topic:
  1445. # Insert into the event_search table.
  1446. self._store_room_topic_txn(txn, event)
  1447. elif event.type == EventTypes.Message:
  1448. # Insert into the event_search table.
  1449. self._store_room_message_txn(txn, event)
  1450. elif event.type == EventTypes.Redaction and event.redacts is not None:
  1451. # Insert into the redactions table.
  1452. self._store_redaction(txn, event)
  1453. elif event.type == EventTypes.Retention:
  1454. # Update the room_retention table.
  1455. self._store_retention_policy_for_room_txn(txn, event)
  1456. self._handle_event_relations(txn, event)
  1457. # Store the labels for this event.
  1458. labels = event.content.get(EventContentFields.LABELS)
  1459. if labels:
  1460. self.insert_labels_for_event_txn(
  1461. txn, event.event_id, labels, event.room_id, event.depth
  1462. )
  1463. if self._ephemeral_messages_enabled:
  1464. # If there's an expiry timestamp on the event, store it.
  1465. expiry_ts = event.content.get(EventContentFields.SELF_DESTRUCT_AFTER)
  1466. if type(expiry_ts) is int and not event.is_state(): # noqa: E721
  1467. self._insert_event_expiry_txn(txn, event.event_id, expiry_ts)
  1468. # Insert into the room_memberships table.
  1469. self._store_room_members_txn(
  1470. txn,
  1471. [
  1472. event
  1473. for event, _ in events_and_contexts
  1474. if event.type == EventTypes.Member
  1475. ],
  1476. inhibit_local_membership_updates=inhibit_local_membership_updates,
  1477. )
  1478. # Prefill the event cache
  1479. self._add_to_cache(txn, events_and_contexts)
  1480. def _add_to_cache(
  1481. self,
  1482. txn: LoggingTransaction,
  1483. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1484. ) -> None:
  1485. to_prefill = []
  1486. rows = []
  1487. ev_map = {e.event_id: e for e, _ in events_and_contexts}
  1488. if not ev_map:
  1489. return
  1490. sql = (
  1491. "SELECT "
  1492. " e.event_id as event_id, "
  1493. " r.redacts as redacts,"
  1494. " rej.event_id as rejects "
  1495. " FROM events as e"
  1496. " LEFT JOIN rejections as rej USING (event_id)"
  1497. " LEFT JOIN redactions as r ON e.event_id = r.redacts"
  1498. " WHERE "
  1499. )
  1500. clause, args = make_in_list_sql_clause(
  1501. self.database_engine, "e.event_id", list(ev_map)
  1502. )
  1503. txn.execute(sql + clause, args)
  1504. rows = self.db_pool.cursor_to_dict(txn)
  1505. for row in rows:
  1506. event = ev_map[row["event_id"]]
  1507. if not row["rejects"] and not row["redacts"]:
  1508. to_prefill.append(EventCacheEntry(event=event, redacted_event=None))
  1509. async def external_prefill() -> None:
  1510. for cache_entry in to_prefill:
  1511. await self.store._get_event_cache.set_external(
  1512. (cache_entry.event.event_id,), cache_entry
  1513. )
  1514. def local_prefill() -> None:
  1515. for cache_entry in to_prefill:
  1516. self.store._get_event_cache.set_local(
  1517. (cache_entry.event.event_id,), cache_entry
  1518. )
  1519. # The order these are called here is not as important as knowing that after the
  1520. # transaction is finished, the async_call_after will run before the call_after.
  1521. txn.async_call_after(external_prefill)
  1522. txn.call_after(local_prefill)
  1523. def _store_redaction(self, txn: LoggingTransaction, event: EventBase) -> None:
  1524. assert event.redacts is not None
  1525. self.db_pool.simple_upsert_txn(
  1526. txn,
  1527. table="redactions",
  1528. keyvalues={"event_id": event.event_id},
  1529. values={
  1530. "redacts": event.redacts,
  1531. "received_ts": self._clock.time_msec(),
  1532. },
  1533. )
  1534. def insert_labels_for_event_txn(
  1535. self,
  1536. txn: LoggingTransaction,
  1537. event_id: str,
  1538. labels: List[str],
  1539. room_id: str,
  1540. topological_ordering: int,
  1541. ) -> None:
  1542. """Store the mapping between an event's ID and its labels, with one row per
  1543. (event_id, label) tuple.
  1544. Args:
  1545. txn: The transaction to execute.
  1546. event_id: The event's ID.
  1547. labels: A list of text labels.
  1548. room_id: The ID of the room the event was sent to.
  1549. topological_ordering: The position of the event in the room's topology.
  1550. """
  1551. self.db_pool.simple_insert_many_txn(
  1552. txn=txn,
  1553. table="event_labels",
  1554. keys=("event_id", "label", "room_id", "topological_ordering"),
  1555. values=[
  1556. (event_id, label, room_id, topological_ordering) for label in labels
  1557. ],
  1558. )
  1559. def _insert_event_expiry_txn(
  1560. self, txn: LoggingTransaction, event_id: str, expiry_ts: int
  1561. ) -> None:
  1562. """Save the expiry timestamp associated with a given event ID.
  1563. Args:
  1564. txn: The database transaction to use.
  1565. event_id: The event ID the expiry timestamp is associated with.
  1566. expiry_ts: The timestamp at which to expire (delete) the event.
  1567. """
  1568. self.db_pool.simple_insert_txn(
  1569. txn=txn,
  1570. table="event_expiry",
  1571. values={"event_id": event_id, "expiry_ts": expiry_ts},
  1572. )
  1573. def _store_room_members_txn(
  1574. self,
  1575. txn: LoggingTransaction,
  1576. events: List[EventBase],
  1577. *,
  1578. inhibit_local_membership_updates: bool = False,
  1579. ) -> None:
  1580. """
  1581. Store a room member in the database.
  1582. Args:
  1583. txn: The transaction to use.
  1584. events: List of events to store.
  1585. inhibit_local_membership_updates: Stop the local_current_membership
  1586. from being updated by these events. This should be set to True
  1587. for backfilled events because backfilled events in the past do
  1588. not affect the current local state.
  1589. """
  1590. self.db_pool.simple_insert_many_txn(
  1591. txn,
  1592. table="room_memberships",
  1593. keys=(
  1594. "event_id",
  1595. "event_stream_ordering",
  1596. "user_id",
  1597. "sender",
  1598. "room_id",
  1599. "membership",
  1600. "display_name",
  1601. "avatar_url",
  1602. ),
  1603. values=[
  1604. (
  1605. event.event_id,
  1606. event.internal_metadata.stream_ordering,
  1607. event.state_key,
  1608. event.user_id,
  1609. event.room_id,
  1610. event.membership,
  1611. non_null_str_or_none(event.content.get("displayname")),
  1612. non_null_str_or_none(event.content.get("avatar_url")),
  1613. )
  1614. for event in events
  1615. ],
  1616. )
  1617. for event in events:
  1618. assert event.internal_metadata.stream_ordering is not None
  1619. # We update the local_current_membership table only if the event is
  1620. # "current", i.e., its something that has just happened.
  1621. #
  1622. # This will usually get updated by the `current_state_events` handling,
  1623. # unless its an outlier, and an outlier is only "current" if it's an "out of
  1624. # band membership", like a remote invite or a rejection of a remote invite.
  1625. if (
  1626. self.is_mine_id(event.state_key)
  1627. and not inhibit_local_membership_updates
  1628. and event.internal_metadata.is_outlier()
  1629. and event.internal_metadata.is_out_of_band_membership()
  1630. ):
  1631. self.db_pool.simple_upsert_txn(
  1632. txn,
  1633. table="local_current_membership",
  1634. keyvalues={"room_id": event.room_id, "user_id": event.state_key},
  1635. values={
  1636. "event_id": event.event_id,
  1637. "event_stream_ordering": event.internal_metadata.stream_ordering,
  1638. "membership": event.membership,
  1639. },
  1640. )
  1641. def _handle_event_relations(
  1642. self, txn: LoggingTransaction, event: EventBase
  1643. ) -> None:
  1644. """Handles inserting relation data during persistence of events
  1645. Args:
  1646. txn: The current database transaction.
  1647. event: The event which might have relations.
  1648. """
  1649. relation = relation_from_event(event)
  1650. if not relation:
  1651. # No relation, nothing to do.
  1652. return
  1653. self.db_pool.simple_insert_txn(
  1654. txn,
  1655. table="event_relations",
  1656. values={
  1657. "event_id": event.event_id,
  1658. "relates_to_id": relation.parent_id,
  1659. "relation_type": relation.rel_type,
  1660. "aggregation_key": relation.aggregation_key,
  1661. },
  1662. )
  1663. if relation.rel_type == RelationTypes.THREAD:
  1664. # Upsert into the threads table, but only overwrite the value if the
  1665. # new event is of a later topological order OR if the topological
  1666. # ordering is equal, but the stream ordering is later.
  1667. sql = """
  1668. INSERT INTO threads (room_id, thread_id, latest_event_id, topological_ordering, stream_ordering)
  1669. VALUES (?, ?, ?, ?, ?)
  1670. ON CONFLICT (room_id, thread_id)
  1671. DO UPDATE SET
  1672. latest_event_id = excluded.latest_event_id,
  1673. topological_ordering = excluded.topological_ordering,
  1674. stream_ordering = excluded.stream_ordering
  1675. WHERE
  1676. threads.topological_ordering <= excluded.topological_ordering AND
  1677. threads.stream_ordering < excluded.stream_ordering
  1678. """
  1679. txn.execute(
  1680. sql,
  1681. (
  1682. event.room_id,
  1683. relation.parent_id,
  1684. event.event_id,
  1685. event.depth,
  1686. event.internal_metadata.stream_ordering,
  1687. ),
  1688. )
  1689. def _handle_redact_relations(
  1690. self, txn: LoggingTransaction, room_id: str, redacted_event_id: str
  1691. ) -> None:
  1692. """Handles receiving a redaction and checking whether the redacted event
  1693. has any relations which must be removed from the database.
  1694. Args:
  1695. txn
  1696. room_id: The room ID of the event that was redacted.
  1697. redacted_event_id: The event that was redacted.
  1698. """
  1699. # Fetch the relation of the event being redacted.
  1700. row = self.db_pool.simple_select_one_txn(
  1701. txn,
  1702. table="event_relations",
  1703. keyvalues={"event_id": redacted_event_id},
  1704. retcols=("relates_to_id", "relation_type"),
  1705. allow_none=True,
  1706. )
  1707. # Nothing to do if no relation is found.
  1708. if row is None:
  1709. return
  1710. redacted_relates_to = row["relates_to_id"]
  1711. rel_type = row["relation_type"]
  1712. self.db_pool.simple_delete_txn(
  1713. txn, table="event_relations", keyvalues={"event_id": redacted_event_id}
  1714. )
  1715. # Any relation information for the related event must be cleared.
  1716. self.store._invalidate_cache_and_stream(
  1717. txn, self.store.get_relations_for_event, (redacted_relates_to,)
  1718. )
  1719. if rel_type == RelationTypes.REFERENCE:
  1720. self.store._invalidate_cache_and_stream(
  1721. txn, self.store.get_references_for_event, (redacted_relates_to,)
  1722. )
  1723. if rel_type == RelationTypes.REPLACE:
  1724. self.store._invalidate_cache_and_stream(
  1725. txn, self.store.get_applicable_edit, (redacted_relates_to,)
  1726. )
  1727. if rel_type == RelationTypes.THREAD:
  1728. self.store._invalidate_cache_and_stream(
  1729. txn, self.store.get_thread_summary, (redacted_relates_to,)
  1730. )
  1731. self.store._invalidate_cache_and_stream(
  1732. txn, self.store.get_thread_participated, (redacted_relates_to,)
  1733. )
  1734. self.store._invalidate_cache_and_stream(
  1735. txn, self.store.get_threads, (room_id,)
  1736. )
  1737. # Find the new latest event in the thread.
  1738. sql = """
  1739. SELECT event_id, topological_ordering, stream_ordering
  1740. FROM event_relations
  1741. INNER JOIN events USING (event_id)
  1742. WHERE relates_to_id = ? AND relation_type = ?
  1743. ORDER BY topological_ordering DESC, stream_ordering DESC
  1744. LIMIT 1
  1745. """
  1746. txn.execute(sql, (redacted_relates_to, RelationTypes.THREAD))
  1747. # If a latest event is found, update the threads table, this might
  1748. # be the same current latest event (if an earlier event in the thread
  1749. # was redacted).
  1750. latest_event_row = txn.fetchone()
  1751. if latest_event_row:
  1752. self.db_pool.simple_upsert_txn(
  1753. txn,
  1754. table="threads",
  1755. keyvalues={"room_id": room_id, "thread_id": redacted_relates_to},
  1756. values={
  1757. "latest_event_id": latest_event_row[0],
  1758. "topological_ordering": latest_event_row[1],
  1759. "stream_ordering": latest_event_row[2],
  1760. },
  1761. )
  1762. # Otherwise, delete the thread: it no longer exists.
  1763. else:
  1764. self.db_pool.simple_delete_one_txn(
  1765. txn, table="threads", keyvalues={"thread_id": redacted_relates_to}
  1766. )
  1767. def _store_room_topic_txn(self, txn: LoggingTransaction, event: EventBase) -> None:
  1768. if isinstance(event.content.get("topic"), str):
  1769. self.store_event_search_txn(
  1770. txn, event, "content.topic", event.content["topic"]
  1771. )
  1772. def _store_room_name_txn(self, txn: LoggingTransaction, event: EventBase) -> None:
  1773. if isinstance(event.content.get("name"), str):
  1774. self.store_event_search_txn(
  1775. txn, event, "content.name", event.content["name"]
  1776. )
  1777. def _store_room_message_txn(
  1778. self, txn: LoggingTransaction, event: EventBase
  1779. ) -> None:
  1780. if isinstance(event.content.get("body"), str):
  1781. self.store_event_search_txn(
  1782. txn, event, "content.body", event.content["body"]
  1783. )
  1784. def _store_retention_policy_for_room_txn(
  1785. self, txn: LoggingTransaction, event: EventBase
  1786. ) -> None:
  1787. if not event.is_state():
  1788. logger.debug("Ignoring non-state m.room.retention event")
  1789. return
  1790. if hasattr(event, "content") and (
  1791. "min_lifetime" in event.content or "max_lifetime" in event.content
  1792. ):
  1793. if (
  1794. "min_lifetime" in event.content
  1795. and type(event.content["min_lifetime"]) is not int # noqa: E721
  1796. ) or (
  1797. "max_lifetime" in event.content
  1798. and type(event.content["max_lifetime"]) is not int # noqa: E721
  1799. ):
  1800. # Ignore the event if one of the value isn't an integer.
  1801. return
  1802. self.db_pool.simple_insert_txn(
  1803. txn=txn,
  1804. table="room_retention",
  1805. values={
  1806. "room_id": event.room_id,
  1807. "event_id": event.event_id,
  1808. "min_lifetime": event.content.get("min_lifetime"),
  1809. "max_lifetime": event.content.get("max_lifetime"),
  1810. },
  1811. )
  1812. self.store._invalidate_cache_and_stream(
  1813. txn, self.store.get_retention_policy_for_room, (event.room_id,)
  1814. )
  1815. def store_event_search_txn(
  1816. self, txn: LoggingTransaction, event: EventBase, key: str, value: str
  1817. ) -> None:
  1818. """Add event to the search table
  1819. Args:
  1820. txn: The database transaction.
  1821. event: The event being added to the search table.
  1822. key: A key describing the search value (one of "content.name",
  1823. "content.topic", or "content.body")
  1824. value: The value from the event's content.
  1825. """
  1826. self.store.store_search_entries_txn(
  1827. txn,
  1828. (
  1829. SearchEntry(
  1830. key=key,
  1831. value=value,
  1832. event_id=event.event_id,
  1833. room_id=event.room_id,
  1834. stream_ordering=event.internal_metadata.stream_ordering,
  1835. origin_server_ts=event.origin_server_ts,
  1836. ),
  1837. ),
  1838. )
  1839. def _set_push_actions_for_event_and_users_txn(
  1840. self,
  1841. txn: LoggingTransaction,
  1842. events_and_contexts: List[Tuple[EventBase, EventContext]],
  1843. all_events_and_contexts: List[Tuple[EventBase, EventContext]],
  1844. ) -> None:
  1845. """Handles moving push actions from staging table to main
  1846. event_push_actions table for all events in `events_and_contexts`.
  1847. Also ensures that all events in `all_events_and_contexts` are removed
  1848. from the push action staging area.
  1849. Args:
  1850. events_and_contexts: events we are persisting
  1851. all_events_and_contexts: all events that we were going to persist.
  1852. This includes events we've already persisted, etc, that wouldn't
  1853. appear in events_and_context.
  1854. """
  1855. # Only notifiable events will have push actions associated with them,
  1856. # so let's filter them out. (This makes joining large rooms faster, as
  1857. # these queries took seconds to process all the state events).
  1858. notifiable_events = [
  1859. event
  1860. for event, _ in events_and_contexts
  1861. if event.internal_metadata.is_notifiable()
  1862. ]
  1863. sql = """
  1864. INSERT INTO event_push_actions (
  1865. room_id, event_id, user_id, actions, stream_ordering,
  1866. topological_ordering, notif, highlight, unread, thread_id
  1867. )
  1868. SELECT ?, event_id, user_id, actions, ?, ?, notif, highlight, unread, thread_id
  1869. FROM event_push_actions_staging
  1870. WHERE event_id = ?
  1871. """
  1872. if notifiable_events:
  1873. txn.execute_batch(
  1874. sql,
  1875. (
  1876. (
  1877. event.room_id,
  1878. event.internal_metadata.stream_ordering,
  1879. event.depth,
  1880. event.event_id,
  1881. )
  1882. for event in notifiable_events
  1883. ),
  1884. )
  1885. # Now we delete the staging area for *all* events that were being
  1886. # persisted.
  1887. txn.execute_batch(
  1888. "DELETE FROM event_push_actions_staging WHERE event_id = ?",
  1889. (
  1890. (event.event_id,)
  1891. for event, _ in all_events_and_contexts
  1892. if event.internal_metadata.is_notifiable()
  1893. ),
  1894. )
  1895. def _remove_push_actions_for_event_id_txn(
  1896. self, txn: LoggingTransaction, room_id: str, event_id: str
  1897. ) -> None:
  1898. txn.execute(
  1899. "DELETE FROM event_push_actions WHERE room_id = ? AND event_id = ?",
  1900. (room_id, event_id),
  1901. )
  1902. def _store_rejections_txn(
  1903. self, txn: LoggingTransaction, event_id: str, reason: str
  1904. ) -> None:
  1905. self.db_pool.simple_insert_txn(
  1906. txn,
  1907. table="rejections",
  1908. values={
  1909. "event_id": event_id,
  1910. "reason": reason,
  1911. "last_check": self._clock.time_msec(),
  1912. },
  1913. )
  1914. def _store_event_state_mappings_txn(
  1915. self,
  1916. txn: LoggingTransaction,
  1917. events_and_contexts: Collection[Tuple[EventBase, EventContext]],
  1918. ) -> None:
  1919. """
  1920. Raises:
  1921. PartialStateConflictError: if attempting to persist a partial state event in
  1922. a room that has been un-partial stated.
  1923. """
  1924. state_groups = {}
  1925. for event, context in events_and_contexts:
  1926. if event.internal_metadata.is_outlier():
  1927. # double-check that we don't have any events that claim to be outliers
  1928. # *and* have partial state (which is meaningless: we should have no
  1929. # state at all for an outlier)
  1930. if context.partial_state:
  1931. raise ValueError(
  1932. "Outlier event %s claims to have partial state", event.event_id
  1933. )
  1934. continue
  1935. # if the event was rejected, just give it the same state as its
  1936. # predecessor.
  1937. if context.rejected:
  1938. state_groups[event.event_id] = context.state_group_before_event
  1939. continue
  1940. state_groups[event.event_id] = context.state_group
  1941. # if we have partial state for these events, record the fact. (This happens
  1942. # here rather than in _store_event_txn because it also needs to happen when
  1943. # we de-outlier an event.)
  1944. try:
  1945. self.db_pool.simple_insert_many_txn(
  1946. txn,
  1947. table="partial_state_events",
  1948. keys=("room_id", "event_id"),
  1949. values=[
  1950. (
  1951. event.room_id,
  1952. event.event_id,
  1953. )
  1954. for event, ctx in events_and_contexts
  1955. if ctx.partial_state
  1956. ],
  1957. )
  1958. except self.db_pool.engine.module.IntegrityError:
  1959. logger.info(
  1960. "Cannot persist events %s in rooms %s: room has been un-partial stated",
  1961. [
  1962. event.event_id
  1963. for event, ctx in events_and_contexts
  1964. if ctx.partial_state
  1965. ],
  1966. list(
  1967. {
  1968. event.room_id
  1969. for event, ctx in events_and_contexts
  1970. if ctx.partial_state
  1971. }
  1972. ),
  1973. )
  1974. raise PartialStateConflictError()
  1975. self.db_pool.simple_upsert_many_txn(
  1976. txn,
  1977. table="event_to_state_groups",
  1978. key_names=["event_id"],
  1979. key_values=[[event_id] for event_id, _ in state_groups.items()],
  1980. value_names=["state_group"],
  1981. value_values=[
  1982. [state_group_id] for _, state_group_id in state_groups.items()
  1983. ],
  1984. )
  1985. for event_id, state_group_id in state_groups.items():
  1986. txn.call_after(
  1987. self.store._get_state_group_for_event.prefill,
  1988. (event_id,),
  1989. state_group_id,
  1990. )
  1991. def _update_min_depth_for_room_txn(
  1992. self, txn: LoggingTransaction, room_id: str, depth: int
  1993. ) -> None:
  1994. min_depth = self.store._get_min_depth_interaction(txn, room_id)
  1995. if min_depth is not None and depth >= min_depth:
  1996. return
  1997. self.db_pool.simple_upsert_txn(
  1998. txn,
  1999. table="room_depth",
  2000. keyvalues={"room_id": room_id},
  2001. values={"min_depth": depth},
  2002. )
  2003. def _handle_mult_prev_events(
  2004. self, txn: LoggingTransaction, events: List[EventBase]
  2005. ) -> None:
  2006. """
  2007. For the given event, update the event edges table and forward and
  2008. backward extremities tables.
  2009. """
  2010. self.db_pool.simple_insert_many_txn(
  2011. txn,
  2012. table="event_edges",
  2013. keys=("event_id", "prev_event_id"),
  2014. values=[
  2015. (ev.event_id, e_id) for ev in events for e_id in ev.prev_event_ids()
  2016. ],
  2017. )
  2018. self._update_backward_extremeties(txn, events)
  2019. def _update_backward_extremeties(
  2020. self, txn: LoggingTransaction, events: List[EventBase]
  2021. ) -> None:
  2022. """Updates the event_backward_extremities tables based on the new/updated
  2023. events being persisted.
  2024. This is called for new events *and* for events that were outliers, but
  2025. are now being persisted as non-outliers.
  2026. Forward extremities are handled when we first start persisting the events.
  2027. """
  2028. # From the events passed in, add all of the prev events as backwards extremities.
  2029. # Ignore any events that are already backwards extrems or outliers.
  2030. query = (
  2031. "INSERT INTO event_backward_extremities (event_id, room_id)"
  2032. " SELECT ?, ? WHERE NOT EXISTS ("
  2033. " SELECT 1 FROM event_backward_extremities"
  2034. " WHERE event_id = ? AND room_id = ?"
  2035. " )"
  2036. # 1. Don't add an event as a extremity again if we already persisted it
  2037. # as a non-outlier.
  2038. # 2. Don't add an outlier as an extremity if it has no prev_events
  2039. " AND NOT EXISTS ("
  2040. " SELECT 1 FROM events"
  2041. " LEFT JOIN event_edges edge"
  2042. " ON edge.event_id = events.event_id"
  2043. " WHERE events.event_id = ? AND events.room_id = ? AND (events.outlier = FALSE OR edge.event_id IS NULL)"
  2044. " )"
  2045. )
  2046. txn.execute_batch(
  2047. query,
  2048. [
  2049. (e_id, ev.room_id, e_id, ev.room_id, e_id, ev.room_id)
  2050. for ev in events
  2051. for e_id in ev.prev_event_ids()
  2052. if not ev.internal_metadata.is_outlier()
  2053. ],
  2054. )
  2055. # Delete all these events that we've already fetched and now know that their
  2056. # prev events are the new backwards extremeties.
  2057. query = (
  2058. "DELETE FROM event_backward_extremities"
  2059. " WHERE event_id = ? AND room_id = ?"
  2060. )
  2061. backward_extremity_tuples_to_remove = [
  2062. (ev.event_id, ev.room_id)
  2063. for ev in events
  2064. if not ev.internal_metadata.is_outlier()
  2065. # If we encountered an event with no prev_events, then we might
  2066. # as well remove it now because it won't ever have anything else
  2067. # to backfill from.
  2068. or len(ev.prev_event_ids()) == 0
  2069. ]
  2070. txn.execute_batch(
  2071. query,
  2072. backward_extremity_tuples_to_remove,
  2073. )
  2074. # Clear out the failed backfill attempts after we successfully pulled
  2075. # the event. Since we no longer need these events as backward
  2076. # extremities, it also means that they won't be backfilled from again so
  2077. # we no longer need to store the backfill attempts around it.
  2078. query = """
  2079. DELETE FROM event_failed_pull_attempts
  2080. WHERE event_id = ? and room_id = ?
  2081. """
  2082. txn.execute_batch(
  2083. query,
  2084. backward_extremity_tuples_to_remove,
  2085. )
  2086. @attr.s(slots=True, auto_attribs=True)
  2087. class _LinkMap:
  2088. """A helper type for tracking links between chains."""
  2089. # Stores the set of links as nested maps: source chain ID -> target chain ID
  2090. # -> source sequence number -> target sequence number.
  2091. maps: Dict[int, Dict[int, Dict[int, int]]] = attr.Factory(dict)
  2092. # Stores the links that have been added (with new set to true), as tuples of
  2093. # `(source chain ID, source sequence no, target chain ID, target sequence no.)`
  2094. additions: Set[Tuple[int, int, int, int]] = attr.Factory(set)
  2095. def add_link(
  2096. self,
  2097. src_tuple: Tuple[int, int],
  2098. target_tuple: Tuple[int, int],
  2099. new: bool = True,
  2100. ) -> bool:
  2101. """Add a new link between two chains, ensuring no redundant links are added.
  2102. New links should be added in topological order.
  2103. Args:
  2104. src_tuple: The chain ID/sequence number of the source of the link.
  2105. target_tuple: The chain ID/sequence number of the target of the link.
  2106. new: Whether this is a "new" link, i.e. should it be returned
  2107. by `get_additions`.
  2108. Returns:
  2109. True if a link was added, false if the given link was dropped as redundant
  2110. """
  2111. src_chain, src_seq = src_tuple
  2112. target_chain, target_seq = target_tuple
  2113. current_links = self.maps.setdefault(src_chain, {}).setdefault(target_chain, {})
  2114. assert src_chain != target_chain
  2115. if new:
  2116. # Check if the new link is redundant
  2117. for current_seq_src, current_seq_target in current_links.items():
  2118. # If a link "crosses" another link then its redundant. For example
  2119. # in the following link 1 (L1) is redundant, as any event reachable
  2120. # via L1 is *also* reachable via L2.
  2121. #
  2122. # Chain A Chain B
  2123. # | |
  2124. # L1 |------ |
  2125. # | | |
  2126. # L2 |---- | -->|
  2127. # | | |
  2128. # | |--->|
  2129. # | |
  2130. # | |
  2131. #
  2132. # So we only need to keep links which *do not* cross, i.e. links
  2133. # that both start and end above or below an existing link.
  2134. #
  2135. # Note, since we add links in topological ordering we should never
  2136. # see `src_seq` less than `current_seq_src`.
  2137. if current_seq_src <= src_seq and target_seq <= current_seq_target:
  2138. # This new link is redundant, nothing to do.
  2139. return False
  2140. self.additions.add((src_chain, src_seq, target_chain, target_seq))
  2141. current_links[src_seq] = target_seq
  2142. return True
  2143. def get_links_from(
  2144. self, src_tuple: Tuple[int, int]
  2145. ) -> Generator[Tuple[int, int], None, None]:
  2146. """Gets the chains reachable from the given chain/sequence number.
  2147. Yields:
  2148. The chain ID and sequence number the link points to.
  2149. """
  2150. src_chain, src_seq = src_tuple
  2151. for target_id, sequence_numbers in self.maps.get(src_chain, {}).items():
  2152. for link_src_seq, target_seq in sequence_numbers.items():
  2153. if link_src_seq <= src_seq:
  2154. yield target_id, target_seq
  2155. def get_links_between(
  2156. self, source_chain: int, target_chain: int
  2157. ) -> Generator[Tuple[int, int], None, None]:
  2158. """Gets the links between two chains.
  2159. Yields:
  2160. The source and target sequence numbers.
  2161. """
  2162. yield from self.maps.get(source_chain, {}).get(target_chain, {}).items()
  2163. def get_additions(self) -> Generator[Tuple[int, int, int, int], None, None]:
  2164. """Gets any newly added links.
  2165. Yields:
  2166. The source chain ID/sequence number and target chain ID/sequence number
  2167. """
  2168. for src_chain, src_seq, target_chain, _ in self.additions:
  2169. target_seq = self.maps.get(src_chain, {}).get(target_chain, {}).get(src_seq)
  2170. if target_seq is not None:
  2171. yield (src_chain, src_seq, target_chain, target_seq)
  2172. def exists_path_from(
  2173. self,
  2174. src_tuple: Tuple[int, int],
  2175. target_tuple: Tuple[int, int],
  2176. ) -> bool:
  2177. """Checks if there is a path between the source chain ID/sequence and
  2178. target chain ID/sequence.
  2179. """
  2180. src_chain, src_seq = src_tuple
  2181. target_chain, target_seq = target_tuple
  2182. if src_chain == target_chain:
  2183. return target_seq <= src_seq
  2184. links = self.get_links_between(src_chain, target_chain)
  2185. for link_start_seq, link_end_seq in links:
  2186. if link_start_seq <= src_seq and target_seq <= link_end_seq:
  2187. return True
  2188. return False