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.
 
 
 
 
 
 

1455 lines
54 KiB

  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, Tuple
  21. from constantly import NamedConstant, Names
  22. from twisted.internet import defer
  23. from synapse.api.constants import EventTypes
  24. from synapse.api.errors import NotFoundError, SynapseError
  25. from synapse.api.room_versions import (
  26. KNOWN_ROOM_VERSIONS,
  27. EventFormatVersions,
  28. RoomVersions,
  29. )
  30. from synapse.events import make_event_from_dict
  31. from synapse.events.utils import prune_event
  32. from synapse.logging.context import PreserveLoggingContext, current_context
  33. from synapse.metrics.background_process_metrics import run_as_background_process
  34. from synapse.replication.slave.storage._slaved_id_tracker import SlavedIdTracker
  35. from synapse.replication.tcp.streams import BackfillStream
  36. from synapse.replication.tcp.streams.events import EventsStream
  37. from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause
  38. from synapse.storage.database import DatabasePool
  39. from synapse.storage.types import Cursor
  40. from synapse.storage.util.id_generators import StreamIdGenerator
  41. from synapse.types import get_domain_from_id
  42. from synapse.util.caches.descriptors import (
  43. Cache,
  44. _CacheContext,
  45. cached,
  46. cachedInlineCallbacks,
  47. )
  48. from synapse.util.iterutils import batch_iter
  49. from synapse.util.metrics import Measure
  50. logger = logging.getLogger(__name__)
  51. # These values are used in the `enqueus_event` and `_do_fetch` methods to
  52. # control how we batch/bulk fetch events from the database.
  53. # The values are plucked out of thing air to make initial sync run faster
  54. # on jki.re
  55. # TODO: Make these configurable.
  56. EVENT_QUEUE_THREADS = 3 # Max number of threads that will fetch events
  57. EVENT_QUEUE_ITERATIONS = 3 # No. times we block waiting for requests for events
  58. EVENT_QUEUE_TIMEOUT_S = 0.1 # Timeout when waiting for requests for events
  59. _EventCacheEntry = namedtuple("_EventCacheEntry", ("event", "redacted_event"))
  60. class EventRedactBehaviour(Names):
  61. """
  62. What to do when retrieving a redacted event from the database.
  63. """
  64. AS_IS = NamedConstant()
  65. REDACT = NamedConstant()
  66. BLOCK = NamedConstant()
  67. class EventsWorkerStore(SQLBaseStore):
  68. def __init__(self, database: DatabasePool, db_conn, hs):
  69. super(EventsWorkerStore, self).__init__(database, db_conn, hs)
  70. if hs.config.worker.writers.events == hs.get_instance_name():
  71. # We are the process in charge of generating stream ids for events,
  72. # so instantiate ID generators based on the database
  73. self._stream_id_gen = StreamIdGenerator(
  74. db_conn, "events", "stream_ordering",
  75. )
  76. self._backfill_id_gen = StreamIdGenerator(
  77. db_conn,
  78. "events",
  79. "stream_ordering",
  80. step=-1,
  81. extra_tables=[("ex_outlier_stream", "event_stream_ordering")],
  82. )
  83. else:
  84. # Another process is in charge of persisting events and generating
  85. # stream IDs: rely on the replication streams to let us know which
  86. # IDs we can process.
  87. self._stream_id_gen = SlavedIdTracker(db_conn, "events", "stream_ordering")
  88. self._backfill_id_gen = SlavedIdTracker(
  89. db_conn, "events", "stream_ordering", step=-1
  90. )
  91. self._get_event_cache = Cache(
  92. "*getEvent*",
  93. keylen=3,
  94. max_entries=hs.config.caches.event_cache_size,
  95. apply_cache_factor_from_config=False,
  96. )
  97. self._event_fetch_lock = threading.Condition()
  98. self._event_fetch_list = []
  99. self._event_fetch_ongoing = 0
  100. def process_replication_rows(self, stream_name, instance_name, token, rows):
  101. if stream_name == EventsStream.NAME:
  102. self._stream_id_gen.advance(token)
  103. elif stream_name == BackfillStream.NAME:
  104. self._backfill_id_gen.advance(-token)
  105. super().process_replication_rows(stream_name, instance_name, token, rows)
  106. def get_received_ts(self, event_id):
  107. """Get received_ts (when it was persisted) for the event.
  108. Raises an exception for unknown events.
  109. Args:
  110. event_id (str)
  111. Returns:
  112. Deferred[int|None]: Timestamp in milliseconds, or None for events
  113. that were persisted before received_ts was implemented.
  114. """
  115. return self.db_pool.simple_select_one_onecol(
  116. table="events",
  117. keyvalues={"event_id": event_id},
  118. retcol="received_ts",
  119. desc="get_received_ts",
  120. )
  121. def get_received_ts_by_stream_pos(self, stream_ordering):
  122. """Given a stream ordering get an approximate timestamp of when it
  123. happened.
  124. This is done by simply taking the received ts of the first event that
  125. has a stream ordering greater than or equal to the given stream pos.
  126. If none exists returns the current time, on the assumption that it must
  127. have happened recently.
  128. Args:
  129. stream_ordering (int)
  130. Returns:
  131. Deferred[int]
  132. """
  133. def _get_approximate_received_ts_txn(txn):
  134. sql = """
  135. SELECT received_ts FROM events
  136. WHERE stream_ordering >= ?
  137. LIMIT 1
  138. """
  139. txn.execute(sql, (stream_ordering,))
  140. row = txn.fetchone()
  141. if row and row[0]:
  142. ts = row[0]
  143. else:
  144. ts = self.clock.time_msec()
  145. return ts
  146. return self.db_pool.runInteraction(
  147. "get_approximate_received_ts", _get_approximate_received_ts_txn
  148. )
  149. @defer.inlineCallbacks
  150. def get_event(
  151. self,
  152. event_id: str,
  153. redact_behaviour: EventRedactBehaviour = EventRedactBehaviour.REDACT,
  154. get_prev_content: bool = False,
  155. allow_rejected: bool = False,
  156. allow_none: bool = False,
  157. check_room_id: Optional[str] = None,
  158. ):
  159. """Get an event from the database by event_id.
  160. Args:
  161. event_id: The event_id of the event to fetch
  162. redact_behaviour: Determine what to do with a redacted event. Possible values:
  163. * AS_IS - Return the full event body with no redacted content
  164. * REDACT - Return the event but with a redacted body
  165. * DISALLOW - Do not return redacted events (behave as per allow_none
  166. if the event is redacted)
  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. behave as per allow_none.
  171. allow_none: If True, return None if no event found, if
  172. False throw a NotFoundError
  173. check_room_id: if not None, check the room of the found event.
  174. If there is a mismatch, behave as per allow_none.
  175. Returns:
  176. Deferred[EventBase|None]
  177. """
  178. if not isinstance(event_id, str):
  179. raise TypeError("Invalid event event_id %r" % (event_id,))
  180. events = yield self.get_events_as_list(
  181. [event_id],
  182. redact_behaviour=redact_behaviour,
  183. get_prev_content=get_prev_content,
  184. allow_rejected=allow_rejected,
  185. )
  186. event = events[0] if events else None
  187. if event is not None and check_room_id is not None:
  188. if event.room_id != check_room_id:
  189. event = None
  190. if event is None and not allow_none:
  191. raise NotFoundError("Could not find event %s" % (event_id,))
  192. return event
  193. @defer.inlineCallbacks
  194. def get_events(
  195. self,
  196. event_ids: List[str],
  197. redact_behaviour: EventRedactBehaviour = EventRedactBehaviour.REDACT,
  198. get_prev_content: bool = False,
  199. allow_rejected: bool = False,
  200. ):
  201. """Get events from the database
  202. Args:
  203. event_ids: The event_ids of the events to fetch
  204. redact_behaviour: Determine what to do with a redacted event. Possible
  205. values:
  206. * AS_IS - Return the full event body with no redacted content
  207. * REDACT - Return the event but with a redacted body
  208. * DISALLOW - Do not return redacted events (omit them from the response)
  209. get_prev_content: If True and event is a state event,
  210. include the previous states content in the unsigned field.
  211. allow_rejected: If True, return rejected events. Otherwise,
  212. omits rejeted events from the response.
  213. Returns:
  214. Deferred : Dict from event_id to event.
  215. """
  216. events = yield self.get_events_as_list(
  217. event_ids,
  218. redact_behaviour=redact_behaviour,
  219. get_prev_content=get_prev_content,
  220. allow_rejected=allow_rejected,
  221. )
  222. return {e.event_id: e for e in events}
  223. @defer.inlineCallbacks
  224. def get_events_as_list(
  225. self,
  226. event_ids: List[str],
  227. redact_behaviour: EventRedactBehaviour = EventRedactBehaviour.REDACT,
  228. get_prev_content: bool = False,
  229. allow_rejected: bool = False,
  230. ):
  231. """Get events from the database and return in a list in the same order
  232. as given by `event_ids` arg.
  233. Unknown events will be omitted from the response.
  234. Args:
  235. event_ids: The event_ids of the events to fetch
  236. redact_behaviour: Determine what to do with a redacted event. Possible values:
  237. * AS_IS - Return the full event body with no redacted content
  238. * REDACT - Return the event but with a redacted body
  239. * DISALLOW - Do not return redacted events (omit them from the response)
  240. get_prev_content: If True and event is a state event,
  241. include the previous states content in the unsigned field.
  242. allow_rejected: If True, return rejected events. Otherwise,
  243. omits rejected events from the response.
  244. Returns:
  245. Deferred[list[EventBase]]: List of events fetched from the database. The
  246. events are in the same order as `event_ids` arg.
  247. Note that the returned list may be smaller than the list of event
  248. IDs if not all events could be fetched.
  249. """
  250. if not event_ids:
  251. return []
  252. # there may be duplicates so we cast the list to a set
  253. event_entry_map = yield self._get_events_from_cache_or_db(
  254. set(event_ids), allow_rejected=allow_rejected
  255. )
  256. events = []
  257. for event_id in event_ids:
  258. entry = event_entry_map.get(event_id, None)
  259. if not entry:
  260. continue
  261. if not allow_rejected:
  262. assert not entry.event.rejected_reason, (
  263. "rejected event returned from _get_events_from_cache_or_db despite "
  264. "allow_rejected=False"
  265. )
  266. # We may not have had the original event when we received a redaction, so
  267. # we have to recheck auth now.
  268. if not allow_rejected and entry.event.type == EventTypes.Redaction:
  269. if entry.event.redacts is None:
  270. # A redacted redaction doesn't have a `redacts` key, in
  271. # which case lets just withhold the event.
  272. #
  273. # Note: Most of the time if the redactions has been
  274. # redacted we still have the un-redacted event in the DB
  275. # and so we'll still see the `redacts` key. However, this
  276. # isn't always true e.g. if we have censored the event.
  277. logger.debug(
  278. "Withholding redaction event %s as we don't have redacts key",
  279. event_id,
  280. )
  281. continue
  282. redacted_event_id = entry.event.redacts
  283. event_map = yield self._get_events_from_cache_or_db([redacted_event_id])
  284. original_event_entry = event_map.get(redacted_event_id)
  285. if not original_event_entry:
  286. # we don't have the redacted event (or it was rejected).
  287. #
  288. # We assume that the redaction isn't authorized for now; if the
  289. # redacted event later turns up, the redaction will be re-checked,
  290. # and if it is found valid, the original will get redacted before it
  291. # is served to the client.
  292. logger.debug(
  293. "Withholding redaction event %s since we don't (yet) have the "
  294. "original %s",
  295. event_id,
  296. redacted_event_id,
  297. )
  298. continue
  299. original_event = original_event_entry.event
  300. if original_event.type == EventTypes.Create:
  301. # we never serve redactions of Creates to clients.
  302. logger.info(
  303. "Withholding redaction %s of create event %s",
  304. event_id,
  305. redacted_event_id,
  306. )
  307. continue
  308. if original_event.room_id != entry.event.room_id:
  309. logger.info(
  310. "Withholding redaction %s of event %s from a different room",
  311. event_id,
  312. redacted_event_id,
  313. )
  314. continue
  315. if entry.event.internal_metadata.need_to_check_redaction():
  316. original_domain = get_domain_from_id(original_event.sender)
  317. redaction_domain = get_domain_from_id(entry.event.sender)
  318. if original_domain != redaction_domain:
  319. # the senders don't match, so this is forbidden
  320. logger.info(
  321. "Withholding redaction %s whose sender domain %s doesn't "
  322. "match that of redacted event %s %s",
  323. event_id,
  324. redaction_domain,
  325. redacted_event_id,
  326. original_domain,
  327. )
  328. continue
  329. # Update the cache to save doing the checks again.
  330. entry.event.internal_metadata.recheck_redaction = False
  331. event = entry.event
  332. if entry.redacted_event:
  333. if redact_behaviour == EventRedactBehaviour.BLOCK:
  334. # Skip this event
  335. continue
  336. elif redact_behaviour == EventRedactBehaviour.REDACT:
  337. event = entry.redacted_event
  338. events.append(event)
  339. if get_prev_content:
  340. if "replaces_state" in event.unsigned:
  341. prev = yield self.get_event(
  342. event.unsigned["replaces_state"],
  343. get_prev_content=False,
  344. allow_none=True,
  345. )
  346. if prev:
  347. event.unsigned = dict(event.unsigned)
  348. event.unsigned["prev_content"] = prev.content
  349. event.unsigned["prev_sender"] = prev.sender
  350. return events
  351. @defer.inlineCallbacks
  352. def _get_events_from_cache_or_db(self, event_ids, allow_rejected=False):
  353. """Fetch a bunch of events from the cache or the database.
  354. If events are pulled from the database, they will be cached for future lookups.
  355. Unknown events are omitted from the response.
  356. Args:
  357. event_ids (Iterable[str]): The event_ids of the events to fetch
  358. allow_rejected (bool): Whether to include rejected events. If False,
  359. rejected events are omitted from the response.
  360. Returns:
  361. Deferred[Dict[str, _EventCacheEntry]]:
  362. map from event id to result
  363. """
  364. event_entry_map = self._get_events_from_cache(
  365. event_ids, allow_rejected=allow_rejected
  366. )
  367. missing_events_ids = [e for e in event_ids if e not in event_entry_map]
  368. if missing_events_ids:
  369. log_ctx = current_context()
  370. log_ctx.record_event_fetch(len(missing_events_ids))
  371. # Note that _get_events_from_db is also responsible for turning db rows
  372. # into FrozenEvents (via _get_event_from_row), which involves seeing if
  373. # the events have been redacted, and if so pulling the redaction event out
  374. # of the database to check it.
  375. #
  376. missing_events = yield self._get_events_from_db(
  377. missing_events_ids, allow_rejected=allow_rejected
  378. )
  379. event_entry_map.update(missing_events)
  380. return event_entry_map
  381. def _invalidate_get_event_cache(self, event_id):
  382. self._get_event_cache.invalidate((event_id,))
  383. def _get_events_from_cache(self, events, allow_rejected, update_metrics=True):
  384. """Fetch events from the caches
  385. Args:
  386. events (Iterable[str]): list of event_ids to fetch
  387. allow_rejected (bool): Whether to return events that were rejected
  388. update_metrics (bool): Whether to update the cache hit ratio metrics
  389. Returns:
  390. dict of event_id -> _EventCacheEntry for each event_id in cache. If
  391. allow_rejected is `False` then there will still be an entry but it
  392. will be `None`
  393. """
  394. event_map = {}
  395. for event_id in events:
  396. ret = self._get_event_cache.get(
  397. (event_id,), None, update_metrics=update_metrics
  398. )
  399. if not ret:
  400. continue
  401. if allow_rejected or not ret.event.rejected_reason:
  402. event_map[event_id] = ret
  403. else:
  404. event_map[event_id] = None
  405. return event_map
  406. def _do_fetch(self, conn):
  407. """Takes a database connection and waits for requests for events from
  408. the _event_fetch_list queue.
  409. """
  410. i = 0
  411. while True:
  412. with self._event_fetch_lock:
  413. event_list = self._event_fetch_list
  414. self._event_fetch_list = []
  415. if not event_list:
  416. single_threaded = self.database_engine.single_threaded
  417. if single_threaded or i > EVENT_QUEUE_ITERATIONS:
  418. self._event_fetch_ongoing -= 1
  419. return
  420. else:
  421. self._event_fetch_lock.wait(EVENT_QUEUE_TIMEOUT_S)
  422. i += 1
  423. continue
  424. i = 0
  425. self._fetch_event_list(conn, event_list)
  426. def _fetch_event_list(self, conn, event_list):
  427. """Handle a load of requests from the _event_fetch_list queue
  428. Args:
  429. conn (twisted.enterprise.adbapi.Connection): database connection
  430. event_list (list[Tuple[list[str], Deferred]]):
  431. The fetch requests. Each entry consists of a list of event
  432. ids to be fetched, and a deferred to be completed once the
  433. events have been fetched.
  434. The deferreds are callbacked with a dictionary mapping from event id
  435. to event row. Note that it may well contain additional events that
  436. were not part of this request.
  437. """
  438. with Measure(self._clock, "_fetch_event_list"):
  439. try:
  440. events_to_fetch = {
  441. event_id for events, _ in event_list for event_id in events
  442. }
  443. row_dict = self.db_pool.new_transaction(
  444. conn, "do_fetch", [], [], self._fetch_event_rows, events_to_fetch
  445. )
  446. # We only want to resolve deferreds from the main thread
  447. def fire():
  448. for _, d in event_list:
  449. d.callback(row_dict)
  450. with PreserveLoggingContext():
  451. self.hs.get_reactor().callFromThread(fire)
  452. except Exception as e:
  453. logger.exception("do_fetch")
  454. # We only want to resolve deferreds from the main thread
  455. def fire(evs, exc):
  456. for _, d in evs:
  457. if not d.called:
  458. with PreserveLoggingContext():
  459. d.errback(exc)
  460. with PreserveLoggingContext():
  461. self.hs.get_reactor().callFromThread(fire, event_list, e)
  462. @defer.inlineCallbacks
  463. def _get_events_from_db(self, event_ids, allow_rejected=False):
  464. """Fetch a bunch of events from the database.
  465. Returned events will be added to the cache for future lookups.
  466. Unknown events are omitted from the response.
  467. Args:
  468. event_ids (Iterable[str]): The event_ids of the events to fetch
  469. allow_rejected (bool): Whether to include rejected events. If False,
  470. rejected events are omitted from the response.
  471. Returns:
  472. Deferred[Dict[str, _EventCacheEntry]]:
  473. map from event id to result. May return extra events which
  474. weren't asked for.
  475. """
  476. fetched_events = {}
  477. events_to_fetch = event_ids
  478. while events_to_fetch:
  479. row_map = yield self._enqueue_events(events_to_fetch)
  480. # we need to recursively fetch any redactions of those events
  481. redaction_ids = set()
  482. for event_id in events_to_fetch:
  483. row = row_map.get(event_id)
  484. fetched_events[event_id] = row
  485. if row:
  486. redaction_ids.update(row["redactions"])
  487. events_to_fetch = redaction_ids.difference(fetched_events.keys())
  488. if events_to_fetch:
  489. logger.debug("Also fetching redaction events %s", events_to_fetch)
  490. # build a map from event_id to EventBase
  491. event_map = {}
  492. for event_id, row in fetched_events.items():
  493. if not row:
  494. continue
  495. assert row["event_id"] == event_id
  496. rejected_reason = row["rejected_reason"]
  497. if not allow_rejected and rejected_reason:
  498. continue
  499. d = db_to_json(row["json"])
  500. internal_metadata = db_to_json(row["internal_metadata"])
  501. format_version = row["format_version"]
  502. if format_version is None:
  503. # This means that we stored the event before we had the concept
  504. # of a event format version, so it must be a V1 event.
  505. format_version = EventFormatVersions.V1
  506. room_version_id = row["room_version_id"]
  507. if not room_version_id:
  508. # this should only happen for out-of-band membership events
  509. if not internal_metadata.get("out_of_band_membership"):
  510. logger.warning(
  511. "Room %s for event %s is unknown", d["room_id"], event_id
  512. )
  513. continue
  514. # take a wild stab at the room version based on the event format
  515. if format_version == EventFormatVersions.V1:
  516. room_version = RoomVersions.V1
  517. elif format_version == EventFormatVersions.V2:
  518. room_version = RoomVersions.V3
  519. else:
  520. room_version = RoomVersions.V5
  521. else:
  522. room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
  523. if not room_version:
  524. logger.warning(
  525. "Event %s in room %s has unknown room version %s",
  526. event_id,
  527. d["room_id"],
  528. room_version_id,
  529. )
  530. continue
  531. if room_version.event_format != format_version:
  532. logger.error(
  533. "Event %s in room %s with version %s has wrong format: "
  534. "expected %s, was %s",
  535. event_id,
  536. d["room_id"],
  537. room_version_id,
  538. room_version.event_format,
  539. format_version,
  540. )
  541. continue
  542. original_ev = make_event_from_dict(
  543. event_dict=d,
  544. room_version=room_version,
  545. internal_metadata_dict=internal_metadata,
  546. rejected_reason=rejected_reason,
  547. )
  548. event_map[event_id] = original_ev
  549. # finally, we can decide whether each one needs redacting, and build
  550. # the cache entries.
  551. result_map = {}
  552. for event_id, original_ev in event_map.items():
  553. redactions = fetched_events[event_id]["redactions"]
  554. redacted_event = self._maybe_redact_event_row(
  555. original_ev, redactions, event_map
  556. )
  557. cache_entry = _EventCacheEntry(
  558. event=original_ev, redacted_event=redacted_event
  559. )
  560. self._get_event_cache.prefill((event_id,), cache_entry)
  561. result_map[event_id] = cache_entry
  562. return result_map
  563. @defer.inlineCallbacks
  564. def _enqueue_events(self, events):
  565. """Fetches events from the database using the _event_fetch_list. This
  566. allows batch and bulk fetching of events - it allows us to fetch events
  567. without having to create a new transaction for each request for events.
  568. Args:
  569. events (Iterable[str]): events to be fetched.
  570. Returns:
  571. Deferred[Dict[str, Dict]]: map from event id to row data from the database.
  572. May contain events that weren't requested.
  573. """
  574. events_d = defer.Deferred()
  575. with self._event_fetch_lock:
  576. self._event_fetch_list.append((events, events_d))
  577. self._event_fetch_lock.notify()
  578. if self._event_fetch_ongoing < EVENT_QUEUE_THREADS:
  579. self._event_fetch_ongoing += 1
  580. should_start = True
  581. else:
  582. should_start = False
  583. if should_start:
  584. run_as_background_process(
  585. "fetch_events", self.db_pool.runWithConnection, self._do_fetch
  586. )
  587. logger.debug("Loading %d events: %s", len(events), events)
  588. with PreserveLoggingContext():
  589. row_map = yield events_d
  590. logger.debug("Loaded %d events (%d rows)", len(events), len(row_map))
  591. return row_map
  592. def _fetch_event_rows(self, txn, event_ids):
  593. """Fetch event rows from the database
  594. Events which are not found are omitted from the result.
  595. The returned per-event dicts contain the following keys:
  596. * event_id (str)
  597. * json (str): json-encoded event structure
  598. * internal_metadata (str): json-encoded internal metadata dict
  599. * format_version (int|None): The format of the event. Hopefully one
  600. of EventFormatVersions. 'None' means the event predates
  601. EventFormatVersions (so the event is format V1).
  602. * room_version_id (str|None): The version of the room which contains the event.
  603. Hopefully one of RoomVersions.
  604. Due to historical reasons, there may be a few events in the database which
  605. do not have an associated room; in this case None will be returned here.
  606. * rejected_reason (str|None): if the event was rejected, the reason
  607. why.
  608. * redactions (List[str]): a list of event-ids which (claim to) redact
  609. this event.
  610. Args:
  611. txn (twisted.enterprise.adbapi.Connection):
  612. event_ids (Iterable[str]): event IDs to fetch
  613. Returns:
  614. Dict[str, Dict]: a map from event id to event info.
  615. """
  616. event_dict = {}
  617. for evs in batch_iter(event_ids, 200):
  618. sql = """\
  619. SELECT
  620. e.event_id,
  621. e.internal_metadata,
  622. e.json,
  623. e.format_version,
  624. r.room_version,
  625. rej.reason
  626. FROM event_json as e
  627. LEFT JOIN rooms r USING (room_id)
  628. LEFT JOIN rejections as rej USING (event_id)
  629. WHERE """
  630. clause, args = make_in_list_sql_clause(
  631. txn.database_engine, "e.event_id", evs
  632. )
  633. txn.execute(sql + clause, args)
  634. for row in txn:
  635. event_id = row[0]
  636. event_dict[event_id] = {
  637. "event_id": event_id,
  638. "internal_metadata": row[1],
  639. "json": row[2],
  640. "format_version": row[3],
  641. "room_version_id": row[4],
  642. "rejected_reason": row[5],
  643. "redactions": [],
  644. }
  645. # check for redactions
  646. redactions_sql = "SELECT event_id, redacts FROM redactions WHERE "
  647. clause, args = make_in_list_sql_clause(txn.database_engine, "redacts", evs)
  648. txn.execute(redactions_sql + clause, args)
  649. for (redacter, redacted) in txn:
  650. d = event_dict.get(redacted)
  651. if d:
  652. d["redactions"].append(redacter)
  653. return event_dict
  654. def _maybe_redact_event_row(self, original_ev, redactions, event_map):
  655. """Given an event object and a list of possible redacting event ids,
  656. determine whether to honour any of those redactions and if so return a redacted
  657. event.
  658. Args:
  659. original_ev (EventBase):
  660. redactions (iterable[str]): list of event ids of potential redaction events
  661. event_map (dict[str, EventBase]): other events which have been fetched, in
  662. which we can look up the redaaction events. Map from event id to event.
  663. Returns:
  664. Deferred[EventBase|None]: if the event should be redacted, a pruned
  665. event object. Otherwise, None.
  666. """
  667. if original_ev.type == "m.room.create":
  668. # we choose to ignore redactions of m.room.create events.
  669. return None
  670. for redaction_id in redactions:
  671. redaction_event = event_map.get(redaction_id)
  672. if not redaction_event or redaction_event.rejected_reason:
  673. # we don't have the redaction event, or the redaction event was not
  674. # authorized.
  675. logger.debug(
  676. "%s was redacted by %s but redaction not found/authed",
  677. original_ev.event_id,
  678. redaction_id,
  679. )
  680. continue
  681. if redaction_event.room_id != original_ev.room_id:
  682. logger.debug(
  683. "%s was redacted by %s but redaction was in a different room!",
  684. original_ev.event_id,
  685. redaction_id,
  686. )
  687. continue
  688. # Starting in room version v3, some redactions need to be
  689. # rechecked if we didn't have the redacted event at the
  690. # time, so we recheck on read instead.
  691. if redaction_event.internal_metadata.need_to_check_redaction():
  692. expected_domain = get_domain_from_id(original_ev.sender)
  693. if get_domain_from_id(redaction_event.sender) == expected_domain:
  694. # This redaction event is allowed. Mark as not needing a recheck.
  695. redaction_event.internal_metadata.recheck_redaction = False
  696. else:
  697. # Senders don't match, so the event isn't actually redacted
  698. logger.debug(
  699. "%s was redacted by %s but the senders don't match",
  700. original_ev.event_id,
  701. redaction_id,
  702. )
  703. continue
  704. logger.debug("Redacting %s due to %s", original_ev.event_id, redaction_id)
  705. # we found a good redaction event. Redact!
  706. redacted_event = prune_event(original_ev)
  707. redacted_event.unsigned["redacted_by"] = redaction_id
  708. # It's fine to add the event directly, since get_pdu_json
  709. # will serialise this field correctly
  710. redacted_event.unsigned["redacted_because"] = redaction_event
  711. return redacted_event
  712. # no valid redaction found for this event
  713. return None
  714. @defer.inlineCallbacks
  715. def have_events_in_timeline(self, event_ids):
  716. """Given a list of event ids, check if we have already processed and
  717. stored them as non outliers.
  718. """
  719. rows = yield self.db_pool.simple_select_many_batch(
  720. table="events",
  721. retcols=("event_id",),
  722. column="event_id",
  723. iterable=list(event_ids),
  724. keyvalues={"outlier": False},
  725. desc="have_events_in_timeline",
  726. )
  727. return {r["event_id"] for r in rows}
  728. @defer.inlineCallbacks
  729. def have_seen_events(self, event_ids):
  730. """Given a list of event ids, check if we have already processed them.
  731. Args:
  732. event_ids (iterable[str]):
  733. Returns:
  734. Deferred[set[str]]: The events we have already seen.
  735. """
  736. results = set()
  737. def have_seen_events_txn(txn, chunk):
  738. sql = "SELECT event_id FROM events as e WHERE "
  739. clause, args = make_in_list_sql_clause(
  740. txn.database_engine, "e.event_id", chunk
  741. )
  742. txn.execute(sql + clause, args)
  743. for (event_id,) in txn:
  744. results.add(event_id)
  745. # break the input up into chunks of 100
  746. input_iterator = iter(event_ids)
  747. for chunk in iter(lambda: list(itertools.islice(input_iterator, 100)), []):
  748. yield self.db_pool.runInteraction(
  749. "have_seen_events", have_seen_events_txn, chunk
  750. )
  751. return results
  752. def _get_total_state_event_counts_txn(self, txn, room_id):
  753. """
  754. See get_total_state_event_counts.
  755. """
  756. # We join against the events table as that has an index on room_id
  757. sql = """
  758. SELECT COUNT(*) FROM state_events
  759. INNER JOIN events USING (room_id, event_id)
  760. WHERE room_id=?
  761. """
  762. txn.execute(sql, (room_id,))
  763. row = txn.fetchone()
  764. return row[0] if row else 0
  765. def get_total_state_event_counts(self, room_id):
  766. """
  767. Gets the total number of state events in a room.
  768. Args:
  769. room_id (str)
  770. Returns:
  771. Deferred[int]
  772. """
  773. return self.db_pool.runInteraction(
  774. "get_total_state_event_counts",
  775. self._get_total_state_event_counts_txn,
  776. room_id,
  777. )
  778. def _get_current_state_event_counts_txn(self, txn, room_id):
  779. """
  780. See get_current_state_event_counts.
  781. """
  782. sql = "SELECT COUNT(*) FROM current_state_events WHERE room_id=?"
  783. txn.execute(sql, (room_id,))
  784. row = txn.fetchone()
  785. return row[0] if row else 0
  786. def get_current_state_event_counts(self, room_id):
  787. """
  788. Gets the current number of state events in a room.
  789. Args:
  790. room_id (str)
  791. Returns:
  792. Deferred[int]
  793. """
  794. return self.db_pool.runInteraction(
  795. "get_current_state_event_counts",
  796. self._get_current_state_event_counts_txn,
  797. room_id,
  798. )
  799. @defer.inlineCallbacks
  800. def get_room_complexity(self, room_id):
  801. """
  802. Get a rough approximation of the complexity of the room. This is used by
  803. remote servers to decide whether they wish to join the room or not.
  804. Higher complexity value indicates that being in the room will consume
  805. more resources.
  806. Args:
  807. room_id (str)
  808. Returns:
  809. Deferred[dict[str:int]] of complexity version to complexity.
  810. """
  811. state_events = yield self.get_current_state_event_counts(room_id)
  812. # Call this one "v1", so we can introduce new ones as we want to develop
  813. # it.
  814. complexity_v1 = round(state_events / 500, 2)
  815. return {"v1": complexity_v1}
  816. def get_current_backfill_token(self):
  817. """The current minimum token that backfilled events have reached"""
  818. return -self._backfill_id_gen.get_current_token()
  819. def get_current_events_token(self):
  820. """The current maximum token that events have reached"""
  821. return self._stream_id_gen.get_current_token()
  822. def get_all_new_forward_event_rows(self, last_id, current_id, limit):
  823. """Returns new events, for the Events replication stream
  824. Args:
  825. last_id: the last stream_id from the previous batch.
  826. current_id: the maximum stream_id to return up to
  827. limit: the maximum number of rows to return
  828. Returns: Deferred[List[Tuple]]
  829. a list of events stream rows. Each tuple consists of a stream id as
  830. the first element, followed by fields suitable for casting into an
  831. EventsStreamRow.
  832. """
  833. def get_all_new_forward_event_rows(txn):
  834. sql = (
  835. "SELECT e.stream_ordering, e.event_id, e.room_id, e.type,"
  836. " state_key, redacts, relates_to_id"
  837. " FROM events AS e"
  838. " LEFT JOIN redactions USING (event_id)"
  839. " LEFT JOIN state_events USING (event_id)"
  840. " LEFT JOIN event_relations USING (event_id)"
  841. " WHERE ? < stream_ordering AND stream_ordering <= ?"
  842. " ORDER BY stream_ordering ASC"
  843. " LIMIT ?"
  844. )
  845. txn.execute(sql, (last_id, current_id, limit))
  846. return txn.fetchall()
  847. return self.db_pool.runInteraction(
  848. "get_all_new_forward_event_rows", get_all_new_forward_event_rows
  849. )
  850. def get_ex_outlier_stream_rows(self, last_id, current_id):
  851. """Returns de-outliered events, for the Events replication stream
  852. Args:
  853. last_id: the last stream_id from the previous batch.
  854. current_id: the maximum stream_id to return up to
  855. Returns: Deferred[List[Tuple]]
  856. a list of events stream rows. Each tuple consists of a stream id as
  857. the first element, followed by fields suitable for casting into an
  858. EventsStreamRow.
  859. """
  860. def get_ex_outlier_stream_rows_txn(txn):
  861. sql = (
  862. "SELECT event_stream_ordering, e.event_id, e.room_id, e.type,"
  863. " state_key, redacts, relates_to_id"
  864. " FROM events AS e"
  865. " INNER JOIN ex_outlier_stream USING (event_id)"
  866. " LEFT JOIN redactions USING (event_id)"
  867. " LEFT JOIN state_events USING (event_id)"
  868. " LEFT JOIN event_relations USING (event_id)"
  869. " WHERE ? < event_stream_ordering"
  870. " AND event_stream_ordering <= ?"
  871. " ORDER BY event_stream_ordering ASC"
  872. )
  873. txn.execute(sql, (last_id, current_id))
  874. return txn.fetchall()
  875. return self.db_pool.runInteraction(
  876. "get_ex_outlier_stream_rows", get_ex_outlier_stream_rows_txn
  877. )
  878. async def get_all_new_backfill_event_rows(
  879. self, instance_name: str, last_id: int, current_id: int, limit: int
  880. ) -> Tuple[List[Tuple[int, list]], int, bool]:
  881. """Get updates for backfill replication stream, including all new
  882. backfilled events and events that have gone from being outliers to not.
  883. Args:
  884. instance_name: The writer we want to fetch updates from. Unused
  885. here since there is only ever one writer.
  886. last_id: The token to fetch updates from. Exclusive.
  887. current_id: The token to fetch updates up to. Inclusive.
  888. limit: The requested limit for the number of rows to return. The
  889. function may return more or fewer rows.
  890. Returns:
  891. A tuple consisting of: the updates, a token to use to fetch
  892. subsequent updates, and whether we returned fewer rows than exists
  893. between the requested tokens due to the limit.
  894. The token returned can be used in a subsequent call to this
  895. function to get further updatees.
  896. The updates are a list of 2-tuples of stream ID and the row data
  897. """
  898. if last_id == current_id:
  899. return [], current_id, False
  900. def get_all_new_backfill_event_rows(txn):
  901. sql = (
  902. "SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,"
  903. " state_key, redacts, relates_to_id"
  904. " FROM events AS e"
  905. " LEFT JOIN redactions USING (event_id)"
  906. " LEFT JOIN state_events USING (event_id)"
  907. " LEFT JOIN event_relations USING (event_id)"
  908. " WHERE ? > stream_ordering AND stream_ordering >= ?"
  909. " ORDER BY stream_ordering ASC"
  910. " LIMIT ?"
  911. )
  912. txn.execute(sql, (-last_id, -current_id, limit))
  913. new_event_updates = [(row[0], row[1:]) for row in txn]
  914. limited = False
  915. if len(new_event_updates) == limit:
  916. upper_bound = new_event_updates[-1][0]
  917. limited = True
  918. else:
  919. upper_bound = current_id
  920. sql = (
  921. "SELECT -event_stream_ordering, e.event_id, e.room_id, e.type,"
  922. " state_key, redacts, relates_to_id"
  923. " FROM events AS e"
  924. " INNER JOIN ex_outlier_stream USING (event_id)"
  925. " LEFT JOIN redactions USING (event_id)"
  926. " LEFT JOIN state_events USING (event_id)"
  927. " LEFT JOIN event_relations USING (event_id)"
  928. " WHERE ? > event_stream_ordering"
  929. " AND event_stream_ordering >= ?"
  930. " ORDER BY event_stream_ordering DESC"
  931. )
  932. txn.execute(sql, (-last_id, -upper_bound))
  933. new_event_updates.extend((row[0], row[1:]) for row in txn)
  934. if len(new_event_updates) >= limit:
  935. upper_bound = new_event_updates[-1][0]
  936. limited = True
  937. return new_event_updates, upper_bound, limited
  938. return await self.db_pool.runInteraction(
  939. "get_all_new_backfill_event_rows", get_all_new_backfill_event_rows
  940. )
  941. async def get_all_updated_current_state_deltas(
  942. self, from_token: int, to_token: int, target_row_count: int
  943. ) -> Tuple[List[Tuple], int, bool]:
  944. """Fetch updates from current_state_delta_stream
  945. Args:
  946. from_token: The previous stream token. Updates from this stream id will
  947. be excluded.
  948. to_token: The current stream token (ie the upper limit). Updates up to this
  949. stream id will be included (modulo the 'limit' param)
  950. target_row_count: The number of rows to try to return. If more rows are
  951. available, we will set 'limited' in the result. In the event of a large
  952. batch, we may return more rows than this.
  953. Returns:
  954. A triplet `(updates, new_last_token, limited)`, where:
  955. * `updates` is a list of database tuples.
  956. * `new_last_token` is the new position in stream.
  957. * `limited` is whether there are more updates to fetch.
  958. """
  959. def get_all_updated_current_state_deltas_txn(txn):
  960. sql = """
  961. SELECT stream_id, room_id, type, state_key, event_id
  962. FROM current_state_delta_stream
  963. WHERE ? < stream_id AND stream_id <= ?
  964. ORDER BY stream_id ASC LIMIT ?
  965. """
  966. txn.execute(sql, (from_token, to_token, target_row_count))
  967. return txn.fetchall()
  968. def get_deltas_for_stream_id_txn(txn, stream_id):
  969. sql = """
  970. SELECT stream_id, room_id, type, state_key, event_id
  971. FROM current_state_delta_stream
  972. WHERE stream_id = ?
  973. """
  974. txn.execute(sql, [stream_id])
  975. return txn.fetchall()
  976. # we need to make sure that, for every stream id in the results, we get *all*
  977. # the rows with that stream id.
  978. rows = await self.db_pool.runInteraction(
  979. "get_all_updated_current_state_deltas",
  980. get_all_updated_current_state_deltas_txn,
  981. ) # type: List[Tuple]
  982. # if we've got fewer rows than the limit, we're good
  983. if len(rows) < target_row_count:
  984. return rows, to_token, False
  985. # we hit the limit, so reduce the upper limit so that we exclude the stream id
  986. # of the last row in the result.
  987. assert rows[-1][0] <= to_token
  988. to_token = rows[-1][0] - 1
  989. # search backwards through the list for the point to truncate
  990. for idx in range(len(rows) - 1, 0, -1):
  991. if rows[idx - 1][0] <= to_token:
  992. return rows[:idx], to_token, True
  993. # bother. We didn't get a full set of changes for even a single
  994. # stream id. let's run the query again, without a row limit, but for
  995. # just one stream id.
  996. to_token += 1
  997. rows = await self.db_pool.runInteraction(
  998. "get_deltas_for_stream_id", get_deltas_for_stream_id_txn, to_token
  999. )
  1000. return rows, to_token, True
  1001. @cached(num_args=5, max_entries=10)
  1002. def get_all_new_events(
  1003. self,
  1004. last_backfill_id,
  1005. last_forward_id,
  1006. current_backfill_id,
  1007. current_forward_id,
  1008. limit,
  1009. ):
  1010. """Get all the new events that have arrived at the server either as
  1011. new events or as backfilled events"""
  1012. have_backfill_events = last_backfill_id != current_backfill_id
  1013. have_forward_events = last_forward_id != current_forward_id
  1014. if not have_backfill_events and not have_forward_events:
  1015. return defer.succeed(AllNewEventsResult([], [], [], [], []))
  1016. def get_all_new_events_txn(txn):
  1017. sql = (
  1018. "SELECT e.stream_ordering, e.event_id, e.room_id, e.type,"
  1019. " state_key, redacts"
  1020. " FROM events AS e"
  1021. " LEFT JOIN redactions USING (event_id)"
  1022. " LEFT JOIN state_events USING (event_id)"
  1023. " WHERE ? < stream_ordering AND stream_ordering <= ?"
  1024. " ORDER BY stream_ordering ASC"
  1025. " LIMIT ?"
  1026. )
  1027. if have_forward_events:
  1028. txn.execute(sql, (last_forward_id, current_forward_id, limit))
  1029. new_forward_events = txn.fetchall()
  1030. if len(new_forward_events) == limit:
  1031. upper_bound = new_forward_events[-1][0]
  1032. else:
  1033. upper_bound = current_forward_id
  1034. sql = (
  1035. "SELECT event_stream_ordering, event_id, state_group"
  1036. " FROM ex_outlier_stream"
  1037. " WHERE ? > event_stream_ordering"
  1038. " AND event_stream_ordering >= ?"
  1039. " ORDER BY event_stream_ordering DESC"
  1040. )
  1041. txn.execute(sql, (last_forward_id, upper_bound))
  1042. forward_ex_outliers = txn.fetchall()
  1043. else:
  1044. new_forward_events = []
  1045. forward_ex_outliers = []
  1046. sql = (
  1047. "SELECT -e.stream_ordering, e.event_id, e.room_id, e.type,"
  1048. " state_key, redacts"
  1049. " FROM events AS e"
  1050. " LEFT JOIN redactions USING (event_id)"
  1051. " LEFT JOIN state_events USING (event_id)"
  1052. " WHERE ? > stream_ordering AND stream_ordering >= ?"
  1053. " ORDER BY stream_ordering DESC"
  1054. " LIMIT ?"
  1055. )
  1056. if have_backfill_events:
  1057. txn.execute(sql, (-last_backfill_id, -current_backfill_id, limit))
  1058. new_backfill_events = txn.fetchall()
  1059. if len(new_backfill_events) == limit:
  1060. upper_bound = new_backfill_events[-1][0]
  1061. else:
  1062. upper_bound = current_backfill_id
  1063. sql = (
  1064. "SELECT -event_stream_ordering, event_id, state_group"
  1065. " FROM ex_outlier_stream"
  1066. " WHERE ? > event_stream_ordering"
  1067. " AND event_stream_ordering >= ?"
  1068. " ORDER BY event_stream_ordering DESC"
  1069. )
  1070. txn.execute(sql, (-last_backfill_id, -upper_bound))
  1071. backward_ex_outliers = txn.fetchall()
  1072. else:
  1073. new_backfill_events = []
  1074. backward_ex_outliers = []
  1075. return AllNewEventsResult(
  1076. new_forward_events,
  1077. new_backfill_events,
  1078. forward_ex_outliers,
  1079. backward_ex_outliers,
  1080. )
  1081. return self.db_pool.runInteraction("get_all_new_events", get_all_new_events_txn)
  1082. async def is_event_after(self, event_id1, event_id2):
  1083. """Returns True if event_id1 is after event_id2 in the stream
  1084. """
  1085. to_1, so_1 = await self.get_event_ordering(event_id1)
  1086. to_2, so_2 = await self.get_event_ordering(event_id2)
  1087. return (to_1, so_1) > (to_2, so_2)
  1088. @cachedInlineCallbacks(max_entries=5000)
  1089. def get_event_ordering(self, event_id):
  1090. res = yield self.db_pool.simple_select_one(
  1091. table="events",
  1092. retcols=["topological_ordering", "stream_ordering"],
  1093. keyvalues={"event_id": event_id},
  1094. allow_none=True,
  1095. )
  1096. if not res:
  1097. raise SynapseError(404, "Could not find event %s" % (event_id,))
  1098. return (int(res["topological_ordering"]), int(res["stream_ordering"]))
  1099. def get_next_event_to_expire(self):
  1100. """Retrieve the entry with the lowest expiry timestamp in the event_expiry
  1101. table, or None if there's no more event to expire.
  1102. Returns: Deferred[Optional[Tuple[str, int]]]
  1103. A tuple containing the event ID as its first element and an expiry timestamp
  1104. as its second one, if there's at least one row in the event_expiry table.
  1105. None otherwise.
  1106. """
  1107. def get_next_event_to_expire_txn(txn):
  1108. txn.execute(
  1109. """
  1110. SELECT event_id, expiry_ts FROM event_expiry
  1111. ORDER BY expiry_ts ASC LIMIT 1
  1112. """
  1113. )
  1114. return txn.fetchone()
  1115. return self.db_pool.runInteraction(
  1116. desc="get_next_event_to_expire", func=get_next_event_to_expire_txn
  1117. )
  1118. @cached(tree=True, cache_context=True)
  1119. async def get_unread_message_count_for_user(
  1120. self, room_id: str, user_id: str, cache_context: _CacheContext,
  1121. ) -> int:
  1122. """Retrieve the count of unread messages for the given room and user.
  1123. Args:
  1124. room_id: The ID of the room to count unread messages in.
  1125. user_id: The ID of the user to count unread messages for.
  1126. Returns:
  1127. The number of unread messages for the given user in the given room.
  1128. """
  1129. with Measure(self._clock, "get_unread_message_count_for_user"):
  1130. last_read_event_id = await self.get_last_receipt_event_id_for_user(
  1131. user_id=user_id,
  1132. room_id=room_id,
  1133. receipt_type="m.read",
  1134. on_invalidate=cache_context.invalidate,
  1135. )
  1136. return await self.db_pool.runInteraction(
  1137. "get_unread_message_count_for_user",
  1138. self._get_unread_message_count_for_user_txn,
  1139. user_id,
  1140. room_id,
  1141. last_read_event_id,
  1142. )
  1143. def _get_unread_message_count_for_user_txn(
  1144. self,
  1145. txn: Cursor,
  1146. user_id: str,
  1147. room_id: str,
  1148. last_read_event_id: Optional[str],
  1149. ) -> int:
  1150. if last_read_event_id:
  1151. # Get the stream ordering for the last read event.
  1152. stream_ordering = self.db_pool.simple_select_one_onecol_txn(
  1153. txn=txn,
  1154. table="events",
  1155. keyvalues={"room_id": room_id, "event_id": last_read_event_id},
  1156. retcol="stream_ordering",
  1157. )
  1158. else:
  1159. # If there's no read receipt for that room, it probably means the user hasn't
  1160. # opened it yet, in which case use the stream ID of their join event.
  1161. # We can't just set it to 0 otherwise messages from other local users from
  1162. # before this user joined will be counted as well.
  1163. txn.execute(
  1164. """
  1165. SELECT stream_ordering FROM local_current_membership
  1166. LEFT JOIN events USING (event_id, room_id)
  1167. WHERE membership = 'join'
  1168. AND user_id = ?
  1169. AND room_id = ?
  1170. """,
  1171. (user_id, room_id),
  1172. )
  1173. row = txn.fetchone()
  1174. if row is None:
  1175. return 0
  1176. stream_ordering = row[0]
  1177. # Count the messages that qualify as unread after the stream ordering we've just
  1178. # retrieved.
  1179. sql = """
  1180. SELECT COUNT(*) FROM events
  1181. WHERE sender != ? AND room_id = ? AND stream_ordering > ? AND count_as_unread
  1182. """
  1183. txn.execute(sql, (user_id, room_id, stream_ordering))
  1184. row = txn.fetchone()
  1185. return row[0] if row else 0
  1186. AllNewEventsResult = namedtuple(
  1187. "AllNewEventsResult",
  1188. [
  1189. "new_forward_events",
  1190. "new_backfill_events",
  1191. "forward_ex_outliers",
  1192. "backward_ex_outliers",
  1193. ],
  1194. )