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.
 
 
 
 
 
 

1121 lines
41 KiB

  1. # Copyright 2019 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import (
  16. TYPE_CHECKING,
  17. Collection,
  18. Dict,
  19. FrozenSet,
  20. Iterable,
  21. List,
  22. Mapping,
  23. Optional,
  24. Sequence,
  25. Set,
  26. Tuple,
  27. Union,
  28. cast,
  29. )
  30. import attr
  31. from synapse.api.constants import MAIN_TIMELINE, Direction, RelationTypes
  32. from synapse.api.errors import SynapseError
  33. from synapse.events import EventBase
  34. from synapse.storage._base import SQLBaseStore
  35. from synapse.storage.database import (
  36. DatabasePool,
  37. LoggingDatabaseConnection,
  38. LoggingTransaction,
  39. make_in_list_sql_clause,
  40. )
  41. from synapse.storage.databases.main.stream import (
  42. generate_next_token,
  43. generate_pagination_bounds,
  44. generate_pagination_where_clause,
  45. )
  46. from synapse.storage.engines import PostgresEngine
  47. from synapse.types import JsonDict, StreamKeyType, StreamToken
  48. from synapse.util.caches.descriptors import cached, cachedList
  49. if TYPE_CHECKING:
  50. from synapse.server import HomeServer
  51. logger = logging.getLogger(__name__)
  52. @attr.s(slots=True, frozen=True, auto_attribs=True)
  53. class ThreadsNextBatch:
  54. topological_ordering: int
  55. stream_ordering: int
  56. def __str__(self) -> str:
  57. return f"{self.topological_ordering}_{self.stream_ordering}"
  58. @classmethod
  59. def from_string(cls, string: str) -> "ThreadsNextBatch":
  60. """
  61. Creates a ThreadsNextBatch from its textual representation.
  62. """
  63. try:
  64. keys = (int(s) for s in string.split("_"))
  65. return cls(*keys)
  66. except Exception:
  67. raise SynapseError(400, "Invalid threads token")
  68. @attr.s(slots=True, frozen=True, auto_attribs=True)
  69. class _RelatedEvent:
  70. """
  71. Contains enough information about a related event in order to properly filter
  72. events from ignored users.
  73. """
  74. # The event ID of the related event.
  75. event_id: str
  76. # The sender of the related event.
  77. sender: str
  78. class RelationsWorkerStore(SQLBaseStore):
  79. def __init__(
  80. self,
  81. database: DatabasePool,
  82. db_conn: LoggingDatabaseConnection,
  83. hs: "HomeServer",
  84. ):
  85. super().__init__(database, db_conn, hs)
  86. self.db_pool.updates.register_background_update_handler(
  87. "threads_backfill", self._backfill_threads
  88. )
  89. async def _backfill_threads(self, progress: JsonDict, batch_size: int) -> int:
  90. """Backfill the threads table."""
  91. def threads_backfill_txn(txn: LoggingTransaction) -> int:
  92. last_thread_id = progress.get("last_thread_id", "")
  93. # Get the latest event in each thread by topo ordering / stream ordering.
  94. #
  95. # Note that the MAX(event_id) is needed to abide by the rules of group by,
  96. # but doesn't actually do anything since there should only be a single event
  97. # ID per topo/stream ordering pair.
  98. sql = f"""
  99. SELECT room_id, relates_to_id, MAX(topological_ordering), MAX(stream_ordering), MAX(event_id)
  100. FROM event_relations
  101. INNER JOIN events USING (event_id)
  102. WHERE
  103. relates_to_id > ? AND
  104. relation_type = '{RelationTypes.THREAD}'
  105. GROUP BY room_id, relates_to_id
  106. ORDER BY relates_to_id
  107. LIMIT ?
  108. """
  109. txn.execute(sql, (last_thread_id, batch_size))
  110. # No more rows to process.
  111. rows = txn.fetchall()
  112. if not rows:
  113. return 0
  114. # Insert the rows into the threads table. If a matching thread already exists,
  115. # assume it is from a newer event.
  116. sql = """
  117. INSERT INTO threads (room_id, thread_id, topological_ordering, stream_ordering, latest_event_id)
  118. VALUES %s
  119. ON CONFLICT (room_id, thread_id)
  120. DO NOTHING
  121. """
  122. if isinstance(txn.database_engine, PostgresEngine):
  123. txn.execute_values(sql % ("?",), rows, fetch=False)
  124. else:
  125. txn.execute_batch(sql % ("(?, ?, ?, ?, ?)",), rows)
  126. # Mark the progress.
  127. self.db_pool.updates._background_update_progress_txn(
  128. txn, "threads_backfill", {"last_thread_id": rows[-1][1]}
  129. )
  130. return txn.rowcount
  131. result = await self.db_pool.runInteraction(
  132. "threads_backfill", threads_backfill_txn
  133. )
  134. if not result:
  135. await self.db_pool.updates._end_background_update("threads_backfill")
  136. return result
  137. @cached(uncached_args=("event",), tree=True)
  138. async def get_relations_for_event(
  139. self,
  140. event_id: str,
  141. event: EventBase,
  142. room_id: str,
  143. relation_type: Optional[str] = None,
  144. event_type: Optional[str] = None,
  145. limit: int = 5,
  146. direction: Direction = Direction.BACKWARDS,
  147. from_token: Optional[StreamToken] = None,
  148. to_token: Optional[StreamToken] = None,
  149. recurse: bool = False,
  150. ) -> Tuple[Sequence[_RelatedEvent], Optional[StreamToken]]:
  151. """Get a list of relations for an event, ordered by topological ordering.
  152. Args:
  153. event_id: Fetch events that relate to this event ID.
  154. event: The matching EventBase to event_id.
  155. room_id: The room the event belongs to.
  156. relation_type: Only fetch events with this relation type, if given.
  157. event_type: Only fetch events with this event type, if given.
  158. limit: Only fetch the most recent `limit` events.
  159. direction: Whether to fetch the most recent first (backwards) or the
  160. oldest first (forwards).
  161. from_token: Fetch rows from the given token, or from the start if None.
  162. to_token: Fetch rows up to the given token, or up to the end if None.
  163. recurse: Whether to recursively find relations.
  164. Returns:
  165. A tuple of:
  166. A list of related event IDs & their senders.
  167. The next stream token, if one exists.
  168. """
  169. # We don't use `event_id`, it's there so that we can cache based on
  170. # it. The `event_id` must match the `event.event_id`.
  171. assert event.event_id == event_id
  172. # Ensure bad limits aren't being passed in.
  173. assert limit >= 0
  174. where_clause = ["room_id = ?"]
  175. where_args: List[Union[str, int]] = [room_id]
  176. is_redacted = event.internal_metadata.is_redacted()
  177. if relation_type is not None:
  178. where_clause.append("relation_type = ?")
  179. where_args.append(relation_type)
  180. if event_type is not None:
  181. where_clause.append("type = ?")
  182. where_args.append(event_type)
  183. order, from_bound, to_bound = generate_pagination_bounds(
  184. direction,
  185. from_token.room_key if from_token else None,
  186. to_token.room_key if to_token else None,
  187. )
  188. pagination_clause = generate_pagination_where_clause(
  189. direction=direction,
  190. column_names=("topological_ordering", "stream_ordering"),
  191. from_token=from_bound,
  192. to_token=to_bound,
  193. engine=self.database_engine,
  194. )
  195. if pagination_clause:
  196. where_clause.append(pagination_clause)
  197. # If a recursive query is requested then the filters are applied after
  198. # recursively following relationships from the requested event to children
  199. # up to 3-relations deep.
  200. #
  201. # If no recursion is needed then the event_relations table is queried
  202. # for direct children of the requested event.
  203. if recurse:
  204. sql = """
  205. WITH RECURSIVE related_events AS (
  206. SELECT event_id, relation_type, relates_to_id, 0 AS depth
  207. FROM event_relations
  208. WHERE relates_to_id = ?
  209. UNION SELECT e.event_id, e.relation_type, e.relates_to_id, depth + 1
  210. FROM event_relations e
  211. INNER JOIN related_events r ON r.event_id = e.relates_to_id
  212. WHERE depth <= 3
  213. )
  214. SELECT event_id, relation_type, sender, topological_ordering, stream_ordering
  215. FROM related_events
  216. INNER JOIN events USING (event_id)
  217. WHERE %s
  218. ORDER BY topological_ordering %s, stream_ordering %s
  219. LIMIT ?;
  220. """ % (
  221. " AND ".join(where_clause),
  222. order,
  223. order,
  224. )
  225. else:
  226. sql = """
  227. SELECT event_id, relation_type, sender, topological_ordering, stream_ordering
  228. FROM event_relations
  229. INNER JOIN events USING (event_id)
  230. WHERE relates_to_id = ? AND %s
  231. ORDER BY topological_ordering %s, stream_ordering %s
  232. LIMIT ?
  233. """ % (
  234. " AND ".join(where_clause),
  235. order,
  236. order,
  237. )
  238. def _get_recent_references_for_event_txn(
  239. txn: LoggingTransaction,
  240. ) -> Tuple[List[_RelatedEvent], Optional[StreamToken]]:
  241. txn.execute(sql, [event.event_id] + where_args + [limit + 1])
  242. events = []
  243. topo_orderings: List[int] = []
  244. stream_orderings: List[int] = []
  245. for event_id, relation_type, sender, topo_ordering, stream_ordering in cast(
  246. List[Tuple[str, str, str, int, int]], txn
  247. ):
  248. # Do not include edits for redacted events as they leak event
  249. # content.
  250. if not is_redacted or relation_type != RelationTypes.REPLACE:
  251. events.append(_RelatedEvent(event_id, sender))
  252. topo_orderings.append(topo_ordering)
  253. stream_orderings.append(stream_ordering)
  254. # If there are more events, generate the next pagination key from the
  255. # last event returned.
  256. next_token = None
  257. if len(events) > limit:
  258. # Instead of using the last row (which tells us there is more
  259. # data), use the last row to be returned.
  260. events = events[:limit]
  261. topo_orderings = topo_orderings[:limit]
  262. stream_orderings = stream_orderings[:limit]
  263. next_key = generate_next_token(
  264. direction, topo_orderings[-1], stream_orderings[-1]
  265. )
  266. if from_token:
  267. next_token = from_token.copy_and_replace(
  268. StreamKeyType.ROOM, next_key
  269. )
  270. else:
  271. next_token = StreamToken(
  272. room_key=next_key,
  273. presence_key=0,
  274. typing_key=0,
  275. receipt_key=0,
  276. account_data_key=0,
  277. push_rules_key=0,
  278. to_device_key=0,
  279. device_list_key=0,
  280. groups_key=0,
  281. un_partial_stated_rooms_key=0,
  282. )
  283. return events[:limit], next_token
  284. return await self.db_pool.runInteraction(
  285. "get_recent_references_for_event", _get_recent_references_for_event_txn
  286. )
  287. async def get_all_relations_for_event_with_types(
  288. self,
  289. event_id: str,
  290. relation_types: List[str],
  291. ) -> List[str]:
  292. """Get the event IDs of all events that have a relation to the given event with
  293. one of the given relation types.
  294. Args:
  295. event_id: The event for which to look for related events.
  296. relation_types: The types of relations to look for.
  297. Returns:
  298. A list of the IDs of the events that relate to the given event with one of
  299. the given relation types.
  300. """
  301. def get_all_relation_ids_for_event_with_types_txn(
  302. txn: LoggingTransaction,
  303. ) -> List[str]:
  304. rows = self.db_pool.simple_select_many_txn(
  305. txn=txn,
  306. table="event_relations",
  307. column="relation_type",
  308. iterable=relation_types,
  309. keyvalues={"relates_to_id": event_id},
  310. retcols=["event_id"],
  311. )
  312. return [row["event_id"] for row in rows]
  313. return await self.db_pool.runInteraction(
  314. desc="get_all_relation_ids_for_event_with_types",
  315. func=get_all_relation_ids_for_event_with_types_txn,
  316. )
  317. async def get_all_relations_for_event(
  318. self,
  319. event_id: str,
  320. ) -> List[str]:
  321. """Get the event IDs of all events that have a relation to the given event.
  322. Args:
  323. event_id: The event for which to look for related events.
  324. Returns:
  325. A list of the IDs of the events that relate to the given event.
  326. """
  327. def get_all_relation_ids_for_event_txn(
  328. txn: LoggingTransaction,
  329. ) -> List[str]:
  330. rows = self.db_pool.simple_select_list_txn(
  331. txn=txn,
  332. table="event_relations",
  333. keyvalues={"relates_to_id": event_id},
  334. retcols=["event_id"],
  335. )
  336. return [row["event_id"] for row in rows]
  337. return await self.db_pool.runInteraction(
  338. desc="get_all_relation_ids_for_event",
  339. func=get_all_relation_ids_for_event_txn,
  340. )
  341. async def event_includes_relation(self, event_id: str) -> bool:
  342. """Check if the given event relates to another event.
  343. An event has a relation if it has a valid m.relates_to with a rel_type
  344. and event_id in the content:
  345. {
  346. "content": {
  347. "m.relates_to": {
  348. "rel_type": "m.replace",
  349. "event_id": "$other_event_id"
  350. }
  351. }
  352. }
  353. Args:
  354. event_id: The event to check.
  355. Returns:
  356. True if the event includes a valid relation.
  357. """
  358. result = await self.db_pool.simple_select_one_onecol(
  359. table="event_relations",
  360. keyvalues={"event_id": event_id},
  361. retcol="event_id",
  362. allow_none=True,
  363. desc="event_includes_relation",
  364. )
  365. return result is not None
  366. async def event_is_target_of_relation(self, parent_id: str) -> bool:
  367. """Check if the given event is the target of another event's relation.
  368. An event is the target of an event relation if it has a valid
  369. m.relates_to with a rel_type and event_id pointing to parent_id in the
  370. content:
  371. {
  372. "content": {
  373. "m.relates_to": {
  374. "rel_type": "m.replace",
  375. "event_id": "$parent_id"
  376. }
  377. }
  378. }
  379. Args:
  380. parent_id: The event to check.
  381. Returns:
  382. True if the event is the target of another event's relation.
  383. """
  384. result = await self.db_pool.simple_select_one_onecol(
  385. table="event_relations",
  386. keyvalues={"relates_to_id": parent_id},
  387. retcol="event_id",
  388. allow_none=True,
  389. desc="event_is_target_of_relation",
  390. )
  391. return result is not None
  392. @cached() # type: ignore[synapse-@cached-mutable]
  393. async def get_references_for_event(self, event_id: str) -> List[JsonDict]:
  394. raise NotImplementedError()
  395. @cachedList(cached_method_name="get_references_for_event", list_name="event_ids")
  396. async def get_references_for_events(
  397. self, event_ids: Collection[str]
  398. ) -> Mapping[str, Optional[Sequence[_RelatedEvent]]]:
  399. """Get a list of references to the given events.
  400. Args:
  401. event_ids: Fetch events that relate to these event IDs.
  402. Returns:
  403. A map of event IDs to a list of related event IDs (and their senders).
  404. """
  405. clause, args = make_in_list_sql_clause(
  406. self.database_engine, "relates_to_id", event_ids
  407. )
  408. args.append(RelationTypes.REFERENCE)
  409. sql = f"""
  410. SELECT relates_to_id, ref.event_id, ref.sender
  411. FROM events AS ref
  412. INNER JOIN event_relations USING (event_id)
  413. INNER JOIN events AS parent ON
  414. parent.event_id = relates_to_id
  415. AND parent.room_id = ref.room_id
  416. WHERE
  417. {clause}
  418. AND relation_type = ?
  419. ORDER BY ref.topological_ordering, ref.stream_ordering
  420. """
  421. def _get_references_for_events_txn(
  422. txn: LoggingTransaction,
  423. ) -> Mapping[str, List[_RelatedEvent]]:
  424. txn.execute(sql, args)
  425. result: Dict[str, List[_RelatedEvent]] = {}
  426. for relates_to_id, event_id, sender in cast(
  427. List[Tuple[str, str, str]], txn
  428. ):
  429. result.setdefault(relates_to_id, []).append(
  430. _RelatedEvent(event_id, sender)
  431. )
  432. return result
  433. return await self.db_pool.runInteraction(
  434. "_get_references_for_events_txn", _get_references_for_events_txn
  435. )
  436. @cached() # type: ignore[synapse-@cached-mutable]
  437. def get_applicable_edit(self, event_id: str) -> Optional[EventBase]:
  438. raise NotImplementedError()
  439. # TODO: This returns a mutable object, which is generally bad.
  440. @cachedList(cached_method_name="get_applicable_edit", list_name="event_ids") # type: ignore[synapse-@cached-mutable]
  441. async def get_applicable_edits(
  442. self, event_ids: Collection[str]
  443. ) -> Mapping[str, Optional[EventBase]]:
  444. """Get the most recent edit (if any) that has happened for the given
  445. events.
  446. Correctly handles checking whether edits were allowed to happen.
  447. Args:
  448. event_ids: The original event IDs
  449. Returns:
  450. A map of the most recent edit for each event. If there are no edits,
  451. the event will map to None.
  452. """
  453. # We only allow edits for events that have the same sender and event type.
  454. # We can't assert these things during regular event auth so we have to do
  455. # the checks post hoc.
  456. # Fetches latest edit that has the same type and sender as the original.
  457. if isinstance(self.database_engine, PostgresEngine):
  458. # The `DISTINCT ON` clause will pick the *first* row it encounters,
  459. # so ordering by origin server ts + event ID desc will ensure we get
  460. # the latest edit.
  461. sql = """
  462. SELECT DISTINCT ON (original.event_id) original.event_id, edit.event_id FROM events AS edit
  463. INNER JOIN event_relations USING (event_id)
  464. INNER JOIN events AS original ON
  465. original.event_id = relates_to_id
  466. AND edit.type = original.type
  467. AND edit.sender = original.sender
  468. AND edit.room_id = original.room_id
  469. WHERE
  470. %s
  471. AND relation_type = ?
  472. ORDER by original.event_id DESC, edit.origin_server_ts DESC, edit.event_id DESC
  473. """
  474. else:
  475. # SQLite uses a simplified query which returns all edits for an
  476. # original event. The results are then de-duplicated when turned into
  477. # a dict. Due to the chosen ordering, the latest edit stomps on
  478. # earlier edits.
  479. sql = """
  480. SELECT original.event_id, edit.event_id FROM events AS edit
  481. INNER JOIN event_relations USING (event_id)
  482. INNER JOIN events AS original ON
  483. original.event_id = relates_to_id
  484. AND edit.type = original.type
  485. AND edit.sender = original.sender
  486. AND edit.room_id = original.room_id
  487. WHERE
  488. %s
  489. AND relation_type = ?
  490. ORDER by edit.origin_server_ts, edit.event_id
  491. """
  492. def _get_applicable_edits_txn(txn: LoggingTransaction) -> Dict[str, str]:
  493. clause, args = make_in_list_sql_clause(
  494. txn.database_engine, "relates_to_id", event_ids
  495. )
  496. args.append(RelationTypes.REPLACE)
  497. txn.execute(sql % (clause,), args)
  498. return dict(cast(Iterable[Tuple[str, str]], txn.fetchall()))
  499. edit_ids = await self.db_pool.runInteraction(
  500. "get_applicable_edits", _get_applicable_edits_txn
  501. )
  502. edits = await self.get_events(edit_ids.values()) # type: ignore[attr-defined]
  503. # Map to the original event IDs to the edit events.
  504. #
  505. # There might not be an edit event due to there being no edits or
  506. # due to the event not being known, either case is treated the same.
  507. return {
  508. original_event_id: edits.get(edit_ids.get(original_event_id))
  509. for original_event_id in event_ids
  510. }
  511. @cached() # type: ignore[synapse-@cached-mutable]
  512. def get_thread_summary(self, event_id: str) -> Optional[Tuple[int, EventBase]]:
  513. raise NotImplementedError()
  514. # TODO: This returns a mutable object, which is generally bad.
  515. @cachedList(cached_method_name="get_thread_summary", list_name="event_ids") # type: ignore[synapse-@cached-mutable]
  516. async def get_thread_summaries(
  517. self, event_ids: Collection[str]
  518. ) -> Mapping[str, Optional[Tuple[int, EventBase]]]:
  519. """Get the number of threaded replies and the latest reply (if any) for the given events.
  520. Args:
  521. event_ids: Summarize the thread related to this event ID.
  522. Returns:
  523. A map of the thread summary each event. A missing event implies there
  524. are no threaded replies.
  525. Each summary is a tuple of:
  526. The number of events in the thread.
  527. The most recent event in the thread.
  528. """
  529. def _get_thread_summaries_txn(
  530. txn: LoggingTransaction,
  531. ) -> Tuple[Dict[str, int], Dict[str, str]]:
  532. # Fetch the count of threaded events and the latest event ID.
  533. # TODO Should this only allow m.room.message events.
  534. if isinstance(self.database_engine, PostgresEngine):
  535. # The `DISTINCT ON` clause will pick the *first* row it encounters,
  536. # so ordering by topological ordering + stream ordering desc will
  537. # ensure we get the latest event in the thread.
  538. sql = """
  539. SELECT DISTINCT ON (parent.event_id) parent.event_id, child.event_id FROM events AS child
  540. INNER JOIN event_relations USING (event_id)
  541. INNER JOIN events AS parent ON
  542. parent.event_id = relates_to_id
  543. AND parent.room_id = child.room_id
  544. WHERE
  545. %s
  546. AND relation_type = ?
  547. ORDER BY parent.event_id, child.topological_ordering DESC, child.stream_ordering DESC
  548. """
  549. else:
  550. # SQLite uses a simplified query which returns all entries for a
  551. # thread. The first result for each thread is chosen to and subsequent
  552. # results for a thread are ignored.
  553. sql = """
  554. SELECT parent.event_id, child.event_id FROM events AS child
  555. INNER JOIN event_relations USING (event_id)
  556. INNER JOIN events AS parent ON
  557. parent.event_id = relates_to_id
  558. AND parent.room_id = child.room_id
  559. WHERE
  560. %s
  561. AND relation_type = ?
  562. ORDER BY child.topological_ordering DESC, child.stream_ordering DESC
  563. """
  564. clause, args = make_in_list_sql_clause(
  565. txn.database_engine, "relates_to_id", event_ids
  566. )
  567. args.append(RelationTypes.THREAD)
  568. txn.execute(sql % (clause,), args)
  569. latest_event_ids = {}
  570. for parent_event_id, child_event_id in txn:
  571. # Only consider the latest threaded reply (by topological ordering).
  572. if parent_event_id not in latest_event_ids:
  573. latest_event_ids[parent_event_id] = child_event_id
  574. # If no threads were found, bail.
  575. if not latest_event_ids:
  576. return {}, latest_event_ids
  577. # Fetch the number of threaded replies.
  578. sql = """
  579. SELECT parent.event_id, COUNT(child.event_id) FROM events AS child
  580. INNER JOIN event_relations USING (event_id)
  581. INNER JOIN events AS parent ON
  582. parent.event_id = relates_to_id
  583. AND parent.room_id = child.room_id
  584. WHERE
  585. %s
  586. AND relation_type = ?
  587. GROUP BY parent.event_id
  588. """
  589. # Regenerate the arguments since only threads found above could
  590. # possibly have any replies.
  591. clause, args = make_in_list_sql_clause(
  592. txn.database_engine, "relates_to_id", latest_event_ids.keys()
  593. )
  594. args.append(RelationTypes.THREAD)
  595. txn.execute(sql % (clause,), args)
  596. counts = dict(cast(List[Tuple[str, int]], txn.fetchall()))
  597. return counts, latest_event_ids
  598. counts, latest_event_ids = await self.db_pool.runInteraction(
  599. "get_thread_summaries", _get_thread_summaries_txn
  600. )
  601. latest_events = await self.get_events(latest_event_ids.values()) # type: ignore[attr-defined]
  602. # Map to the event IDs to the thread summary.
  603. #
  604. # There might not be a summary due to there not being a thread or
  605. # due to the latest event not being known, either case is treated the same.
  606. summaries = {}
  607. for parent_event_id, latest_event_id in latest_event_ids.items():
  608. latest_event = latest_events.get(latest_event_id)
  609. summary = None
  610. if latest_event:
  611. summary = (counts[parent_event_id], latest_event)
  612. summaries[parent_event_id] = summary
  613. return summaries
  614. async def get_threaded_messages_per_user(
  615. self,
  616. event_ids: Collection[str],
  617. users: FrozenSet[str] = frozenset(),
  618. ) -> Dict[Tuple[str, str], int]:
  619. """Get the number of threaded replies for a set of users.
  620. This is used, in conjunction with get_thread_summaries, to calculate an
  621. accurate count of the replies to a thread by subtracting ignored users.
  622. Args:
  623. event_ids: The events to check for threaded replies.
  624. users: The user to calculate the count of their replies.
  625. Returns:
  626. A map of the (event_id, sender) to the count of their replies.
  627. """
  628. if not users:
  629. return {}
  630. # Fetch the number of threaded replies.
  631. sql = """
  632. SELECT parent.event_id, child.sender, COUNT(child.event_id) FROM events AS child
  633. INNER JOIN event_relations USING (event_id)
  634. INNER JOIN events AS parent ON
  635. parent.event_id = relates_to_id
  636. AND parent.room_id = child.room_id
  637. WHERE
  638. relation_type = ?
  639. AND %s
  640. AND %s
  641. GROUP BY parent.event_id, child.sender
  642. """
  643. def _get_threaded_messages_per_user_txn(
  644. txn: LoggingTransaction,
  645. ) -> Dict[Tuple[str, str], int]:
  646. users_sql, users_args = make_in_list_sql_clause(
  647. self.database_engine, "child.sender", users
  648. )
  649. events_clause, events_args = make_in_list_sql_clause(
  650. txn.database_engine, "relates_to_id", event_ids
  651. )
  652. txn.execute(
  653. sql % (users_sql, events_clause),
  654. [RelationTypes.THREAD] + users_args + events_args,
  655. )
  656. return {(row[0], row[1]): row[2] for row in txn}
  657. return await self.db_pool.runInteraction(
  658. "get_threaded_messages_per_user", _get_threaded_messages_per_user_txn
  659. )
  660. @cached()
  661. def get_thread_participated(self, event_id: str, user_id: str) -> bool:
  662. raise NotImplementedError()
  663. @cachedList(cached_method_name="get_thread_participated", list_name="event_ids")
  664. async def get_threads_participated(
  665. self, event_ids: Collection[str], user_id: str
  666. ) -> Mapping[str, bool]:
  667. """Get whether the requesting user participated in the given threads.
  668. This is separate from get_thread_summaries since that can be cached across
  669. all users while this value is specific to the requester.
  670. Args:
  671. event_ids: The thread related to these event IDs.
  672. user_id: The user requesting the summary.
  673. Returns:
  674. A map of event ID to a boolean which represents if the requesting
  675. user participated in that event's thread, otherwise false.
  676. """
  677. def _get_threads_participated_txn(txn: LoggingTransaction) -> Set[str]:
  678. # Fetch whether the requester has participated or not.
  679. sql = """
  680. SELECT DISTINCT relates_to_id
  681. FROM events AS child
  682. INNER JOIN event_relations USING (event_id)
  683. INNER JOIN events AS parent ON
  684. parent.event_id = relates_to_id
  685. AND parent.room_id = child.room_id
  686. WHERE
  687. %s
  688. AND relation_type = ?
  689. AND child.sender = ?
  690. """
  691. clause, args = make_in_list_sql_clause(
  692. txn.database_engine, "relates_to_id", event_ids
  693. )
  694. args.extend([RelationTypes.THREAD, user_id])
  695. txn.execute(sql % (clause,), args)
  696. return {row[0] for row in txn.fetchall()}
  697. participated_threads = await self.db_pool.runInteraction(
  698. "get_threads_participated", _get_threads_participated_txn
  699. )
  700. return {event_id: event_id in participated_threads for event_id in event_ids}
  701. async def events_have_relations(
  702. self,
  703. parent_ids: List[str],
  704. relation_senders: Optional[List[str]],
  705. relation_types: Optional[List[str]],
  706. ) -> List[str]:
  707. """Check which events have a relationship from the given senders of the
  708. given types.
  709. Args:
  710. parent_ids: The events being annotated
  711. relation_senders: The relation senders to check.
  712. relation_types: The relation types to check.
  713. Returns:
  714. True if the event has at least one relationship from one of the given senders of the given type.
  715. """
  716. # If no restrictions are given then the event has the required relations.
  717. if not relation_senders and not relation_types:
  718. return parent_ids
  719. sql = """
  720. SELECT relates_to_id FROM event_relations
  721. INNER JOIN events USING (event_id)
  722. WHERE
  723. %s;
  724. """
  725. def _get_if_events_have_relations(txn: LoggingTransaction) -> List[str]:
  726. clauses: List[str] = []
  727. clause, args = make_in_list_sql_clause(
  728. txn.database_engine, "relates_to_id", parent_ids
  729. )
  730. clauses.append(clause)
  731. if relation_senders:
  732. clause, temp_args = make_in_list_sql_clause(
  733. txn.database_engine, "sender", relation_senders
  734. )
  735. clauses.append(clause)
  736. args.extend(temp_args)
  737. if relation_types:
  738. clause, temp_args = make_in_list_sql_clause(
  739. txn.database_engine, "relation_type", relation_types
  740. )
  741. clauses.append(clause)
  742. args.extend(temp_args)
  743. txn.execute(sql % " AND ".join(clauses), args)
  744. return [row[0] for row in txn]
  745. return await self.db_pool.runInteraction(
  746. "get_if_events_have_relations", _get_if_events_have_relations
  747. )
  748. async def has_user_annotated_event(
  749. self, parent_id: str, event_type: str, aggregation_key: str, sender: str
  750. ) -> bool:
  751. """Check if a user has already annotated an event with the same key
  752. (e.g. already liked an event).
  753. Args:
  754. parent_id: The event being annotated
  755. event_type: The event type of the annotation
  756. aggregation_key: The aggregation key of the annotation
  757. sender: The sender of the annotation
  758. Returns:
  759. True if the event is already annotated.
  760. """
  761. sql = """
  762. SELECT 1 FROM event_relations
  763. INNER JOIN events USING (event_id)
  764. WHERE
  765. relates_to_id = ?
  766. AND relation_type = ?
  767. AND type = ?
  768. AND sender = ?
  769. AND aggregation_key = ?
  770. LIMIT 1;
  771. """
  772. def _get_if_user_has_annotated_event(txn: LoggingTransaction) -> bool:
  773. txn.execute(
  774. sql,
  775. (
  776. parent_id,
  777. RelationTypes.ANNOTATION,
  778. event_type,
  779. sender,
  780. aggregation_key,
  781. ),
  782. )
  783. return bool(txn.fetchone())
  784. return await self.db_pool.runInteraction(
  785. "get_if_user_has_annotated_event", _get_if_user_has_annotated_event
  786. )
  787. @cached(tree=True)
  788. async def get_threads(
  789. self,
  790. room_id: str,
  791. limit: int = 5,
  792. from_token: Optional[ThreadsNextBatch] = None,
  793. ) -> Tuple[Sequence[str], Optional[ThreadsNextBatch]]:
  794. """Get a list of thread IDs, ordered by topological ordering of their
  795. latest reply.
  796. Args:
  797. room_id: The room the event belongs to.
  798. limit: Only fetch the most recent `limit` threads.
  799. from_token: Fetch rows from a previous next_batch, or from the start if None.
  800. Returns:
  801. A tuple of:
  802. A list of thread root event IDs.
  803. The next_batch, if one exists.
  804. """
  805. # Generate the pagination clause, if necessary.
  806. #
  807. # Find any threads where the latest reply is equal / before the last
  808. # thread's topo ordering and earlier in stream ordering.
  809. pagination_clause = ""
  810. pagination_args: tuple = ()
  811. if from_token:
  812. pagination_clause = "AND topological_ordering <= ? AND stream_ordering < ?"
  813. pagination_args = (
  814. from_token.topological_ordering,
  815. from_token.stream_ordering,
  816. )
  817. sql = f"""
  818. SELECT thread_id, topological_ordering, stream_ordering
  819. FROM threads
  820. WHERE
  821. room_id = ?
  822. {pagination_clause}
  823. ORDER BY topological_ordering DESC, stream_ordering DESC
  824. LIMIT ?
  825. """
  826. def _get_threads_txn(
  827. txn: LoggingTransaction,
  828. ) -> Tuple[List[str], Optional[ThreadsNextBatch]]:
  829. txn.execute(sql, (room_id, *pagination_args, limit + 1))
  830. rows = cast(List[Tuple[str, int, int]], txn.fetchall())
  831. thread_ids = [r[0] for r in rows]
  832. # If there are more events, generate the next pagination key from the
  833. # last thread which will be returned.
  834. next_token = None
  835. if len(thread_ids) > limit:
  836. last_topo_id = rows[-2][1]
  837. last_stream_id = rows[-2][2]
  838. next_token = ThreadsNextBatch(last_topo_id, last_stream_id)
  839. return thread_ids[:limit], next_token
  840. return await self.db_pool.runInteraction("get_threads", _get_threads_txn)
  841. @cached()
  842. async def get_thread_id(self, event_id: str) -> str:
  843. """
  844. Get the thread ID for an event. This considers multi-level relations,
  845. e.g. an annotation to an event which is part of a thread.
  846. It only searches up the relations tree, i.e. it only searches for events
  847. which the given event is related to (and which those events are related
  848. to, etc.)
  849. Given the following DAG:
  850. A <---[m.thread]-- B <--[m.annotation]-- C
  851. ^
  852. |--[m.reference]-- D <--[m.annotation]-- E
  853. get_thread_id(X) considers events B and C as part of thread A.
  854. See also get_thread_id_for_receipts.
  855. Args:
  856. event_id: The event ID to fetch the thread ID for.
  857. Returns:
  858. The event ID of the root event in the thread, if this event is part
  859. of a thread. "main", otherwise.
  860. """
  861. # Recurse event relations up to the *root* event, then search that chain
  862. # of relations for a thread relation. If one is found, the root event is
  863. # returned.
  864. #
  865. # Note that this should only ever find 0 or 1 entries since it is invalid
  866. # for an event to have a thread relation to an event which also has a
  867. # relation.
  868. sql = """
  869. WITH RECURSIVE related_events AS (
  870. SELECT event_id, relates_to_id, relation_type, 0 AS depth
  871. FROM event_relations
  872. WHERE event_id = ?
  873. UNION SELECT e.event_id, e.relates_to_id, e.relation_type, depth + 1
  874. FROM event_relations e
  875. INNER JOIN related_events r ON r.relates_to_id = e.event_id
  876. WHERE depth <= 3
  877. )
  878. SELECT relates_to_id FROM related_events
  879. WHERE relation_type = 'm.thread'
  880. ORDER BY depth DESC
  881. LIMIT 1;
  882. """
  883. def _get_thread_id(txn: LoggingTransaction) -> str:
  884. txn.execute(sql, (event_id,))
  885. row = txn.fetchone()
  886. if row:
  887. return row[0]
  888. # If no thread was found, it is part of the main timeline.
  889. return MAIN_TIMELINE
  890. return await self.db_pool.runInteraction("get_thread_id", _get_thread_id)
  891. @cached()
  892. async def get_thread_id_for_receipts(self, event_id: str) -> str:
  893. """
  894. Get the thread ID for an event by traversing to the top-most related event
  895. and confirming any children events form a thread.
  896. Given the following DAG:
  897. A <---[m.thread]-- B <--[m.annotation]-- C
  898. ^
  899. |--[m.reference]-- D <--[m.annotation]-- E
  900. get_thread_id_for_receipts(X) considers events A, B, C, D, and E as part
  901. of thread A.
  902. See also get_thread_id.
  903. Args:
  904. event_id: The event ID to fetch the thread ID for.
  905. Returns:
  906. The event ID of the root event in the thread, if this event is part
  907. of a thread. "main", otherwise.
  908. """
  909. # Recurse event relations up to the *root* event, then search for any events
  910. # related to that root node for a thread relation. If one is found, the
  911. # root event is returned.
  912. #
  913. # Note that there cannot be thread relations in the middle of the chain since
  914. # it is invalid for an event to have a thread relation to an event which also
  915. # has a relation.
  916. sql = """
  917. SELECT relates_to_id FROM event_relations WHERE relates_to_id = COALESCE((
  918. WITH RECURSIVE related_events AS (
  919. SELECT event_id, relates_to_id, relation_type, 0 AS depth
  920. FROM event_relations
  921. WHERE event_id = ?
  922. UNION SELECT e.event_id, e.relates_to_id, e.relation_type, depth + 1
  923. FROM event_relations e
  924. INNER JOIN related_events r ON r.relates_to_id = e.event_id
  925. WHERE depth <= 3
  926. )
  927. SELECT relates_to_id FROM related_events
  928. ORDER BY depth DESC
  929. LIMIT 1
  930. ), ?) AND relation_type = 'm.thread' LIMIT 1;
  931. """
  932. def _get_related_thread_id(txn: LoggingTransaction) -> str:
  933. txn.execute(sql, (event_id, event_id))
  934. row = txn.fetchone()
  935. if row:
  936. return row[0]
  937. # If no thread was found, it is part of the main timeline.
  938. return MAIN_TIMELINE
  939. return await self.db_pool.runInteraction(
  940. "get_related_thread_id", _get_related_thread_id
  941. )
  942. class RelationsStore(RelationsWorkerStore):
  943. pass