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.
 
 
 
 
 
 

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