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.
 
 
 
 
 
 

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