events_worker.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from __future__ import division
  16. import itertools
  17. import logging
  18. from collections import namedtuple
  19. from canonicaljson import json
  20. from twisted.internet import defer
  21. from synapse.api.constants import EventTypes
  22. from synapse.api.errors import NotFoundError
  23. from synapse.api.room_versions import EventFormatVersions
  24. from synapse.events import FrozenEvent, event_type_from_format_version # noqa: F401
  25. from synapse.events.snapshot import EventContext # noqa: F401
  26. from synapse.events.utils import prune_event
  27. from synapse.logging.context import LoggingContext, PreserveLoggingContext
  28. from synapse.metrics.background_process_metrics import run_as_background_process
  29. from synapse.types import get_domain_from_id
  30. from synapse.util import batch_iter
  31. from synapse.util.metrics import Measure
  32. from ._base import SQLBaseStore
  33. logger = logging.getLogger(__name__)
  34. # These values are used in the `enqueus_event` and `_do_fetch` methods to
  35. # control how we batch/bulk fetch events from the database.
  36. # The values are plucked out of thing air to make initial sync run faster
  37. # on jki.re
  38. # TODO: Make these configurable.
  39. EVENT_QUEUE_THREADS = 3 # Max number of threads that will fetch events
  40. EVENT_QUEUE_ITERATIONS = 3 # No. times we block waiting for requests for events
  41. EVENT_QUEUE_TIMEOUT_S = 0.1 # Timeout when waiting for requests for events
  42. _EventCacheEntry = namedtuple("_EventCacheEntry", ("event", "redacted_event"))
  43. class EventsWorkerStore(SQLBaseStore):
  44. def get_received_ts(self, event_id):
  45. """Get received_ts (when it was persisted) for the event.
  46. Raises an exception for unknown events.
  47. Args:
  48. event_id (str)
  49. Returns:
  50. Deferred[int|None]: Timestamp in milliseconds, or None for events
  51. that were persisted before received_ts was implemented.
  52. """
  53. return self._simple_select_one_onecol(
  54. table="events",
  55. keyvalues={"event_id": event_id},
  56. retcol="received_ts",
  57. desc="get_received_ts",
  58. )
  59. def get_received_ts_by_stream_pos(self, stream_ordering):
  60. """Given a stream ordering get an approximate timestamp of when it
  61. happened.
  62. This is done by simply taking the received ts of the first event that
  63. has a stream ordering greater than or equal to the given stream pos.
  64. If none exists returns the current time, on the assumption that it must
  65. have happened recently.
  66. Args:
  67. stream_ordering (int)
  68. Returns:
  69. Deferred[int]
  70. """
  71. def _get_approximate_received_ts_txn(txn):
  72. sql = """
  73. SELECT received_ts FROM events
  74. WHERE stream_ordering >= ?
  75. LIMIT 1
  76. """
  77. txn.execute(sql, (stream_ordering,))
  78. row = txn.fetchone()
  79. if row and row[0]:
  80. ts = row[0]
  81. else:
  82. ts = self.clock.time_msec()
  83. return ts
  84. return self.runInteraction(
  85. "get_approximate_received_ts", _get_approximate_received_ts_txn
  86. )
  87. @defer.inlineCallbacks
  88. def get_event(
  89. self,
  90. event_id,
  91. check_redacted=True,
  92. get_prev_content=False,
  93. allow_rejected=False,
  94. allow_none=False,
  95. check_room_id=None,
  96. ):
  97. """Get an event from the database by event_id.
  98. Args:
  99. event_id (str): The event_id of the event to fetch
  100. check_redacted (bool): If True, check if event has been redacted
  101. and redact it.
  102. get_prev_content (bool): If True and event is a state event,
  103. include the previous states content in the unsigned field.
  104. allow_rejected (bool): If True return rejected events.
  105. allow_none (bool): If True, return None if no event found, if
  106. False throw a NotFoundError
  107. check_room_id (str|None): if not None, check the room of the found event.
  108. If there is a mismatch, behave as per allow_none.
  109. Returns:
  110. Deferred[EventBase|None]
  111. """
  112. if not isinstance(event_id, str):
  113. raise TypeError("Invalid event event_id %r" % (event_id,))
  114. events = yield self.get_events_as_list(
  115. [event_id],
  116. check_redacted=check_redacted,
  117. get_prev_content=get_prev_content,
  118. allow_rejected=allow_rejected,
  119. )
  120. event = events[0] if events else None
  121. if event is not None and check_room_id is not None:
  122. if event.room_id != check_room_id:
  123. event = None
  124. if event is None and not allow_none:
  125. raise NotFoundError("Could not find event %s" % (event_id,))
  126. return event
  127. @defer.inlineCallbacks
  128. def get_events(
  129. self,
  130. event_ids,
  131. check_redacted=True,
  132. get_prev_content=False,
  133. allow_rejected=False,
  134. ):
  135. """Get events from the database
  136. Args:
  137. event_ids (list): The event_ids of the events to fetch
  138. check_redacted (bool): If True, check if event has been redacted
  139. and redact it.
  140. get_prev_content (bool): If True and event is a state event,
  141. include the previous states content in the unsigned field.
  142. allow_rejected (bool): If True return rejected events.
  143. Returns:
  144. Deferred : Dict from event_id to event.
  145. """
  146. events = yield self.get_events_as_list(
  147. event_ids,
  148. check_redacted=check_redacted,
  149. get_prev_content=get_prev_content,
  150. allow_rejected=allow_rejected,
  151. )
  152. return {e.event_id: e for e in events}
  153. @defer.inlineCallbacks
  154. def get_events_as_list(
  155. self,
  156. event_ids,
  157. check_redacted=True,
  158. get_prev_content=False,
  159. allow_rejected=False,
  160. ):
  161. """Get events from the database and return in a list in the same order
  162. as given by `event_ids` arg.
  163. Args:
  164. event_ids (list): The event_ids of the events to fetch
  165. check_redacted (bool): If True, check if event has been redacted
  166. and redact it.
  167. get_prev_content (bool): If True and event is a state event,
  168. include the previous states content in the unsigned field.
  169. allow_rejected (bool): If True return rejected events.
  170. Returns:
  171. Deferred[list[EventBase]]: List of events fetched from the database. The
  172. events are in the same order as `event_ids` arg.
  173. Note that the returned list may be smaller than the list of event
  174. IDs if not all events could be fetched.
  175. """
  176. if not event_ids:
  177. return []
  178. # there may be duplicates so we cast the list to a set
  179. event_entry_map = yield self._get_events_from_cache_or_db(
  180. set(event_ids), allow_rejected=allow_rejected
  181. )
  182. events = []
  183. for event_id in event_ids:
  184. entry = event_entry_map.get(event_id, None)
  185. if not entry:
  186. continue
  187. if not allow_rejected:
  188. assert not entry.event.rejected_reason, (
  189. "rejected event returned from _get_events_from_cache_or_db despite "
  190. "allow_rejected=False"
  191. )
  192. # We may not have had the original event when we received a redaction, so
  193. # we have to recheck auth now.
  194. if not allow_rejected and entry.event.type == EventTypes.Redaction:
  195. redacted_event_id = entry.event.redacts
  196. event_map = yield self._get_events_from_cache_or_db([redacted_event_id])
  197. original_event_entry = event_map.get(redacted_event_id)
  198. if not original_event_entry:
  199. # we don't have the redacted event (or it was rejected).
  200. #
  201. # We assume that the redaction isn't authorized for now; if the
  202. # redacted event later turns up, the redaction will be re-checked,
  203. # and if it is found valid, the original will get redacted before it
  204. # is served to the client.
  205. logger.debug(
  206. "Withholding redaction event %s since we don't (yet) have the "
  207. "original %s",
  208. event_id,
  209. redacted_event_id,
  210. )
  211. continue
  212. original_event = original_event_entry.event
  213. if original_event.type == EventTypes.Create:
  214. # we never serve redactions of Creates to clients.
  215. logger.info(
  216. "Withholding redaction %s of create event %s",
  217. event_id,
  218. redacted_event_id,
  219. )
  220. continue
  221. if original_event.room_id != entry.event.room_id:
  222. logger.info(
  223. "Withholding redaction %s of event %s from a different room",
  224. event_id,
  225. redacted_event_id,
  226. )
  227. continue
  228. if entry.event.internal_metadata.need_to_check_redaction():
  229. original_domain = get_domain_from_id(original_event.sender)
  230. redaction_domain = get_domain_from_id(entry.event.sender)
  231. if original_domain != redaction_domain:
  232. # the senders don't match, so this is forbidden
  233. logger.info(
  234. "Withholding redaction %s whose sender domain %s doesn't "
  235. "match that of redacted event %s %s",
  236. event_id,
  237. redaction_domain,
  238. redacted_event_id,
  239. original_domain,
  240. )
  241. continue
  242. # Update the cache to save doing the checks again.
  243. entry.event.internal_metadata.recheck_redaction = False
  244. if check_redacted and entry.redacted_event:
  245. event = entry.redacted_event
  246. else:
  247. event = entry.event
  248. events.append(event)
  249. if get_prev_content:
  250. if "replaces_state" in event.unsigned:
  251. prev = yield self.get_event(
  252. event.unsigned["replaces_state"],
  253. get_prev_content=False,
  254. allow_none=True,
  255. )
  256. if prev:
  257. event.unsigned = dict(event.unsigned)
  258. event.unsigned["prev_content"] = prev.content
  259. event.unsigned["prev_sender"] = prev.sender
  260. return events
  261. @defer.inlineCallbacks
  262. def _get_events_from_cache_or_db(self, event_ids, allow_rejected=False):
  263. """Fetch a bunch of events from the cache or the database.
  264. If events are pulled from the database, they will be cached for future lookups.
  265. Args:
  266. event_ids (Iterable[str]): The event_ids of the events to fetch
  267. allow_rejected (bool): Whether to include rejected events
  268. Returns:
  269. Deferred[Dict[str, _EventCacheEntry]]:
  270. map from event id to result
  271. """
  272. event_entry_map = self._get_events_from_cache(
  273. event_ids, allow_rejected=allow_rejected
  274. )
  275. missing_events_ids = [e for e in event_ids if e not in event_entry_map]
  276. if missing_events_ids:
  277. log_ctx = LoggingContext.current_context()
  278. log_ctx.record_event_fetch(len(missing_events_ids))
  279. # Note that _get_events_from_db is also responsible for turning db rows
  280. # into FrozenEvents (via _get_event_from_row), which involves seeing if
  281. # the events have been redacted, and if so pulling the redaction event out
  282. # of the database to check it.
  283. #
  284. missing_events = yield self._get_events_from_db(
  285. missing_events_ids, allow_rejected=allow_rejected
  286. )
  287. event_entry_map.update(missing_events)
  288. return event_entry_map
  289. def _invalidate_get_event_cache(self, event_id):
  290. self._get_event_cache.invalidate((event_id,))
  291. def _get_events_from_cache(self, events, allow_rejected, update_metrics=True):
  292. """Fetch events from the caches
  293. Args:
  294. events (Iterable[str]): list of event_ids to fetch
  295. allow_rejected (bool): Whether to return events that were rejected
  296. update_metrics (bool): Whether to update the cache hit ratio metrics
  297. Returns:
  298. dict of event_id -> _EventCacheEntry for each event_id in cache. If
  299. allow_rejected is `False` then there will still be an entry but it
  300. will be `None`
  301. """
  302. event_map = {}
  303. for event_id in events:
  304. ret = self._get_event_cache.get(
  305. (event_id,), None, update_metrics=update_metrics
  306. )
  307. if not ret:
  308. continue
  309. if allow_rejected or not ret.event.rejected_reason:
  310. event_map[event_id] = ret
  311. else:
  312. event_map[event_id] = None
  313. return event_map
  314. def _do_fetch(self, conn):
  315. """Takes a database connection and waits for requests for events from
  316. the _event_fetch_list queue.
  317. """
  318. i = 0
  319. while True:
  320. with self._event_fetch_lock:
  321. event_list = self._event_fetch_list
  322. self._event_fetch_list = []
  323. if not event_list:
  324. single_threaded = self.database_engine.single_threaded
  325. if single_threaded or i > EVENT_QUEUE_ITERATIONS:
  326. self._event_fetch_ongoing -= 1
  327. return
  328. else:
  329. self._event_fetch_lock.wait(EVENT_QUEUE_TIMEOUT_S)
  330. i += 1
  331. continue
  332. i = 0
  333. self._fetch_event_list(conn, event_list)
  334. def _fetch_event_list(self, conn, event_list):
  335. """Handle a load of requests from the _event_fetch_list queue
  336. Args:
  337. conn (twisted.enterprise.adbapi.Connection): database connection
  338. event_list (list[Tuple[list[str], Deferred]]):
  339. The fetch requests. Each entry consists of a list of event
  340. ids to be fetched, and a deferred to be completed once the
  341. events have been fetched.
  342. The deferreds are callbacked with a dictionary mapping from event id
  343. to event row. Note that it may well contain additional events that
  344. were not part of this request.
  345. """
  346. with Measure(self._clock, "_fetch_event_list"):
  347. try:
  348. events_to_fetch = set(
  349. event_id for events, _ in event_list for event_id in events
  350. )
  351. row_dict = self._new_transaction(
  352. conn, "do_fetch", [], [], self._fetch_event_rows, events_to_fetch
  353. )
  354. # We only want to resolve deferreds from the main thread
  355. def fire():
  356. for _, d in event_list:
  357. d.callback(row_dict)
  358. with PreserveLoggingContext():
  359. self.hs.get_reactor().callFromThread(fire)
  360. except Exception as e:
  361. logger.exception("do_fetch")
  362. # We only want to resolve deferreds from the main thread
  363. def fire(evs, exc):
  364. for _, d in evs:
  365. if not d.called:
  366. with PreserveLoggingContext():
  367. d.errback(exc)
  368. with PreserveLoggingContext():
  369. self.hs.get_reactor().callFromThread(fire, event_list, e)
  370. @defer.inlineCallbacks
  371. def _get_events_from_db(self, event_ids, allow_rejected=False):
  372. """Fetch a bunch of events from the database.
  373. Returned events will be added to the cache for future lookups.
  374. Args:
  375. event_ids (Iterable[str]): The event_ids of the events to fetch
  376. allow_rejected (bool): Whether to include rejected events
  377. Returns:
  378. Deferred[Dict[str, _EventCacheEntry]]:
  379. map from event id to result. May return extra events which
  380. weren't asked for.
  381. """
  382. fetched_events = {}
  383. events_to_fetch = event_ids
  384. while events_to_fetch:
  385. row_map = yield self._enqueue_events(events_to_fetch)
  386. # we need to recursively fetch any redactions of those events
  387. redaction_ids = set()
  388. for event_id in events_to_fetch:
  389. row = row_map.get(event_id)
  390. fetched_events[event_id] = row
  391. if row:
  392. redaction_ids.update(row["redactions"])
  393. events_to_fetch = redaction_ids.difference(fetched_events.keys())
  394. if events_to_fetch:
  395. logger.debug("Also fetching redaction events %s", events_to_fetch)
  396. # build a map from event_id to EventBase
  397. event_map = {}
  398. for event_id, row in fetched_events.items():
  399. if not row:
  400. continue
  401. assert row["event_id"] == event_id
  402. rejected_reason = row["rejected_reason"]
  403. if not allow_rejected and rejected_reason:
  404. continue
  405. d = json.loads(row["json"])
  406. internal_metadata = json.loads(row["internal_metadata"])
  407. format_version = row["format_version"]
  408. if format_version is None:
  409. # This means that we stored the event before we had the concept
  410. # of a event format version, so it must be a V1 event.
  411. format_version = EventFormatVersions.V1
  412. original_ev = event_type_from_format_version(format_version)(
  413. event_dict=d,
  414. internal_metadata_dict=internal_metadata,
  415. rejected_reason=rejected_reason,
  416. )
  417. event_map[event_id] = original_ev
  418. # finally, we can decide whether each one nededs redacting, and build
  419. # the cache entries.
  420. result_map = {}
  421. for event_id, original_ev in event_map.items():
  422. redactions = fetched_events[event_id]["redactions"]
  423. redacted_event = self._maybe_redact_event_row(
  424. original_ev, redactions, event_map
  425. )
  426. cache_entry = _EventCacheEntry(
  427. event=original_ev, redacted_event=redacted_event
  428. )
  429. self._get_event_cache.prefill((event_id,), cache_entry)
  430. result_map[event_id] = cache_entry
  431. return result_map
  432. @defer.inlineCallbacks
  433. def _enqueue_events(self, events):
  434. """Fetches events from the database using the _event_fetch_list. This
  435. allows batch and bulk fetching of events - it allows us to fetch events
  436. without having to create a new transaction for each request for events.
  437. Args:
  438. events (Iterable[str]): events to be fetched.
  439. Returns:
  440. Deferred[Dict[str, Dict]]: map from event id to row data from the database.
  441. May contain events that weren't requested.
  442. """
  443. events_d = defer.Deferred()
  444. with self._event_fetch_lock:
  445. self._event_fetch_list.append((events, events_d))
  446. self._event_fetch_lock.notify()
  447. if self._event_fetch_ongoing < EVENT_QUEUE_THREADS:
  448. self._event_fetch_ongoing += 1
  449. should_start = True
  450. else:
  451. should_start = False
  452. if should_start:
  453. run_as_background_process(
  454. "fetch_events", self.runWithConnection, self._do_fetch
  455. )
  456. logger.debug("Loading %d events: %s", len(events), events)
  457. with PreserveLoggingContext():
  458. row_map = yield events_d
  459. logger.debug("Loaded %d events (%d rows)", len(events), len(row_map))
  460. return row_map
  461. def _fetch_event_rows(self, txn, event_ids):
  462. """Fetch event rows from the database
  463. Events which are not found are omitted from the result.
  464. The returned per-event dicts contain the following keys:
  465. * event_id (str)
  466. * json (str): json-encoded event structure
  467. * internal_metadata (str): json-encoded internal metadata dict
  468. * format_version (int|None): The format of the event. Hopefully one
  469. of EventFormatVersions. 'None' means the event predates
  470. EventFormatVersions (so the event is format V1).
  471. * rejected_reason (str|None): if the event was rejected, the reason
  472. why.
  473. * redactions (List[str]): a list of event-ids which (claim to) redact
  474. this event.
  475. Args:
  476. txn (twisted.enterprise.adbapi.Connection):
  477. event_ids (Iterable[str]): event IDs to fetch
  478. Returns:
  479. Dict[str, Dict]: a map from event id to event info.
  480. """
  481. event_dict = {}
  482. for evs in batch_iter(event_ids, 200):
  483. sql = (
  484. "SELECT "
  485. " e.event_id, "
  486. " e.internal_metadata,"
  487. " e.json,"
  488. " e.format_version, "
  489. " rej.reason "
  490. " FROM event_json as e"
  491. " LEFT JOIN rejections as rej USING (event_id)"
  492. " WHERE e.event_id IN (%s)"
  493. ) % (",".join(["?"] * len(evs)),)
  494. txn.execute(sql, evs)
  495. for row in txn:
  496. event_id = row[0]
  497. event_dict[event_id] = {
  498. "event_id": event_id,
  499. "internal_metadata": row[1],
  500. "json": row[2],
  501. "format_version": row[3],
  502. "rejected_reason": row[4],
  503. "redactions": [],
  504. }
  505. # check for redactions
  506. redactions_sql = (
  507. "SELECT event_id, redacts FROM redactions WHERE redacts IN (%s)"
  508. ) % (",".join(["?"] * len(evs)),)
  509. txn.execute(redactions_sql, evs)
  510. for (redacter, redacted) in txn:
  511. d = event_dict.get(redacted)
  512. if d:
  513. d["redactions"].append(redacter)
  514. return event_dict
  515. def _maybe_redact_event_row(self, original_ev, redactions, event_map):
  516. """Given an event object and a list of possible redacting event ids,
  517. determine whether to honour any of those redactions and if so return a redacted
  518. event.
  519. Args:
  520. original_ev (EventBase):
  521. redactions (iterable[str]): list of event ids of potential redaction events
  522. event_map (dict[str, EventBase]): other events which have been fetched, in
  523. which we can look up the redaaction events. Map from event id to event.
  524. Returns:
  525. Deferred[EventBase|None]: if the event should be redacted, a pruned
  526. event object. Otherwise, None.
  527. """
  528. if original_ev.type == "m.room.create":
  529. # we choose to ignore redactions of m.room.create events.
  530. return None
  531. for redaction_id in redactions:
  532. redaction_event = event_map.get(redaction_id)
  533. if not redaction_event or redaction_event.rejected_reason:
  534. # we don't have the redaction event, or the redaction event was not
  535. # authorized.
  536. logger.debug(
  537. "%s was redacted by %s but redaction not found/authed",
  538. original_ev.event_id,
  539. redaction_id,
  540. )
  541. continue
  542. if redaction_event.room_id != original_ev.room_id:
  543. logger.debug(
  544. "%s was redacted by %s but redaction was in a different room!",
  545. original_ev.event_id,
  546. redaction_id,
  547. )
  548. continue
  549. # Starting in room version v3, some redactions need to be
  550. # rechecked if we didn't have the redacted event at the
  551. # time, so we recheck on read instead.
  552. if redaction_event.internal_metadata.need_to_check_redaction():
  553. expected_domain = get_domain_from_id(original_ev.sender)
  554. if get_domain_from_id(redaction_event.sender) == expected_domain:
  555. # This redaction event is allowed. Mark as not needing a recheck.
  556. redaction_event.internal_metadata.recheck_redaction = False
  557. else:
  558. # Senders don't match, so the event isn't actually redacted
  559. logger.debug(
  560. "%s was redacted by %s but the senders don't match",
  561. original_ev.event_id,
  562. redaction_id,
  563. )
  564. continue
  565. logger.debug("Redacting %s due to %s", original_ev.event_id, redaction_id)
  566. # we found a good redaction event. Redact!
  567. redacted_event = prune_event(original_ev)
  568. redacted_event.unsigned["redacted_by"] = redaction_id
  569. # It's fine to add the event directly, since get_pdu_json
  570. # will serialise this field correctly
  571. redacted_event.unsigned["redacted_because"] = redaction_event
  572. return redacted_event
  573. # no valid redaction found for this event
  574. return None
  575. @defer.inlineCallbacks
  576. def have_events_in_timeline(self, event_ids):
  577. """Given a list of event ids, check if we have already processed and
  578. stored them as non outliers.
  579. """
  580. rows = yield self._simple_select_many_batch(
  581. table="events",
  582. retcols=("event_id",),
  583. column="event_id",
  584. iterable=list(event_ids),
  585. keyvalues={"outlier": False},
  586. desc="have_events_in_timeline",
  587. )
  588. return set(r["event_id"] for r in rows)
  589. @defer.inlineCallbacks
  590. def have_seen_events(self, event_ids):
  591. """Given a list of event ids, check if we have already processed them.
  592. Args:
  593. event_ids (iterable[str]):
  594. Returns:
  595. Deferred[set[str]]: The events we have already seen.
  596. """
  597. results = set()
  598. def have_seen_events_txn(txn, chunk):
  599. sql = "SELECT event_id FROM events as e WHERE e.event_id IN (%s)" % (
  600. ",".join("?" * len(chunk)),
  601. )
  602. txn.execute(sql, chunk)
  603. for (event_id,) in txn:
  604. results.add(event_id)
  605. # break the input up into chunks of 100
  606. input_iterator = iter(event_ids)
  607. for chunk in iter(lambda: list(itertools.islice(input_iterator, 100)), []):
  608. yield self.runInteraction("have_seen_events", have_seen_events_txn, chunk)
  609. return results
  610. def get_seen_events_with_rejections(self, event_ids):
  611. """Given a list of event ids, check if we rejected them.
  612. Args:
  613. event_ids (list[str])
  614. Returns:
  615. Deferred[dict[str, str|None):
  616. Has an entry for each event id we already have seen. Maps to
  617. the rejected reason string if we rejected the event, else maps
  618. to None.
  619. """
  620. if not event_ids:
  621. return defer.succeed({})
  622. def f(txn):
  623. sql = (
  624. "SELECT e.event_id, reason FROM events as e "
  625. "LEFT JOIN rejections as r ON e.event_id = r.event_id "
  626. "WHERE e.event_id = ?"
  627. )
  628. res = {}
  629. for event_id in event_ids:
  630. txn.execute(sql, (event_id,))
  631. row = txn.fetchone()
  632. if row:
  633. _, rejected = row
  634. res[event_id] = rejected
  635. return res
  636. return self.runInteraction("get_seen_events_with_rejections", f)
  637. def _get_total_state_event_counts_txn(self, txn, room_id):
  638. """
  639. See get_total_state_event_counts.
  640. """
  641. # We join against the events table as that has an index on room_id
  642. sql = """
  643. SELECT COUNT(*) FROM state_events
  644. INNER JOIN events USING (room_id, event_id)
  645. WHERE room_id=?
  646. """
  647. txn.execute(sql, (room_id,))
  648. row = txn.fetchone()
  649. return row[0] if row else 0
  650. def get_total_state_event_counts(self, room_id):
  651. """
  652. Gets the total number of state events in a room.
  653. Args:
  654. room_id (str)
  655. Returns:
  656. Deferred[int]
  657. """
  658. return self.runInteraction(
  659. "get_total_state_event_counts",
  660. self._get_total_state_event_counts_txn,
  661. room_id,
  662. )
  663. def _get_current_state_event_counts_txn(self, txn, room_id):
  664. """
  665. See get_current_state_event_counts.
  666. """
  667. sql = "SELECT COUNT(*) FROM current_state_events WHERE room_id=?"
  668. txn.execute(sql, (room_id,))
  669. row = txn.fetchone()
  670. return row[0] if row else 0
  671. def get_current_state_event_counts(self, room_id):
  672. """
  673. Gets the current number of state events in a room.
  674. Args:
  675. room_id (str)
  676. Returns:
  677. Deferred[int]
  678. """
  679. return self.runInteraction(
  680. "get_current_state_event_counts",
  681. self._get_current_state_event_counts_txn,
  682. room_id,
  683. )
  684. @defer.inlineCallbacks
  685. def get_room_complexity(self, room_id):
  686. """
  687. Get a rough approximation of the complexity of the room. This is used by
  688. remote servers to decide whether they wish to join the room or not.
  689. Higher complexity value indicates that being in the room will consume
  690. more resources.
  691. Args:
  692. room_id (str)
  693. Returns:
  694. Deferred[dict[str:int]] of complexity version to complexity.
  695. """
  696. state_events = yield self.get_current_state_event_counts(room_id)
  697. # Call this one "v1", so we can introduce new ones as we want to develop
  698. # it.
  699. complexity_v1 = round(state_events / 500, 2)
  700. return {"v1": complexity_v1}