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.
 
 
 
 
 
 

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