events.py 98 KB

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