events_worker.py 33 KB

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