You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2451 lines
97 KiB

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