events_worker.py 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202
  1. # Copyright 2018 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import threading
  16. import weakref
  17. from enum import Enum, auto
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. Collection,
  22. Container,
  23. Dict,
  24. Iterable,
  25. List,
  26. MutableMapping,
  27. Optional,
  28. Set,
  29. Tuple,
  30. cast,
  31. overload,
  32. )
  33. import attr
  34. from prometheus_client import Gauge
  35. from typing_extensions import Literal
  36. from twisted.internet import defer
  37. from synapse.api.constants import EventTypes
  38. from synapse.api.errors import NotFoundError, SynapseError
  39. from synapse.api.room_versions import (
  40. KNOWN_ROOM_VERSIONS,
  41. EventFormatVersions,
  42. RoomVersion,
  43. RoomVersions,
  44. )
  45. from synapse.events import EventBase, make_event_from_dict
  46. from synapse.events.snapshot import EventContext
  47. from synapse.events.utils import prune_event
  48. from synapse.logging.context import (
  49. PreserveLoggingContext,
  50. current_context,
  51. make_deferred_yieldable,
  52. )
  53. from synapse.metrics.background_process_metrics import (
  54. run_as_background_process,
  55. wrap_as_background_process,
  56. )
  57. from synapse.replication.slave.storage._slaved_id_tracker import SlavedIdTracker
  58. from synapse.replication.tcp.streams import BackfillStream
  59. from synapse.replication.tcp.streams.events import EventsStream
  60. from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause
  61. from synapse.storage.database import (
  62. DatabasePool,
  63. LoggingDatabaseConnection,
  64. LoggingTransaction,
  65. )
  66. from synapse.storage.engines import PostgresEngine
  67. from synapse.storage.types import Cursor
  68. from synapse.storage.util.id_generators import (
  69. AbstractStreamIdTracker,
  70. MultiWriterIdGenerator,
  71. StreamIdGenerator,
  72. )
  73. from synapse.storage.util.sequence import build_sequence_generator
  74. from synapse.types import JsonDict, get_domain_from_id
  75. from synapse.util import unwrapFirstError
  76. from synapse.util.async_helpers import ObservableDeferred, delay_cancellation
  77. from synapse.util.caches.descriptors import cached, cachedList
  78. from synapse.util.caches.lrucache import AsyncLruCache
  79. from synapse.util.iterutils import batch_iter
  80. from synapse.util.metrics import Measure
  81. if TYPE_CHECKING:
  82. from synapse.server import HomeServer
  83. logger = logging.getLogger(__name__)
  84. # These values are used in the `enqueue_event` and `_fetch_loop` methods to
  85. # control how we batch/bulk fetch events from the database.
  86. # The values are plucked out of thing air to make initial sync run faster
  87. # on jki.re
  88. # TODO: Make these configurable.
  89. EVENT_QUEUE_THREADS = 3 # Max number of threads that will fetch events
  90. EVENT_QUEUE_ITERATIONS = 3 # No. times we block waiting for requests for events
  91. EVENT_QUEUE_TIMEOUT_S = 0.1 # Timeout when waiting for requests for events
  92. event_fetch_ongoing_gauge = Gauge(
  93. "synapse_event_fetch_ongoing",
  94. "The number of event fetchers that are running",
  95. )
  96. @attr.s(slots=True, auto_attribs=True)
  97. class EventCacheEntry:
  98. event: EventBase
  99. redacted_event: Optional[EventBase]
  100. @attr.s(slots=True, frozen=True, auto_attribs=True)
  101. class _EventRow:
  102. """
  103. An event, as pulled from the database.
  104. Properties:
  105. event_id: The event ID of the event.
  106. stream_ordering: stream ordering for this event
  107. json: json-encoded event structure
  108. internal_metadata: json-encoded internal metadata dict
  109. format_version: The format of the event. Hopefully one of EventFormatVersions.
  110. 'None' means the event predates EventFormatVersions (so the event is format V1).
  111. room_version_id: The version of the room which contains the event. Hopefully
  112. one of RoomVersions.
  113. Due to historical reasons, there may be a few events in the database which
  114. do not have an associated room; in this case None will be returned here.
  115. rejected_reason: if the event was rejected, the reason why.
  116. redactions: a list of event-ids which (claim to) redact this event.
  117. outlier: True if this event is an outlier.
  118. """
  119. event_id: str
  120. stream_ordering: int
  121. json: str
  122. internal_metadata: str
  123. format_version: Optional[int]
  124. room_version_id: Optional[str]
  125. rejected_reason: Optional[str]
  126. redactions: List[str]
  127. outlier: bool
  128. class EventRedactBehaviour(Enum):
  129. """
  130. What to do when retrieving a redacted event from the database.
  131. """
  132. as_is = auto()
  133. redact = auto()
  134. block = auto()
  135. class EventsWorkerStore(SQLBaseStore):
  136. # Whether to use dedicated DB threads for event fetching. This is only used
  137. # if there are multiple DB threads available. When used will lock the DB
  138. # thread for periods of time (so unit tests want to disable this when they
  139. # run DB transactions on the main thread). See EVENT_QUEUE_* for more
  140. # options controlling this.
  141. USE_DEDICATED_DB_THREADS_FOR_EVENT_FETCHING = True
  142. def __init__(
  143. self,
  144. database: DatabasePool,
  145. db_conn: LoggingDatabaseConnection,
  146. hs: "HomeServer",
  147. ):
  148. super().__init__(database, db_conn, hs)
  149. self._stream_id_gen: AbstractStreamIdTracker
  150. self._backfill_id_gen: AbstractStreamIdTracker
  151. if isinstance(database.engine, PostgresEngine):
  152. # If we're using Postgres than we can use `MultiWriterIdGenerator`
  153. # regardless of whether this process writes to the streams or not.
  154. self._stream_id_gen = MultiWriterIdGenerator(
  155. db_conn=db_conn,
  156. db=database,
  157. stream_name="events",
  158. instance_name=hs.get_instance_name(),
  159. tables=[("events", "instance_name", "stream_ordering")],
  160. sequence_name="events_stream_seq",
  161. writers=hs.config.worker.writers.events,
  162. )
  163. self._backfill_id_gen = MultiWriterIdGenerator(
  164. db_conn=db_conn,
  165. db=database,
  166. stream_name="backfill",
  167. instance_name=hs.get_instance_name(),
  168. tables=[("events", "instance_name", "stream_ordering")],
  169. sequence_name="events_backfill_stream_seq",
  170. positive=False,
  171. writers=hs.config.worker.writers.events,
  172. )
  173. else:
  174. # We shouldn't be running in worker mode with SQLite, but its useful
  175. # to support it for unit tests.
  176. #
  177. # If this process is the writer than we need to use
  178. # `StreamIdGenerator`, otherwise we use `SlavedIdTracker` which gets
  179. # updated over replication. (Multiple writers are not supported for
  180. # SQLite).
  181. if hs.get_instance_name() in hs.config.worker.writers.events:
  182. self._stream_id_gen = StreamIdGenerator(
  183. db_conn,
  184. "events",
  185. "stream_ordering",
  186. )
  187. self._backfill_id_gen = StreamIdGenerator(
  188. db_conn,
  189. "events",
  190. "stream_ordering",
  191. step=-1,
  192. extra_tables=[("ex_outlier_stream", "event_stream_ordering")],
  193. )
  194. else:
  195. self._stream_id_gen = SlavedIdTracker(
  196. db_conn, "events", "stream_ordering"
  197. )
  198. self._backfill_id_gen = SlavedIdTracker(
  199. db_conn, "events", "stream_ordering", step=-1
  200. )
  201. if hs.config.worker.run_background_tasks:
  202. # We periodically clean out old transaction ID mappings
  203. self._clock.looping_call(
  204. self._cleanup_old_transaction_ids,
  205. 5 * 60 * 1000,
  206. )
  207. self._get_event_cache: AsyncLruCache[
  208. Tuple[str], EventCacheEntry
  209. ] = AsyncLruCache(
  210. cache_name="*getEvent*",
  211. max_size=hs.config.caches.event_cache_size,
  212. )
  213. # Map from event ID to a deferred that will result in a map from event
  214. # ID to cache entry. Note that the returned dict may not have the
  215. # requested event in it if the event isn't in the DB.
  216. self._current_event_fetches: Dict[
  217. str, ObservableDeferred[Dict[str, EventCacheEntry]]
  218. ] = {}
  219. # We keep track of the events we have currently loaded in memory so that
  220. # we can reuse them even if they've been evicted from the cache. We only
  221. # track events that don't need redacting in here (as then we don't need
  222. # to track redaction status).
  223. self._event_ref: MutableMapping[str, EventBase] = weakref.WeakValueDictionary()
  224. self._event_fetch_lock = threading.Condition()
  225. self._event_fetch_list: List[
  226. Tuple[Iterable[str], "defer.Deferred[Dict[str, _EventRow]]"]
  227. ] = []
  228. self._event_fetch_ongoing = 0
  229. event_fetch_ongoing_gauge.set(self._event_fetch_ongoing)
  230. # We define this sequence here so that it can be referenced from both
  231. # the DataStore and PersistEventStore.
  232. def get_chain_id_txn(txn: Cursor) -> int:
  233. txn.execute("SELECT COALESCE(max(chain_id), 0) FROM event_auth_chains")
  234. return cast(Tuple[int], txn.fetchone())[0]
  235. self.event_chain_id_gen = build_sequence_generator(
  236. db_conn,
  237. database.engine,
  238. get_chain_id_txn,
  239. "event_auth_chain_id",
  240. table="event_auth_chains",
  241. id_column="chain_id",
  242. )
  243. def process_replication_rows(
  244. self,
  245. stream_name: str,
  246. instance_name: str,
  247. token: int,
  248. rows: Iterable[Any],
  249. ) -> None:
  250. if stream_name == EventsStream.NAME:
  251. self._stream_id_gen.advance(instance_name, token)
  252. elif stream_name == BackfillStream.NAME:
  253. self._backfill_id_gen.advance(instance_name, -token)
  254. super().process_replication_rows(stream_name, instance_name, token, rows)
  255. async def have_censored_event(self, event_id: str) -> bool:
  256. """Check if an event has been censored, i.e. if the content of the event has been erased
  257. from the database due to a redaction.
  258. Args:
  259. event_id: The event ID that was redacted.
  260. Returns:
  261. True if the event has been censored, False otherwise.
  262. """
  263. censored_redactions_list = await self.db_pool.simple_select_onecol(
  264. table="redactions",
  265. keyvalues={"redacts": event_id},
  266. retcol="have_censored",
  267. desc="get_have_censored",
  268. )
  269. return any(censored_redactions_list)
  270. # Inform mypy that if allow_none is False (the default) then get_event
  271. # always returns an EventBase.
  272. @overload
  273. async def get_event(
  274. self,
  275. event_id: str,
  276. redact_behaviour: EventRedactBehaviour = EventRedactBehaviour.redact,
  277. get_prev_content: bool = ...,
  278. allow_rejected: bool = ...,
  279. allow_none: Literal[False] = ...,
  280. check_room_id: Optional[str] = ...,
  281. ) -> EventBase:
  282. ...
  283. @overload
  284. async def get_event(
  285. self,
  286. event_id: str,
  287. redact_behaviour: EventRedactBehaviour = EventRedactBehaviour.redact,
  288. get_prev_content: bool = ...,
  289. allow_rejected: bool = ...,
  290. allow_none: Literal[True] = ...,
  291. check_room_id: Optional[str] = ...,
  292. ) -> Optional[EventBase]:
  293. ...
  294. async def get_event(
  295. self,
  296. event_id: str,
  297. redact_behaviour: EventRedactBehaviour = EventRedactBehaviour.redact,
  298. get_prev_content: bool = False,
  299. allow_rejected: bool = False,
  300. allow_none: bool = False,
  301. check_room_id: Optional[str] = None,
  302. ) -> Optional[EventBase]:
  303. """Get an event from the database by event_id.
  304. Args:
  305. event_id: The event_id of the event to fetch
  306. redact_behaviour: Determine what to do with a redacted event. Possible values:
  307. * as_is - Return the full event body with no redacted content
  308. * redact - Return the event but with a redacted body
  309. * block - Do not return redacted events (behave as per allow_none
  310. if the event is redacted)
  311. get_prev_content: If True and event is a state event,
  312. include the previous states content in the unsigned field.
  313. allow_rejected: If True, return rejected events. Otherwise,
  314. behave as per allow_none.
  315. allow_none: If True, return None if no event found, if
  316. False throw a NotFoundError
  317. check_room_id: if not None, check the room of the found event.
  318. If there is a mismatch, behave as per allow_none.
  319. Returns:
  320. The event, or None if the event was not found.
  321. """
  322. if not isinstance(event_id, str):
  323. raise TypeError("Invalid event event_id %r" % (event_id,))
  324. events = await self.get_events_as_list(
  325. [event_id],
  326. redact_behaviour=redact_behaviour,
  327. get_prev_content=get_prev_content,
  328. allow_rejected=allow_rejected,
  329. )
  330. event = events[0] if events else None
  331. if event is not None and check_room_id is not None:
  332. if event.room_id != check_room_id:
  333. event = None
  334. if event is None and not allow_none:
  335. raise NotFoundError("Could not find event %s" % (event_id,))
  336. return event
  337. async def get_events(
  338. self,
  339. event_ids: Collection[str],
  340. redact_behaviour: EventRedactBehaviour = EventRedactBehaviour.redact,
  341. get_prev_content: bool = False,
  342. allow_rejected: bool = False,
  343. ) -> Dict[str, EventBase]:
  344. """Get events from the database
  345. Args:
  346. event_ids: The event_ids of the events to fetch
  347. redact_behaviour: Determine what to do with a redacted event. Possible
  348. values:
  349. * as_is - Return the full event body with no redacted content
  350. * redact - Return the event but with a redacted body
  351. * block - Do not return redacted events (omit them from the response)
  352. get_prev_content: If True and event is a state event,
  353. include the previous states content in the unsigned field.
  354. allow_rejected: If True, return rejected events. Otherwise,
  355. omits rejected events from the response.
  356. Returns:
  357. A mapping from event_id to event.
  358. """
  359. events = await self.get_events_as_list(
  360. event_ids,
  361. redact_behaviour=redact_behaviour,
  362. get_prev_content=get_prev_content,
  363. allow_rejected=allow_rejected,
  364. )
  365. return {e.event_id: e for e in events}
  366. async def get_events_as_list(
  367. self,
  368. event_ids: Collection[str],
  369. redact_behaviour: EventRedactBehaviour = EventRedactBehaviour.redact,
  370. get_prev_content: bool = False,
  371. allow_rejected: bool = False,
  372. ) -> List[EventBase]:
  373. """Get events from the database and return in a list in the same order
  374. as given by `event_ids` arg.
  375. Unknown events will be omitted from the response.
  376. Args:
  377. event_ids: The event_ids of the events to fetch
  378. redact_behaviour: Determine what to do with a redacted event. Possible values:
  379. * as_is - Return the full event body with no redacted content
  380. * redact - Return the event but with a redacted body
  381. * block - Do not return redacted events (omit them from the response)
  382. get_prev_content: If True and event is a state event,
  383. include the previous states content in the unsigned field.
  384. allow_rejected: If True, return rejected events. Otherwise,
  385. omits rejected events from the response.
  386. Returns:
  387. List of events fetched from the database. The events are in the same
  388. order as `event_ids` arg.
  389. Note that the returned list may be smaller than the list of event
  390. IDs if not all events could be fetched.
  391. """
  392. if not event_ids:
  393. return []
  394. # there may be duplicates so we cast the list to a set
  395. event_entry_map = await self._get_events_from_cache_or_db(
  396. set(event_ids), allow_rejected=allow_rejected
  397. )
  398. events = []
  399. for event_id in event_ids:
  400. entry = event_entry_map.get(event_id, None)
  401. if not entry:
  402. continue
  403. if not allow_rejected:
  404. assert not entry.event.rejected_reason, (
  405. "rejected event returned from _get_events_from_cache_or_db despite "
  406. "allow_rejected=False"
  407. )
  408. # We may not have had the original event when we received a redaction, so
  409. # we have to recheck auth now.
  410. if not allow_rejected and entry.event.type == EventTypes.Redaction:
  411. if entry.event.redacts is None:
  412. # A redacted redaction doesn't have a `redacts` key, in
  413. # which case lets just withhold the event.
  414. #
  415. # Note: Most of the time if the redactions has been
  416. # redacted we still have the un-redacted event in the DB
  417. # and so we'll still see the `redacts` key. However, this
  418. # isn't always true e.g. if we have censored the event.
  419. logger.debug(
  420. "Withholding redaction event %s as we don't have redacts key",
  421. event_id,
  422. )
  423. continue
  424. redacted_event_id = entry.event.redacts
  425. event_map = await self._get_events_from_cache_or_db([redacted_event_id])
  426. original_event_entry = event_map.get(redacted_event_id)
  427. if not original_event_entry:
  428. # we don't have the redacted event (or it was rejected).
  429. #
  430. # We assume that the redaction isn't authorized for now; if the
  431. # redacted event later turns up, the redaction will be re-checked,
  432. # and if it is found valid, the original will get redacted before it
  433. # is served to the client.
  434. logger.debug(
  435. "Withholding redaction event %s since we don't (yet) have the "
  436. "original %s",
  437. event_id,
  438. redacted_event_id,
  439. )
  440. continue
  441. original_event = original_event_entry.event
  442. if original_event.type == EventTypes.Create:
  443. # we never serve redactions of Creates to clients.
  444. logger.info(
  445. "Withholding redaction %s of create event %s",
  446. event_id,
  447. redacted_event_id,
  448. )
  449. continue
  450. if original_event.room_id != entry.event.room_id:
  451. logger.info(
  452. "Withholding redaction %s of event %s from a different room",
  453. event_id,
  454. redacted_event_id,
  455. )
  456. continue
  457. if entry.event.internal_metadata.need_to_check_redaction():
  458. original_domain = get_domain_from_id(original_event.sender)
  459. redaction_domain = get_domain_from_id(entry.event.sender)
  460. if original_domain != redaction_domain:
  461. # the senders don't match, so this is forbidden
  462. logger.info(
  463. "Withholding redaction %s whose sender domain %s doesn't "
  464. "match that of redacted event %s %s",
  465. event_id,
  466. redaction_domain,
  467. redacted_event_id,
  468. original_domain,
  469. )
  470. continue
  471. # Update the cache to save doing the checks again.
  472. entry.event.internal_metadata.recheck_redaction = False
  473. event = entry.event
  474. if entry.redacted_event:
  475. if redact_behaviour == EventRedactBehaviour.block:
  476. # Skip this event
  477. continue
  478. elif redact_behaviour == EventRedactBehaviour.redact:
  479. event = entry.redacted_event
  480. events.append(event)
  481. if get_prev_content:
  482. if "replaces_state" in event.unsigned:
  483. prev = await self.get_event(
  484. event.unsigned["replaces_state"],
  485. get_prev_content=False,
  486. allow_none=True,
  487. )
  488. if prev:
  489. event.unsigned = dict(event.unsigned)
  490. event.unsigned["prev_content"] = prev.content
  491. event.unsigned["prev_sender"] = prev.sender
  492. return events
  493. async def _get_events_from_cache_or_db(
  494. self, event_ids: Iterable[str], allow_rejected: bool = False
  495. ) -> Dict[str, EventCacheEntry]:
  496. """Fetch a bunch of events from the cache or the database.
  497. If events are pulled from the database, they will be cached for future lookups.
  498. Unknown events are omitted from the response.
  499. Args:
  500. event_ids: The event_ids of the events to fetch
  501. allow_rejected: Whether to include rejected events. If False,
  502. rejected events are omitted from the response.
  503. Returns:
  504. map from event id to result
  505. """
  506. # Shortcut: check if we have any events in the *in memory* cache - this function
  507. # may be called repeatedly for the same event so at this point we cannot reach
  508. # out to any external cache for performance reasons. The external cache is
  509. # checked later on in the `get_missing_events_from_cache_or_db` function below.
  510. event_entry_map = self._get_events_from_local_cache(
  511. event_ids,
  512. )
  513. missing_events_ids = {e for e in event_ids if e not in event_entry_map}
  514. # We now look up if we're already fetching some of the events in the DB,
  515. # if so we wait for those lookups to finish instead of pulling the same
  516. # events out of the DB multiple times.
  517. #
  518. # Note: we might get the same `ObservableDeferred` back for multiple
  519. # events we're already fetching, so we deduplicate the deferreds to
  520. # avoid extraneous work (if we don't do this we can end up in a n^2 mode
  521. # when we wait on the same Deferred N times, then try and merge the
  522. # same dict into itself N times).
  523. already_fetching_ids: Set[str] = set()
  524. already_fetching_deferreds: Set[
  525. ObservableDeferred[Dict[str, EventCacheEntry]]
  526. ] = set()
  527. for event_id in missing_events_ids:
  528. deferred = self._current_event_fetches.get(event_id)
  529. if deferred is not None:
  530. # We're already pulling the event out of the DB. Add the deferred
  531. # to the collection of deferreds to wait on.
  532. already_fetching_ids.add(event_id)
  533. already_fetching_deferreds.add(deferred)
  534. missing_events_ids.difference_update(already_fetching_ids)
  535. if missing_events_ids:
  536. async def get_missing_events_from_cache_or_db() -> Dict[
  537. str, EventCacheEntry
  538. ]:
  539. """Fetches the events in `missing_event_ids` from the database.
  540. Also creates entries in `self._current_event_fetches` to allow
  541. concurrent `_get_events_from_cache_or_db` calls to reuse the same fetch.
  542. """
  543. log_ctx = current_context()
  544. log_ctx.record_event_fetch(len(missing_events_ids))
  545. # Add entries to `self._current_event_fetches` for each event we're
  546. # going to pull from the DB. We use a single deferred that resolves
  547. # to all the events we pulled from the DB (this will result in this
  548. # function returning more events than requested, but that can happen
  549. # already due to `_get_events_from_db`).
  550. fetching_deferred: ObservableDeferred[
  551. Dict[str, EventCacheEntry]
  552. ] = ObservableDeferred(defer.Deferred(), consumeErrors=True)
  553. for event_id in missing_events_ids:
  554. self._current_event_fetches[event_id] = fetching_deferred
  555. # Note that _get_events_from_db is also responsible for turning db rows
  556. # into FrozenEvents (via _get_event_from_row), which involves seeing if
  557. # the events have been redacted, and if so pulling the redaction event
  558. # out of the database to check it.
  559. #
  560. missing_events = {}
  561. try:
  562. # Try to fetch from any external cache. We already checked the
  563. # in-memory cache above.
  564. missing_events = await self._get_events_from_external_cache(
  565. missing_events_ids,
  566. )
  567. # Now actually fetch any remaining events from the DB
  568. db_missing_events = await self._get_events_from_db(
  569. missing_events_ids - missing_events.keys(),
  570. )
  571. missing_events.update(db_missing_events)
  572. except Exception as e:
  573. with PreserveLoggingContext():
  574. fetching_deferred.errback(e)
  575. raise e
  576. finally:
  577. # Ensure that we mark these events as no longer being fetched.
  578. for event_id in missing_events_ids:
  579. self._current_event_fetches.pop(event_id, None)
  580. with PreserveLoggingContext():
  581. fetching_deferred.callback(missing_events)
  582. return missing_events
  583. # We must allow the database fetch to complete in the presence of
  584. # cancellations, since multiple `_get_events_from_cache_or_db` calls can
  585. # reuse the same fetch.
  586. missing_events: Dict[str, EventCacheEntry] = await delay_cancellation(
  587. get_missing_events_from_cache_or_db()
  588. )
  589. event_entry_map.update(missing_events)
  590. if already_fetching_deferreds:
  591. # Wait for the other event requests to finish and add their results
  592. # to ours.
  593. results = await make_deferred_yieldable(
  594. defer.gatherResults(
  595. (d.observe() for d in already_fetching_deferreds),
  596. consumeErrors=True,
  597. )
  598. ).addErrback(unwrapFirstError)
  599. for result in results:
  600. # We filter out events that we haven't asked for as we might get
  601. # a *lot* of superfluous events back, and there is no point
  602. # going through and inserting them all (which can take time).
  603. event_entry_map.update(
  604. (event_id, entry)
  605. for event_id, entry in result.items()
  606. if event_id in already_fetching_ids
  607. )
  608. if not allow_rejected:
  609. event_entry_map = {
  610. event_id: entry
  611. for event_id, entry in event_entry_map.items()
  612. if not entry.event.rejected_reason
  613. }
  614. return event_entry_map
  615. def invalidate_get_event_cache_after_txn(
  616. self, txn: LoggingTransaction, event_id: str
  617. ) -> None:
  618. """
  619. Prepares a database transaction to invalidate the get event cache for a given
  620. event ID when executed successfully. This is achieved by attaching two callbacks
  621. to the transaction, one to invalidate the async cache and one for the in memory
  622. sync cache (importantly called in that order).
  623. Arguments:
  624. txn: the database transaction to attach the callbacks to
  625. event_id: the event ID to be invalidated from caches
  626. """
  627. txn.async_call_after(self._invalidate_async_get_event_cache, event_id)
  628. txn.call_after(self._invalidate_local_get_event_cache, event_id)
  629. async def _invalidate_async_get_event_cache(self, event_id: str) -> None:
  630. """
  631. Invalidates an event in the asyncronous get event cache, which may be remote.
  632. Arguments:
  633. event_id: the event ID to invalidate
  634. """
  635. await self._get_event_cache.invalidate((event_id,))
  636. def _invalidate_local_get_event_cache(self, event_id: str) -> None:
  637. """
  638. Invalidates an event in local in-memory get event caches.
  639. Arguments:
  640. event_id: the event ID to invalidate
  641. """
  642. self._get_event_cache.invalidate_local((event_id,))
  643. self._event_ref.pop(event_id, None)
  644. self._current_event_fetches.pop(event_id, None)
  645. async def _get_events_from_cache(
  646. self, events: Iterable[str], update_metrics: bool = True
  647. ) -> Dict[str, EventCacheEntry]:
  648. """Fetch events from the caches, both in memory and any external.
  649. May return rejected events.
  650. Args:
  651. events: list of event_ids to fetch
  652. update_metrics: Whether to update the cache hit ratio metrics
  653. """
  654. event_map = self._get_events_from_local_cache(
  655. events, update_metrics=update_metrics
  656. )
  657. missing_event_ids = (e for e in events if e not in event_map)
  658. event_map.update(
  659. await self._get_events_from_external_cache(
  660. events=missing_event_ids,
  661. update_metrics=update_metrics,
  662. )
  663. )
  664. return event_map
  665. async def _get_events_from_external_cache(
  666. self, events: Iterable[str], update_metrics: bool = True
  667. ) -> Dict[str, EventCacheEntry]:
  668. """Fetch events from any configured external cache.
  669. May return rejected events.
  670. Args:
  671. events: list of event_ids to fetch
  672. update_metrics: Whether to update the cache hit ratio metrics
  673. """
  674. event_map = {}
  675. for event_id in events:
  676. ret = await self._get_event_cache.get_external(
  677. (event_id,), None, update_metrics=update_metrics
  678. )
  679. if ret:
  680. event_map[event_id] = ret
  681. return event_map
  682. def _get_events_from_local_cache(
  683. self, events: Iterable[str], update_metrics: bool = True
  684. ) -> Dict[str, EventCacheEntry]:
  685. """Fetch events from the local, in memory, caches.
  686. May return rejected events.
  687. Args:
  688. events: list of event_ids to fetch
  689. update_metrics: Whether to update the cache hit ratio metrics
  690. """
  691. event_map = {}
  692. for event_id in events:
  693. # First check if it's in the event cache
  694. ret = self._get_event_cache.get_local(
  695. (event_id,), None, update_metrics=update_metrics
  696. )
  697. if ret:
  698. event_map[event_id] = ret
  699. continue
  700. # Otherwise check if we still have the event in memory.
  701. event = self._event_ref.get(event_id)
  702. if event:
  703. # Reconstruct an event cache entry
  704. cache_entry = EventCacheEntry(
  705. event=event,
  706. # We don't cache weakrefs to redacted events, so we know
  707. # this is None.
  708. redacted_event=None,
  709. )
  710. event_map[event_id] = cache_entry
  711. # We add the entry back into the cache as we want to keep
  712. # recently queried events in the cache.
  713. self._get_event_cache.set_local((event_id,), cache_entry)
  714. return event_map
  715. async def get_stripped_room_state_from_event_context(
  716. self,
  717. context: EventContext,
  718. state_types_to_include: Container[str],
  719. membership_user_id: Optional[str] = None,
  720. ) -> List[JsonDict]:
  721. """
  722. Retrieve the stripped state from a room, given an event context to retrieve state
  723. from as well as the state types to include. Optionally, include the membership
  724. events from a specific user.
  725. "Stripped" state means that only the `type`, `state_key`, `content` and `sender` keys
  726. are included from each state event.
  727. Args:
  728. context: The event context to retrieve state of the room from.
  729. state_types_to_include: The type of state events to include.
  730. membership_user_id: An optional user ID to include the stripped membership state
  731. events of. This is useful when generating the stripped state of a room for
  732. invites. We want to send membership events of the inviter, so that the
  733. invitee can display the inviter's profile information if the room lacks any.
  734. Returns:
  735. A list of dictionaries, each representing a stripped state event from the room.
  736. """
  737. current_state_ids = await context.get_current_state_ids()
  738. # We know this event is not an outlier, so this must be
  739. # non-None.
  740. assert current_state_ids is not None
  741. # The state to include
  742. state_to_include_ids = [
  743. e_id
  744. for k, e_id in current_state_ids.items()
  745. if k[0] in state_types_to_include
  746. or (membership_user_id and k == (EventTypes.Member, membership_user_id))
  747. ]
  748. state_to_include = await self.get_events(state_to_include_ids)
  749. return [
  750. {
  751. "type": e.type,
  752. "state_key": e.state_key,
  753. "content": e.content,
  754. "sender": e.sender,
  755. }
  756. for e in state_to_include.values()
  757. ]
  758. def _maybe_start_fetch_thread(self) -> None:
  759. """Starts an event fetch thread if we are not yet at the maximum number."""
  760. with self._event_fetch_lock:
  761. if (
  762. self._event_fetch_list
  763. and self._event_fetch_ongoing < EVENT_QUEUE_THREADS
  764. ):
  765. self._event_fetch_ongoing += 1
  766. event_fetch_ongoing_gauge.set(self._event_fetch_ongoing)
  767. # `_event_fetch_ongoing` is decremented in `_fetch_thread`.
  768. should_start = True
  769. else:
  770. should_start = False
  771. if should_start:
  772. run_as_background_process("fetch_events", self._fetch_thread)
  773. async def _fetch_thread(self) -> None:
  774. """Services requests for events from `_event_fetch_list`."""
  775. exc = None
  776. try:
  777. await self.db_pool.runWithConnection(self._fetch_loop)
  778. except BaseException as e:
  779. exc = e
  780. raise
  781. finally:
  782. should_restart = False
  783. event_fetches_to_fail = []
  784. with self._event_fetch_lock:
  785. self._event_fetch_ongoing -= 1
  786. event_fetch_ongoing_gauge.set(self._event_fetch_ongoing)
  787. # There may still be work remaining in `_event_fetch_list` if we
  788. # failed, or it was added in between us deciding to exit and
  789. # decrementing `_event_fetch_ongoing`.
  790. if self._event_fetch_list:
  791. if exc is None:
  792. # We decided to exit, but then some more work was added
  793. # before `_event_fetch_ongoing` was decremented.
  794. # If a new event fetch thread was not started, we should
  795. # restart ourselves since the remaining event fetch threads
  796. # may take a while to get around to the new work.
  797. #
  798. # Unfortunately it is not possible to tell whether a new
  799. # event fetch thread was started, so we restart
  800. # unconditionally. If we are unlucky, we will end up with
  801. # an idle fetch thread, but it will time out after
  802. # `EVENT_QUEUE_ITERATIONS * EVENT_QUEUE_TIMEOUT_S` seconds
  803. # in any case.
  804. #
  805. # Note that multiple fetch threads may run down this path at
  806. # the same time.
  807. should_restart = True
  808. elif isinstance(exc, Exception):
  809. if self._event_fetch_ongoing == 0:
  810. # We were the last remaining fetcher and failed.
  811. # Fail any outstanding fetches since no one else will
  812. # handle them.
  813. event_fetches_to_fail = self._event_fetch_list
  814. self._event_fetch_list = []
  815. else:
  816. # We weren't the last remaining fetcher, so another
  817. # fetcher will pick up the work. This will either happen
  818. # after their existing work, however long that takes,
  819. # or after at most `EVENT_QUEUE_TIMEOUT_S` seconds if
  820. # they are idle.
  821. pass
  822. else:
  823. # The exception is a `SystemExit`, `KeyboardInterrupt` or
  824. # `GeneratorExit`. Don't try to do anything clever here.
  825. pass
  826. if should_restart:
  827. # We exited cleanly but noticed more work.
  828. self._maybe_start_fetch_thread()
  829. if event_fetches_to_fail:
  830. # We were the last remaining fetcher and failed.
  831. # Fail any outstanding fetches since no one else will handle them.
  832. assert exc is not None
  833. with PreserveLoggingContext():
  834. for _, deferred in event_fetches_to_fail:
  835. deferred.errback(exc)
  836. def _fetch_loop(self, conn: LoggingDatabaseConnection) -> None:
  837. """Takes a database connection and waits for requests for events from
  838. the _event_fetch_list queue.
  839. """
  840. i = 0
  841. while True:
  842. with self._event_fetch_lock:
  843. event_list = self._event_fetch_list
  844. self._event_fetch_list = []
  845. if not event_list:
  846. # There are no requests waiting. If we haven't yet reached the
  847. # maximum iteration limit, wait for some more requests to turn up.
  848. # Otherwise, bail out.
  849. single_threaded = self.database_engine.single_threaded
  850. if (
  851. not self.USE_DEDICATED_DB_THREADS_FOR_EVENT_FETCHING
  852. or single_threaded
  853. or i > EVENT_QUEUE_ITERATIONS
  854. ):
  855. return
  856. self._event_fetch_lock.wait(EVENT_QUEUE_TIMEOUT_S)
  857. i += 1
  858. continue
  859. i = 0
  860. self._fetch_event_list(conn, event_list)
  861. def _fetch_event_list(
  862. self,
  863. conn: LoggingDatabaseConnection,
  864. event_list: List[Tuple[Iterable[str], "defer.Deferred[Dict[str, _EventRow]]"]],
  865. ) -> None:
  866. """Handle a load of requests from the _event_fetch_list queue
  867. Args:
  868. conn: database connection
  869. event_list:
  870. The fetch requests. Each entry consists of a list of event
  871. ids to be fetched, and a deferred to be completed once the
  872. events have been fetched.
  873. The deferreds are callbacked with a dictionary mapping from event id
  874. to event row. Note that it may well contain additional events that
  875. were not part of this request.
  876. """
  877. with Measure(self._clock, "_fetch_event_list"):
  878. try:
  879. events_to_fetch = {
  880. event_id for events, _ in event_list for event_id in events
  881. }
  882. row_dict = self.db_pool.new_transaction(
  883. conn,
  884. "do_fetch",
  885. [],
  886. [],
  887. [],
  888. self._fetch_event_rows,
  889. events_to_fetch,
  890. )
  891. # We only want to resolve deferreds from the main thread
  892. def fire() -> None:
  893. for _, d in event_list:
  894. d.callback(row_dict)
  895. with PreserveLoggingContext():
  896. self.hs.get_reactor().callFromThread(fire)
  897. except Exception as e:
  898. logger.exception("do_fetch")
  899. # We only want to resolve deferreds from the main thread
  900. def fire_errback(exc: Exception) -> None:
  901. for _, d in event_list:
  902. d.errback(exc)
  903. with PreserveLoggingContext():
  904. self.hs.get_reactor().callFromThread(fire_errback, e)
  905. async def _get_events_from_db(
  906. self, event_ids: Collection[str]
  907. ) -> Dict[str, EventCacheEntry]:
  908. """Fetch a bunch of events from the database.
  909. May return rejected events.
  910. Returned events will be added to the cache for future lookups.
  911. Unknown events are omitted from the response.
  912. Args:
  913. event_ids: The event_ids of the events to fetch
  914. Returns:
  915. map from event id to result. May return extra events which
  916. weren't asked for.
  917. """
  918. fetched_event_ids: Set[str] = set()
  919. fetched_events: Dict[str, _EventRow] = {}
  920. events_to_fetch = event_ids
  921. while events_to_fetch:
  922. row_map = await self._enqueue_events(events_to_fetch)
  923. # we need to recursively fetch any redactions of those events
  924. redaction_ids: Set[str] = set()
  925. for event_id in events_to_fetch:
  926. row = row_map.get(event_id)
  927. fetched_event_ids.add(event_id)
  928. if row:
  929. fetched_events[event_id] = row
  930. redaction_ids.update(row.redactions)
  931. events_to_fetch = redaction_ids.difference(fetched_event_ids)
  932. if events_to_fetch:
  933. logger.debug("Also fetching redaction events %s", events_to_fetch)
  934. # build a map from event_id to EventBase
  935. event_map: Dict[str, EventBase] = {}
  936. for event_id, row in fetched_events.items():
  937. assert row.event_id == event_id
  938. rejected_reason = row.rejected_reason
  939. # If the event or metadata cannot be parsed, log the error and act
  940. # as if the event is unknown.
  941. try:
  942. d = db_to_json(row.json)
  943. except ValueError:
  944. logger.error("Unable to parse json from event: %s", event_id)
  945. continue
  946. try:
  947. internal_metadata = db_to_json(row.internal_metadata)
  948. except ValueError:
  949. logger.error(
  950. "Unable to parse internal_metadata from event: %s", event_id
  951. )
  952. continue
  953. format_version = row.format_version
  954. if format_version is None:
  955. # This means that we stored the event before we had the concept
  956. # of a event format version, so it must be a V1 event.
  957. format_version = EventFormatVersions.V1
  958. room_version_id = row.room_version_id
  959. room_version: Optional[RoomVersion]
  960. if not room_version_id:
  961. # this should only happen for out-of-band membership events which
  962. # arrived before #6983 landed. For all other events, we should have
  963. # an entry in the 'rooms' table.
  964. #
  965. # However, the 'out_of_band_membership' flag is unreliable for older
  966. # invites, so just accept it for all membership events.
  967. #
  968. if d["type"] != EventTypes.Member:
  969. raise Exception(
  970. "Room %s for event %s is unknown" % (d["room_id"], event_id)
  971. )
  972. # so, assuming this is an out-of-band-invite that arrived before #6983
  973. # landed, we know that the room version must be v5 or earlier (because
  974. # v6 hadn't been invented at that point, so invites from such rooms
  975. # would have been rejected.)
  976. #
  977. # The main reason we need to know the room version here (other than
  978. # choosing the right python Event class) is in case the event later has
  979. # to be redacted - and all the room versions up to v5 used the same
  980. # redaction algorithm.
  981. #
  982. # So, the following approximations should be adequate.
  983. if format_version == EventFormatVersions.V1:
  984. # if it's event format v1 then it must be room v1 or v2
  985. room_version = RoomVersions.V1
  986. elif format_version == EventFormatVersions.V2:
  987. # if it's event format v2 then it must be room v3
  988. room_version = RoomVersions.V3
  989. else:
  990. # if it's event format v3 then it must be room v4 or v5
  991. room_version = RoomVersions.V5
  992. else:
  993. room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
  994. if not room_version:
  995. logger.warning(
  996. "Event %s in room %s has unknown room version %s",
  997. event_id,
  998. d["room_id"],
  999. room_version_id,
  1000. )
  1001. continue
  1002. if room_version.event_format != format_version:
  1003. logger.error(
  1004. "Event %s in room %s with version %s has wrong format: "
  1005. "expected %s, was %s",
  1006. event_id,
  1007. d["room_id"],
  1008. room_version_id,
  1009. room_version.event_format,
  1010. format_version,
  1011. )
  1012. continue
  1013. original_ev = make_event_from_dict(
  1014. event_dict=d,
  1015. room_version=room_version,
  1016. internal_metadata_dict=internal_metadata,
  1017. rejected_reason=rejected_reason,
  1018. )
  1019. original_ev.internal_metadata.stream_ordering = row.stream_ordering
  1020. original_ev.internal_metadata.outlier = row.outlier
  1021. # Consistency check: if the content of the event has been modified in the
  1022. # database, then the calculated event ID will not match the event id in the
  1023. # database.
  1024. if original_ev.event_id != event_id:
  1025. # it's difficult to see what to do here. Pretty much all bets are off
  1026. # if Synapse cannot rely on the consistency of its database.
  1027. raise RuntimeError(
  1028. f"Database corruption: Event {event_id} in room {d['room_id']} "
  1029. f"from the database appears to have been modified (calculated "
  1030. f"event id {original_ev.event_id})"
  1031. )
  1032. event_map[event_id] = original_ev
  1033. # finally, we can decide whether each one needs redacting, and build
  1034. # the cache entries.
  1035. result_map: Dict[str, EventCacheEntry] = {}
  1036. for event_id, original_ev in event_map.items():
  1037. redactions = fetched_events[event_id].redactions
  1038. redacted_event = self._maybe_redact_event_row(
  1039. original_ev, redactions, event_map
  1040. )
  1041. cache_entry = EventCacheEntry(
  1042. event=original_ev, redacted_event=redacted_event
  1043. )
  1044. await self._get_event_cache.set((event_id,), cache_entry)
  1045. result_map[event_id] = cache_entry
  1046. if not redacted_event:
  1047. # We only cache references to unredacted events.
  1048. self._event_ref[event_id] = original_ev
  1049. return result_map
  1050. async def _enqueue_events(self, events: Collection[str]) -> Dict[str, _EventRow]:
  1051. """Fetches events from the database using the _event_fetch_list. This
  1052. allows batch and bulk fetching of events - it allows us to fetch events
  1053. without having to create a new transaction for each request for events.
  1054. Args:
  1055. events: events to be fetched.
  1056. Returns:
  1057. A map from event id to row data from the database. May contain events
  1058. that weren't requested.
  1059. """
  1060. events_d: "defer.Deferred[Dict[str, _EventRow]]" = defer.Deferred()
  1061. with self._event_fetch_lock:
  1062. self._event_fetch_list.append((events, events_d))
  1063. self._event_fetch_lock.notify()
  1064. self._maybe_start_fetch_thread()
  1065. logger.debug("Loading %d events: %s", len(events), events)
  1066. with PreserveLoggingContext():
  1067. row_map = await events_d
  1068. logger.debug("Loaded %d events (%d rows)", len(events), len(row_map))
  1069. return row_map
  1070. def _fetch_event_rows(
  1071. self, txn: LoggingTransaction, event_ids: Iterable[str]
  1072. ) -> Dict[str, _EventRow]:
  1073. """Fetch event rows from the database
  1074. Events which are not found are omitted from the result.
  1075. Args:
  1076. txn: The database transaction.
  1077. event_ids: event IDs to fetch
  1078. Returns:
  1079. A map from event id to event info.
  1080. """
  1081. event_dict = {}
  1082. for evs in batch_iter(event_ids, 200):
  1083. sql = """\
  1084. SELECT
  1085. e.event_id,
  1086. e.stream_ordering,
  1087. ej.internal_metadata,
  1088. ej.json,
  1089. ej.format_version,
  1090. r.room_version,
  1091. rej.reason,
  1092. e.outlier
  1093. FROM events AS e
  1094. JOIN event_json AS ej USING (event_id)
  1095. LEFT JOIN rooms r ON r.room_id = e.room_id
  1096. LEFT JOIN rejections as rej USING (event_id)
  1097. WHERE """
  1098. clause, args = make_in_list_sql_clause(
  1099. txn.database_engine, "e.event_id", evs
  1100. )
  1101. txn.execute(sql + clause, args)
  1102. for row in txn:
  1103. event_id = row[0]
  1104. event_dict[event_id] = _EventRow(
  1105. event_id=event_id,
  1106. stream_ordering=row[1],
  1107. internal_metadata=row[2],
  1108. json=row[3],
  1109. format_version=row[4],
  1110. room_version_id=row[5],
  1111. rejected_reason=row[6],
  1112. redactions=[],
  1113. outlier=row[7],
  1114. )
  1115. # check for redactions
  1116. redactions_sql = "SELECT event_id, redacts FROM redactions WHERE "
  1117. clause, args = make_in_list_sql_clause(txn.database_engine, "redacts", evs)
  1118. txn.execute(redactions_sql + clause, args)
  1119. for (redacter, redacted) in txn:
  1120. d = event_dict.get(redacted)
  1121. if d:
  1122. d.redactions.append(redacter)
  1123. return event_dict
  1124. def _maybe_redact_event_row(
  1125. self,
  1126. original_ev: EventBase,
  1127. redactions: Iterable[str],
  1128. event_map: Dict[str, EventBase],
  1129. ) -> Optional[EventBase]:
  1130. """Given an event object and a list of possible redacting event ids,
  1131. determine whether to honour any of those redactions and if so return a redacted
  1132. event.
  1133. Args:
  1134. original_ev: The original event.
  1135. redactions: list of event ids of potential redaction events
  1136. event_map: other events which have been fetched, in which we can
  1137. look up the redaaction events. Map from event id to event.
  1138. Returns:
  1139. If the event should be redacted, a pruned event object. Otherwise, None.
  1140. """
  1141. if original_ev.type == "m.room.create":
  1142. # we choose to ignore redactions of m.room.create events.
  1143. return None
  1144. for redaction_id in redactions:
  1145. redaction_event = event_map.get(redaction_id)
  1146. if not redaction_event or redaction_event.rejected_reason:
  1147. # we don't have the redaction event, or the redaction event was not
  1148. # authorized.
  1149. logger.debug(
  1150. "%s was redacted by %s but redaction not found/authed",
  1151. original_ev.event_id,
  1152. redaction_id,
  1153. )
  1154. continue
  1155. if redaction_event.room_id != original_ev.room_id:
  1156. logger.debug(
  1157. "%s was redacted by %s but redaction was in a different room!",
  1158. original_ev.event_id,
  1159. redaction_id,
  1160. )
  1161. continue
  1162. # Starting in room version v3, some redactions need to be
  1163. # rechecked if we didn't have the redacted event at the
  1164. # time, so we recheck on read instead.
  1165. if redaction_event.internal_metadata.need_to_check_redaction():
  1166. expected_domain = get_domain_from_id(original_ev.sender)
  1167. if get_domain_from_id(redaction_event.sender) == expected_domain:
  1168. # This redaction event is allowed. Mark as not needing a recheck.
  1169. redaction_event.internal_metadata.recheck_redaction = False
  1170. else:
  1171. # Senders don't match, so the event isn't actually redacted
  1172. logger.debug(
  1173. "%s was redacted by %s but the senders don't match",
  1174. original_ev.event_id,
  1175. redaction_id,
  1176. )
  1177. continue
  1178. logger.debug("Redacting %s due to %s", original_ev.event_id, redaction_id)
  1179. # we found a good redaction event. Redact!
  1180. redacted_event = prune_event(original_ev)
  1181. redacted_event.unsigned["redacted_by"] = redaction_id
  1182. # It's fine to add the event directly, since get_pdu_json
  1183. # will serialise this field correctly
  1184. redacted_event.unsigned["redacted_because"] = redaction_event
  1185. return redacted_event
  1186. # no valid redaction found for this event
  1187. return None
  1188. async def have_events_in_timeline(self, event_ids: Iterable[str]) -> Set[str]:
  1189. """Given a list of event ids, check if we have already processed and
  1190. stored them as non outliers.
  1191. """
  1192. rows = await self.db_pool.simple_select_many_batch(
  1193. table="events",
  1194. retcols=("event_id",),
  1195. column="event_id",
  1196. iterable=list(event_ids),
  1197. keyvalues={"outlier": False},
  1198. desc="have_events_in_timeline",
  1199. )
  1200. return {r["event_id"] for r in rows}
  1201. async def have_seen_events(
  1202. self, room_id: str, event_ids: Iterable[str]
  1203. ) -> Set[str]:
  1204. """Given a list of event ids, check if we have already processed them.
  1205. The room_id is only used to structure the cache (so that it can later be
  1206. invalidated by room_id) - there is no guarantee that the events are actually
  1207. in the room in question.
  1208. Args:
  1209. room_id: Room we are polling
  1210. event_ids: events we are looking for
  1211. Returns:
  1212. The set of events we have already seen.
  1213. """
  1214. # @cachedList chomps lots of memory if you call it with a big list, so
  1215. # we break it down. However, each batch requires its own index scan, so we make
  1216. # the batches as big as possible.
  1217. results: Set[str] = set()
  1218. for chunk in batch_iter(event_ids, 500):
  1219. r = await self._have_seen_events_dict(
  1220. [(room_id, event_id) for event_id in chunk]
  1221. )
  1222. results.update(eid for ((_rid, eid), have_event) in r.items() if have_event)
  1223. return results
  1224. @cachedList(cached_method_name="have_seen_event", list_name="keys")
  1225. async def _have_seen_events_dict(
  1226. self, keys: Collection[Tuple[str, str]]
  1227. ) -> Dict[Tuple[str, str], bool]:
  1228. """Helper for have_seen_events
  1229. Returns:
  1230. a dict {(room_id, event_id)-> bool}
  1231. """
  1232. # if the event cache contains the event, obviously we've seen it.
  1233. cache_results = {
  1234. (rid, eid)
  1235. for (rid, eid) in keys
  1236. if await self._get_event_cache.contains((eid,))
  1237. }
  1238. results = dict.fromkeys(cache_results, True)
  1239. remaining = [k for k in keys if k not in cache_results]
  1240. if not remaining:
  1241. return results
  1242. def have_seen_events_txn(txn: LoggingTransaction) -> None:
  1243. # we deliberately do *not* query the database for room_id, to make the
  1244. # query an index-only lookup on `events_event_id_key`.
  1245. #
  1246. # We therefore pull the events from the database into a set...
  1247. sql = "SELECT event_id FROM events AS e WHERE "
  1248. clause, args = make_in_list_sql_clause(
  1249. txn.database_engine, "e.event_id", [eid for (_rid, eid) in remaining]
  1250. )
  1251. txn.execute(sql + clause, args)
  1252. found_events = {eid for eid, in txn}
  1253. # ... and then we can update the results for each key
  1254. results.update(
  1255. {(rid, eid): (eid in found_events) for (rid, eid) in remaining}
  1256. )
  1257. await self.db_pool.runInteraction("have_seen_events", have_seen_events_txn)
  1258. return results
  1259. @cached(max_entries=100000, tree=True)
  1260. async def have_seen_event(self, room_id: str, event_id: str) -> bool:
  1261. res = await self._have_seen_events_dict(((room_id, event_id),))
  1262. return res[(room_id, event_id)]
  1263. def _get_current_state_event_counts_txn(
  1264. self, txn: LoggingTransaction, room_id: str
  1265. ) -> int:
  1266. """
  1267. See get_current_state_event_counts.
  1268. """
  1269. sql = "SELECT COUNT(*) FROM current_state_events WHERE room_id=?"
  1270. txn.execute(sql, (room_id,))
  1271. row = txn.fetchone()
  1272. return row[0] if row else 0
  1273. async def get_current_state_event_counts(self, room_id: str) -> int:
  1274. """
  1275. Gets the current number of state events in a room.
  1276. Args:
  1277. room_id: The room ID to query.
  1278. Returns:
  1279. The current number of state events.
  1280. """
  1281. return await self.db_pool.runInteraction(
  1282. "get_current_state_event_counts",
  1283. self._get_current_state_event_counts_txn,
  1284. room_id,
  1285. )
  1286. async def get_room_complexity(self, room_id: str) -> Dict[str, float]:
  1287. """
  1288. Get a rough approximation of the complexity of the room. This is used by
  1289. remote servers to decide whether they wish to join the room or not.
  1290. Higher complexity value indicates that being in the room will consume
  1291. more resources.
  1292. Args:
  1293. room_id: The room ID to query.
  1294. Returns:
  1295. dict[str:float] of complexity version to complexity.
  1296. """
  1297. state_events = await self.get_current_state_event_counts(room_id)
  1298. # Call this one "v1", so we can introduce new ones as we want to develop
  1299. # it.
  1300. complexity_v1 = round(state_events / 500, 2)
  1301. return {"v1": complexity_v1}
  1302. async def get_all_new_forward_event_rows(
  1303. self, instance_name: str, last_id: int, current_id: int, limit: int
  1304. ) -> List[Tuple[int, str, str, str, str, str, str, str, bool, bool]]:
  1305. """Returns new events, for the Events replication stream
  1306. Args:
  1307. last_id: the last stream_id from the previous batch.
  1308. current_id: the maximum stream_id to return up to
  1309. limit: the maximum number of rows to return
  1310. Returns:
  1311. a list of events stream rows. Each tuple consists of a stream id as
  1312. the first element, followed by fields suitable for casting into an
  1313. EventsStreamRow.
  1314. """
  1315. def get_all_new_forward_event_rows(
  1316. txn: LoggingTransaction,
  1317. ) -> List[Tuple[int, str, str, str, str, str, str, str, bool, bool]]:
  1318. sql = (
  1319. "SELECT e.stream_ordering, e.event_id, e.room_id, e.type,"
  1320. " se.state_key, redacts, relates_to_id, membership, rejections.reason IS NOT NULL,"
  1321. " e.outlier"
  1322. " FROM events AS e"
  1323. " LEFT JOIN redactions USING (event_id)"
  1324. " LEFT JOIN state_events AS se USING (event_id)"
  1325. " LEFT JOIN event_relations USING (event_id)"
  1326. " LEFT JOIN room_memberships USING (event_id)"
  1327. " LEFT JOIN rejections USING (event_id)"
  1328. " WHERE ? < stream_ordering AND stream_ordering <= ?"
  1329. " AND instance_name = ?"
  1330. " ORDER BY stream_ordering ASC"
  1331. " LIMIT ?"
  1332. )
  1333. txn.execute(sql, (last_id, current_id, instance_name, limit))
  1334. return cast(
  1335. List[Tuple[int, str, str, str, str, str, str, str, bool, bool]],
  1336. txn.fetchall(),
  1337. )
  1338. return await self.db_pool.runInteraction(
  1339. "get_all_new_forward_event_rows", get_all_new_forward_event_rows
  1340. )
  1341. async def get_ex_outlier_stream_rows(
  1342. self, instance_name: str, last_id: int, current_id: int
  1343. ) -> List[Tuple[int, str, str, str, str, str, str, str, bool, bool]]:
  1344. """Returns de-outliered events, for the Events replication stream
  1345. Args:
  1346. last_id: the last stream_id from the previous batch.
  1347. current_id: the maximum stream_id to return up to
  1348. Returns:
  1349. a list of events stream rows. Each tuple consists of a stream id as
  1350. the first element, followed by fields suitable for casting into an
  1351. EventsStreamRow.
  1352. """
  1353. def get_ex_outlier_stream_rows_txn(
  1354. txn: LoggingTransaction,
  1355. ) -> List[Tuple[int, str, str, str, str, str, str, str, bool, bool]]:
  1356. sql = (
  1357. "SELECT event_stream_ordering, e.event_id, e.room_id, e.type,"
  1358. " se.state_key, redacts, relates_to_id, membership, rejections.reason IS NOT NULL,"
  1359. " e.outlier"
  1360. " FROM events AS e"
  1361. # NB: the next line (inner join) is what makes this query different from
  1362. # get_all_new_forward_event_rows.
  1363. " INNER JOIN ex_outlier_stream AS out USING (event_id)"
  1364. " LEFT JOIN redactions USING (event_id)"
  1365. " LEFT JOIN state_events AS se USING (event_id)"
  1366. " LEFT JOIN event_relations USING (event_id)"
  1367. " LEFT JOIN room_memberships USING (event_id)"
  1368. " LEFT JOIN rejections USING (event_id)"
  1369. " WHERE ? < event_stream_ordering"
  1370. " AND event_stream_ordering <= ?"
  1371. " AND out.instance_name = ?"
  1372. " ORDER BY event_stream_ordering ASC"
  1373. )
  1374. txn.execute(sql, (last_id, current_id, instance_name))
  1375. return cast(
  1376. List[Tuple[int, str, str, str, str, str, str, str, bool, bool]],
  1377. txn.fetchall(),
  1378. )
  1379. return await self.db_pool.runInteraction(
  1380. "get_ex_outlier_stream_rows", get_ex_outlier_stream_rows_txn
  1381. )
  1382. async def get_all_new_backfill_event_rows(
  1383. self, instance_name: str, last_id: int, current_id: int, limit: int
  1384. ) -> Tuple[List[Tuple[int, Tuple[str, str, str, str, str, str]]], int, bool]:
  1385. """Get updates for backfill replication stream, including all new
  1386. backfilled events and events that have gone from being outliers to not.
  1387. NOTE: The IDs given here are from replication, and so should be
  1388. *positive*.
  1389. Args:
  1390. instance_name: The writer we want to fetch updates from. Unused
  1391. here since there is only ever one writer.
  1392. last_id: The token to fetch updates from. Exclusive.
  1393. current_id: The token to fetch updates up to. Inclusive.
  1394. limit: The requested limit for the number of rows to return. The
  1395. function may return more or fewer rows.
  1396. Returns:
  1397. A tuple consisting of: the updates, a token to use to fetch
  1398. subsequent updates, and whether we returned fewer rows than exists
  1399. between the requested tokens due to the limit.
  1400. The token returned can be used in a subsequent call to this
  1401. function to get further updatees.
  1402. The updates are a list of 2-tuples of stream ID and the row data
  1403. """
  1404. if last_id == current_id:
  1405. return [], current_id, False
  1406. def get_all_new_backfill_event_rows(
  1407. txn: LoggingTransaction,
  1408. ) -> Tuple[List[Tuple[int, Tuple[str, str, str, str, str, str]]], int, bool]:
  1409. sql = (
  1410. "SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,"
  1411. " se.state_key, redacts, relates_to_id"
  1412. " FROM events AS e"
  1413. " LEFT JOIN redactions USING (event_id)"
  1414. " LEFT JOIN state_events AS se USING (event_id)"
  1415. " LEFT JOIN event_relations USING (event_id)"
  1416. " WHERE ? > stream_ordering AND stream_ordering >= ?"
  1417. " AND instance_name = ?"
  1418. " ORDER BY stream_ordering ASC"
  1419. " LIMIT ?"
  1420. )
  1421. txn.execute(sql, (-last_id, -current_id, instance_name, limit))
  1422. new_event_updates: List[
  1423. Tuple[int, Tuple[str, str, str, str, str, str]]
  1424. ] = []
  1425. row: Tuple[int, str, str, str, str, str, str]
  1426. # Type safety: iterating over `txn` yields `Tuple`, i.e.
  1427. # `Tuple[Any, ...]` of arbitrary length. Mypy detects assigning a
  1428. # variadic tuple to a fixed length tuple and flags it up as an error.
  1429. for row in txn: # type: ignore[assignment]
  1430. new_event_updates.append((row[0], row[1:]))
  1431. limited = False
  1432. if len(new_event_updates) == limit:
  1433. upper_bound = new_event_updates[-1][0]
  1434. limited = True
  1435. else:
  1436. upper_bound = current_id
  1437. sql = (
  1438. "SELECT -event_stream_ordering, e.event_id, e.room_id, e.type,"
  1439. " se.state_key, redacts, relates_to_id"
  1440. " FROM events AS e"
  1441. " INNER JOIN ex_outlier_stream AS out USING (event_id)"
  1442. " LEFT JOIN redactions USING (event_id)"
  1443. " LEFT JOIN state_events AS se USING (event_id)"
  1444. " LEFT JOIN event_relations USING (event_id)"
  1445. " WHERE ? > event_stream_ordering"
  1446. " AND event_stream_ordering >= ?"
  1447. " AND out.instance_name = ?"
  1448. " ORDER BY event_stream_ordering DESC"
  1449. )
  1450. txn.execute(sql, (-last_id, -upper_bound, instance_name))
  1451. # Type safety: iterating over `txn` yields `Tuple`, i.e.
  1452. # `Tuple[Any, ...]` of arbitrary length. Mypy detects assigning a
  1453. # variadic tuple to a fixed length tuple and flags it up as an error.
  1454. for row in txn: # type: ignore[assignment]
  1455. new_event_updates.append((row[0], row[1:]))
  1456. if len(new_event_updates) >= limit:
  1457. upper_bound = new_event_updates[-1][0]
  1458. limited = True
  1459. return new_event_updates, upper_bound, limited
  1460. return await self.db_pool.runInteraction(
  1461. "get_all_new_backfill_event_rows", get_all_new_backfill_event_rows
  1462. )
  1463. async def get_all_updated_current_state_deltas(
  1464. self, instance_name: str, from_token: int, to_token: int, target_row_count: int
  1465. ) -> Tuple[List[Tuple[int, str, str, str, str]], int, bool]:
  1466. """Fetch updates from current_state_delta_stream
  1467. Args:
  1468. from_token: The previous stream token. Updates from this stream id will
  1469. be excluded.
  1470. to_token: The current stream token (ie the upper limit). Updates up to this
  1471. stream id will be included (modulo the 'limit' param)
  1472. target_row_count: The number of rows to try to return. If more rows are
  1473. available, we will set 'limited' in the result. In the event of a large
  1474. batch, we may return more rows than this.
  1475. Returns:
  1476. A triplet `(updates, new_last_token, limited)`, where:
  1477. * `updates` is a list of database tuples.
  1478. * `new_last_token` is the new position in stream.
  1479. * `limited` is whether there are more updates to fetch.
  1480. """
  1481. def get_all_updated_current_state_deltas_txn(
  1482. txn: LoggingTransaction,
  1483. ) -> List[Tuple[int, str, str, str, str]]:
  1484. sql = """
  1485. SELECT stream_id, room_id, type, state_key, event_id
  1486. FROM current_state_delta_stream
  1487. WHERE ? < stream_id AND stream_id <= ?
  1488. AND instance_name = ?
  1489. ORDER BY stream_id ASC LIMIT ?
  1490. """
  1491. txn.execute(sql, (from_token, to_token, instance_name, target_row_count))
  1492. return cast(List[Tuple[int, str, str, str, str]], txn.fetchall())
  1493. def get_deltas_for_stream_id_txn(
  1494. txn: LoggingTransaction, stream_id: int
  1495. ) -> List[Tuple[int, str, str, str, str]]:
  1496. sql = """
  1497. SELECT stream_id, room_id, type, state_key, event_id
  1498. FROM current_state_delta_stream
  1499. WHERE stream_id = ?
  1500. """
  1501. txn.execute(sql, [stream_id])
  1502. return cast(List[Tuple[int, str, str, str, str]], txn.fetchall())
  1503. # we need to make sure that, for every stream id in the results, we get *all*
  1504. # the rows with that stream id.
  1505. rows: List[Tuple[int, str, str, str, str]] = await self.db_pool.runInteraction(
  1506. "get_all_updated_current_state_deltas",
  1507. get_all_updated_current_state_deltas_txn,
  1508. )
  1509. # if we've got fewer rows than the limit, we're good
  1510. if len(rows) < target_row_count:
  1511. return rows, to_token, False
  1512. # we hit the limit, so reduce the upper limit so that we exclude the stream id
  1513. # of the last row in the result.
  1514. assert rows[-1][0] <= to_token
  1515. to_token = rows[-1][0] - 1
  1516. # search backwards through the list for the point to truncate
  1517. for idx in range(len(rows) - 1, 0, -1):
  1518. if rows[idx - 1][0] <= to_token:
  1519. return rows[:idx], to_token, True
  1520. # bother. We didn't get a full set of changes for even a single
  1521. # stream id. let's run the query again, without a row limit, but for
  1522. # just one stream id.
  1523. to_token += 1
  1524. rows = await self.db_pool.runInteraction(
  1525. "get_deltas_for_stream_id", get_deltas_for_stream_id_txn, to_token
  1526. )
  1527. return rows, to_token, True
  1528. async def is_event_after(self, event_id1: str, event_id2: str) -> bool:
  1529. """Returns True if event_id1 is after event_id2 in the stream"""
  1530. to_1, so_1 = await self.get_event_ordering(event_id1)
  1531. to_2, so_2 = await self.get_event_ordering(event_id2)
  1532. return (to_1, so_1) > (to_2, so_2)
  1533. @cached(max_entries=5000)
  1534. async def get_event_ordering(self, event_id: str) -> Tuple[int, int]:
  1535. res = await self.db_pool.simple_select_one(
  1536. table="events",
  1537. retcols=["topological_ordering", "stream_ordering"],
  1538. keyvalues={"event_id": event_id},
  1539. allow_none=True,
  1540. )
  1541. if not res:
  1542. raise SynapseError(404, "Could not find event %s" % (event_id,))
  1543. return int(res["topological_ordering"]), int(res["stream_ordering"])
  1544. async def get_next_event_to_expire(self) -> Optional[Tuple[str, int]]:
  1545. """Retrieve the entry with the lowest expiry timestamp in the event_expiry
  1546. table, or None if there's no more event to expire.
  1547. Returns:
  1548. A tuple containing the event ID as its first element and an expiry timestamp
  1549. as its second one, if there's at least one row in the event_expiry table.
  1550. None otherwise.
  1551. """
  1552. def get_next_event_to_expire_txn(
  1553. txn: LoggingTransaction,
  1554. ) -> Optional[Tuple[str, int]]:
  1555. txn.execute(
  1556. """
  1557. SELECT event_id, expiry_ts FROM event_expiry
  1558. ORDER BY expiry_ts ASC LIMIT 1
  1559. """
  1560. )
  1561. return cast(Optional[Tuple[str, int]], txn.fetchone())
  1562. return await self.db_pool.runInteraction(
  1563. desc="get_next_event_to_expire", func=get_next_event_to_expire_txn
  1564. )
  1565. async def get_event_id_from_transaction_id(
  1566. self, room_id: str, user_id: str, token_id: int, txn_id: str
  1567. ) -> Optional[str]:
  1568. """Look up if we have already persisted an event for the transaction ID,
  1569. returning the event ID if so.
  1570. """
  1571. return await self.db_pool.simple_select_one_onecol(
  1572. table="event_txn_id",
  1573. keyvalues={
  1574. "room_id": room_id,
  1575. "user_id": user_id,
  1576. "token_id": token_id,
  1577. "txn_id": txn_id,
  1578. },
  1579. retcol="event_id",
  1580. allow_none=True,
  1581. desc="get_event_id_from_transaction_id",
  1582. )
  1583. async def get_already_persisted_events(
  1584. self, events: Iterable[EventBase]
  1585. ) -> Dict[str, str]:
  1586. """Look up if we have already persisted an event for the transaction ID,
  1587. returning a mapping from event ID in the given list to the event ID of
  1588. an existing event.
  1589. Also checks if there are duplicates in the given events, if there are
  1590. will map duplicates to the *first* event.
  1591. """
  1592. mapping = {}
  1593. txn_id_to_event: Dict[Tuple[str, int, str], str] = {}
  1594. for event in events:
  1595. token_id = getattr(event.internal_metadata, "token_id", None)
  1596. txn_id = getattr(event.internal_metadata, "txn_id", None)
  1597. if token_id and txn_id:
  1598. # Check if this is a duplicate of an event in the given events.
  1599. existing = txn_id_to_event.get((event.room_id, token_id, txn_id))
  1600. if existing:
  1601. mapping[event.event_id] = existing
  1602. continue
  1603. # Check if this is a duplicate of an event we've already
  1604. # persisted.
  1605. existing = await self.get_event_id_from_transaction_id(
  1606. event.room_id, event.sender, token_id, txn_id
  1607. )
  1608. if existing:
  1609. mapping[event.event_id] = existing
  1610. txn_id_to_event[(event.room_id, token_id, txn_id)] = existing
  1611. else:
  1612. txn_id_to_event[(event.room_id, token_id, txn_id)] = event.event_id
  1613. return mapping
  1614. @wrap_as_background_process("_cleanup_old_transaction_ids")
  1615. async def _cleanup_old_transaction_ids(self) -> None:
  1616. """Cleans out transaction id mappings older than 24hrs."""
  1617. def _cleanup_old_transaction_ids_txn(txn: LoggingTransaction) -> None:
  1618. sql = """
  1619. DELETE FROM event_txn_id
  1620. WHERE inserted_ts < ?
  1621. """
  1622. one_day_ago = self._clock.time_msec() - 24 * 60 * 60 * 1000
  1623. txn.execute(sql, (one_day_ago,))
  1624. return await self.db_pool.runInteraction(
  1625. "_cleanup_old_transaction_ids",
  1626. _cleanup_old_transaction_ids_txn,
  1627. )
  1628. async def is_event_next_to_backward_gap(self, event: EventBase) -> bool:
  1629. """Check if the given event is next to a backward gap of missing events.
  1630. <latest messages> A(False)--->B(False)--->C(True)---> <gap, unknown events> <oldest messages>
  1631. Args:
  1632. room_id: room where the event lives
  1633. event_id: event to check
  1634. Returns:
  1635. Boolean indicating whether it's an extremity
  1636. """
  1637. def is_event_next_to_backward_gap_txn(txn: LoggingTransaction) -> bool:
  1638. # If the event in question has any of its prev_events listed as a
  1639. # backward extremity, it's next to a gap.
  1640. #
  1641. # We can't just check the backward edges in `event_edges` because
  1642. # when we persist events, we will also record the prev_events as
  1643. # edges to the event in question regardless of whether we have those
  1644. # prev_events yet. We need to check whether those prev_events are
  1645. # backward extremities, also known as gaps, that need to be
  1646. # backfilled.
  1647. backward_extremity_query = """
  1648. SELECT 1 FROM event_backward_extremities
  1649. WHERE
  1650. room_id = ?
  1651. AND %s
  1652. LIMIT 1
  1653. """
  1654. # If the event in question is a backward extremity or has any of its
  1655. # prev_events listed as a backward extremity, it's next to a
  1656. # backward gap.
  1657. clause, args = make_in_list_sql_clause(
  1658. self.database_engine,
  1659. "event_id",
  1660. [event.event_id] + list(event.prev_event_ids()),
  1661. )
  1662. txn.execute(backward_extremity_query % (clause,), [event.room_id] + args)
  1663. backward_extremities = txn.fetchall()
  1664. # We consider any backward extremity as a backward gap
  1665. if len(backward_extremities):
  1666. return True
  1667. return False
  1668. return await self.db_pool.runInteraction(
  1669. "is_event_next_to_backward_gap_txn",
  1670. is_event_next_to_backward_gap_txn,
  1671. )
  1672. async def is_event_next_to_forward_gap(self, event: EventBase) -> bool:
  1673. """Check if the given event is next to a forward gap of missing events.
  1674. The gap in front of the latest events is not considered a gap.
  1675. <latest messages> A(False)--->B(False)--->C(False)---> <gap, unknown events> <oldest messages>
  1676. <latest messages> A(False)--->B(False)---> <gap, unknown events> --->D(True)--->E(False) <oldest messages>
  1677. Args:
  1678. room_id: room where the event lives
  1679. event_id: event to check
  1680. Returns:
  1681. Boolean indicating whether it's an extremity
  1682. """
  1683. def is_event_next_to_gap_txn(txn: LoggingTransaction) -> bool:
  1684. # If the event in question is a forward extremity, we will just
  1685. # consider any potential forward gap as not a gap since it's one of
  1686. # the latest events in the room.
  1687. #
  1688. # `event_forward_extremities` does not include backfilled or outlier
  1689. # events so we can't rely on it to find forward gaps. We can only
  1690. # use it to determine whether a message is the latest in the room.
  1691. #
  1692. # We can't combine this query with the `forward_edge_query` below
  1693. # because if the event in question has no forward edges (isn't
  1694. # referenced by any other event's prev_events) but is in
  1695. # `event_forward_extremities`, we don't want to return 0 rows and
  1696. # say it's next to a gap.
  1697. forward_extremity_query = """
  1698. SELECT 1 FROM event_forward_extremities
  1699. WHERE
  1700. room_id = ?
  1701. AND event_id = ?
  1702. LIMIT 1
  1703. """
  1704. # We consider any forward extremity as the latest in the room and
  1705. # not a forward gap.
  1706. #
  1707. # To expand, even though there is technically a gap at the front of
  1708. # the room where the forward extremities are, we consider those the
  1709. # latest messages in the room so asking other homeservers for more
  1710. # is useless. The new latest messages will just be federated as
  1711. # usual.
  1712. txn.execute(forward_extremity_query, (event.room_id, event.event_id))
  1713. if txn.fetchone():
  1714. return False
  1715. # Check to see whether the event in question is already referenced
  1716. # by another event. If we don't see any edges, we're next to a
  1717. # forward gap.
  1718. forward_edge_query = """
  1719. SELECT 1 FROM event_edges
  1720. /* Check to make sure the event referencing our event in question is not rejected */
  1721. LEFT JOIN rejections ON event_edges.event_id = rejections.event_id
  1722. WHERE
  1723. event_edges.prev_event_id = ?
  1724. /* It's not a valid edge if the event referencing our event in
  1725. * question is rejected.
  1726. */
  1727. AND rejections.event_id IS NULL
  1728. LIMIT 1
  1729. """
  1730. # If there are no forward edges to the event in question (another
  1731. # event hasn't referenced this event in their prev_events), then we
  1732. # assume there is a forward gap in the history.
  1733. txn.execute(forward_edge_query, (event.event_id,))
  1734. if not txn.fetchone():
  1735. return True
  1736. return False
  1737. return await self.db_pool.runInteraction(
  1738. "is_event_next_to_gap_txn",
  1739. is_event_next_to_gap_txn,
  1740. )
  1741. async def get_event_id_for_timestamp(
  1742. self, room_id: str, timestamp: int, direction: str
  1743. ) -> Optional[str]:
  1744. """Find the closest event to the given timestamp in the given direction.
  1745. Args:
  1746. room_id: Room to fetch the event from
  1747. timestamp: The point in time (inclusive) we should navigate from in
  1748. the given direction to find the closest event.
  1749. direction: ["f"|"b"] to indicate whether we should navigate forward
  1750. or backward from the given timestamp to find the closest event.
  1751. Returns:
  1752. The closest event_id otherwise None if we can't find any event in
  1753. the given direction.
  1754. """
  1755. sql_template = """
  1756. SELECT event_id FROM events
  1757. LEFT JOIN rejections USING (event_id)
  1758. WHERE
  1759. origin_server_ts %s ?
  1760. AND room_id = ?
  1761. /* Make sure event is not rejected */
  1762. AND rejections.event_id IS NULL
  1763. ORDER BY origin_server_ts %s
  1764. LIMIT 1;
  1765. """
  1766. def get_event_id_for_timestamp_txn(txn: LoggingTransaction) -> Optional[str]:
  1767. if direction == "b":
  1768. # Find closest event *before* a given timestamp. We use descending
  1769. # (which gives values largest to smallest) because we want the
  1770. # largest possible timestamp *before* the given timestamp.
  1771. comparison_operator = "<="
  1772. order = "DESC"
  1773. else:
  1774. # Find closest event *after* a given timestamp. We use ascending
  1775. # (which gives values smallest to largest) because we want the
  1776. # closest possible timestamp *after* the given timestamp.
  1777. comparison_operator = ">="
  1778. order = "ASC"
  1779. txn.execute(
  1780. sql_template % (comparison_operator, order), (timestamp, room_id)
  1781. )
  1782. row = txn.fetchone()
  1783. if row:
  1784. (event_id,) = row
  1785. return event_id
  1786. return None
  1787. if direction not in ("f", "b"):
  1788. raise ValueError("Unknown direction: %s" % (direction,))
  1789. return await self.db_pool.runInteraction(
  1790. "get_event_id_for_timestamp_txn",
  1791. get_event_id_for_timestamp_txn,
  1792. )
  1793. @cachedList(cached_method_name="is_partial_state_event", list_name="event_ids")
  1794. async def get_partial_state_events(
  1795. self, event_ids: Collection[str]
  1796. ) -> Dict[str, bool]:
  1797. """Checks which of the given events have partial state
  1798. Args:
  1799. event_ids: the events we want to check for partial state.
  1800. Returns:
  1801. a dict mapping from event id to partial-stateness. We return True for
  1802. any of the events which are unknown (or are outliers).
  1803. """
  1804. result = await self.db_pool.simple_select_many_batch(
  1805. table="partial_state_events",
  1806. column="event_id",
  1807. iterable=event_ids,
  1808. retcols=["event_id"],
  1809. desc="get_partial_state_events",
  1810. )
  1811. # convert the result to a dict, to make @cachedList work
  1812. partial = {r["event_id"] for r in result}
  1813. return {e_id: e_id in partial for e_id in event_ids}
  1814. @cached()
  1815. async def is_partial_state_event(self, event_id: str) -> bool:
  1816. """Checks if the given event has partial state"""
  1817. result = await self.db_pool.simple_select_one_onecol(
  1818. table="partial_state_events",
  1819. keyvalues={"event_id": event_id},
  1820. retcol="1",
  1821. allow_none=True,
  1822. desc="is_partial_state_event",
  1823. )
  1824. return result is not None
  1825. async def get_partial_state_events_batch(self, room_id: str) -> List[str]:
  1826. """Get a list of events in the given room that have partial state"""
  1827. return await self.db_pool.runInteraction(
  1828. "get_partial_state_events_batch",
  1829. self._get_partial_state_events_batch_txn,
  1830. room_id,
  1831. )
  1832. @staticmethod
  1833. def _get_partial_state_events_batch_txn(
  1834. txn: LoggingTransaction, room_id: str
  1835. ) -> List[str]:
  1836. # we want to work through the events from oldest to newest, so
  1837. # we only want events whose prev_events do *not* have partial state - hence
  1838. # the 'NOT EXISTS' clause in the below.
  1839. #
  1840. # This is necessary because ordering by stream ordering isn't quite enough
  1841. # to ensure that we work from oldest to newest event (in particular,
  1842. # if an event is initially persisted as an outlier and later de-outliered,
  1843. # it can end up with a lower stream_ordering than its prev_events).
  1844. #
  1845. # Typically this means we'll only return one event per batch, but that's
  1846. # hard to do much about.
  1847. #
  1848. # See also: https://github.com/matrix-org/synapse/issues/13001
  1849. txn.execute(
  1850. """
  1851. SELECT event_id FROM partial_state_events AS pse
  1852. JOIN events USING (event_id)
  1853. WHERE pse.room_id = ? AND
  1854. NOT EXISTS(
  1855. SELECT 1 FROM event_edges AS ee
  1856. JOIN partial_state_events AS prev_pse ON (prev_pse.event_id=ee.prev_event_id)
  1857. WHERE ee.event_id=pse.event_id
  1858. )
  1859. ORDER BY events.stream_ordering
  1860. LIMIT 100
  1861. """,
  1862. (room_id,),
  1863. )
  1864. return [row[0] for row in txn]