events_worker.py 92 KB

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