events.py 97 KB

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