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.
 
 
 
 
 
 

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