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.
 
 
 
 
 
 

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