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.
 
 
 
 
 
 

1124 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, MultiWriterStreamToken, 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=MultiWriterStreamToken(stream=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 = cast(
  305. List[Tuple[str]],
  306. self.db_pool.simple_select_many_txn(
  307. txn=txn,
  308. table="event_relations",
  309. column="relation_type",
  310. iterable=relation_types,
  311. keyvalues={"relates_to_id": event_id},
  312. retcols=["event_id"],
  313. ),
  314. )
  315. return [row[0] for row in rows]
  316. return await self.db_pool.runInteraction(
  317. desc="get_all_relation_ids_for_event_with_types",
  318. func=get_all_relation_ids_for_event_with_types_txn,
  319. )
  320. async def get_all_relations_for_event(
  321. self,
  322. event_id: str,
  323. ) -> List[str]:
  324. """Get the event IDs of all events that have a relation to the given event.
  325. Args:
  326. event_id: The event for which to look for related events.
  327. Returns:
  328. A list of the IDs of the events that relate to the given event.
  329. """
  330. def get_all_relation_ids_for_event_txn(
  331. txn: LoggingTransaction,
  332. ) -> List[str]:
  333. rows = self.db_pool.simple_select_list_txn(
  334. txn=txn,
  335. table="event_relations",
  336. keyvalues={"relates_to_id": event_id},
  337. retcols=["event_id"],
  338. )
  339. return [row["event_id"] for row in rows]
  340. return await self.db_pool.runInteraction(
  341. desc="get_all_relation_ids_for_event",
  342. func=get_all_relation_ids_for_event_txn,
  343. )
  344. async def event_includes_relation(self, event_id: str) -> bool:
  345. """Check if the given event relates to another event.
  346. An event has a relation if it has a valid m.relates_to with a rel_type
  347. and event_id in the content:
  348. {
  349. "content": {
  350. "m.relates_to": {
  351. "rel_type": "m.replace",
  352. "event_id": "$other_event_id"
  353. }
  354. }
  355. }
  356. Args:
  357. event_id: The event to check.
  358. Returns:
  359. True if the event includes a valid relation.
  360. """
  361. result = await self.db_pool.simple_select_one_onecol(
  362. table="event_relations",
  363. keyvalues={"event_id": event_id},
  364. retcol="event_id",
  365. allow_none=True,
  366. desc="event_includes_relation",
  367. )
  368. return result is not None
  369. async def event_is_target_of_relation(self, parent_id: str) -> bool:
  370. """Check if the given event is the target of another event's relation.
  371. An event is the target of an event relation if it has a valid
  372. m.relates_to with a rel_type and event_id pointing to parent_id in the
  373. content:
  374. {
  375. "content": {
  376. "m.relates_to": {
  377. "rel_type": "m.replace",
  378. "event_id": "$parent_id"
  379. }
  380. }
  381. }
  382. Args:
  383. parent_id: The event to check.
  384. Returns:
  385. True if the event is the target of another event's relation.
  386. """
  387. result = await self.db_pool.simple_select_one_onecol(
  388. table="event_relations",
  389. keyvalues={"relates_to_id": parent_id},
  390. retcol="event_id",
  391. allow_none=True,
  392. desc="event_is_target_of_relation",
  393. )
  394. return result is not None
  395. @cached() # type: ignore[synapse-@cached-mutable]
  396. async def get_references_for_event(self, event_id: str) -> List[JsonDict]:
  397. raise NotImplementedError()
  398. @cachedList(cached_method_name="get_references_for_event", list_name="event_ids")
  399. async def get_references_for_events(
  400. self, event_ids: Collection[str]
  401. ) -> Mapping[str, Optional[Sequence[_RelatedEvent]]]:
  402. """Get a list of references to the given events.
  403. Args:
  404. event_ids: Fetch events that relate to these event IDs.
  405. Returns:
  406. A map of event IDs to a list of related event IDs (and their senders).
  407. """
  408. clause, args = make_in_list_sql_clause(
  409. self.database_engine, "relates_to_id", event_ids
  410. )
  411. args.append(RelationTypes.REFERENCE)
  412. sql = f"""
  413. SELECT relates_to_id, ref.event_id, ref.sender
  414. FROM events AS ref
  415. INNER JOIN event_relations USING (event_id)
  416. INNER JOIN events AS parent ON
  417. parent.event_id = relates_to_id
  418. AND parent.room_id = ref.room_id
  419. WHERE
  420. {clause}
  421. AND relation_type = ?
  422. ORDER BY ref.topological_ordering, ref.stream_ordering
  423. """
  424. def _get_references_for_events_txn(
  425. txn: LoggingTransaction,
  426. ) -> Mapping[str, List[_RelatedEvent]]:
  427. txn.execute(sql, args)
  428. result: Dict[str, List[_RelatedEvent]] = {}
  429. for relates_to_id, event_id, sender in cast(
  430. List[Tuple[str, str, str]], txn
  431. ):
  432. result.setdefault(relates_to_id, []).append(
  433. _RelatedEvent(event_id, sender)
  434. )
  435. return result
  436. return await self.db_pool.runInteraction(
  437. "_get_references_for_events_txn", _get_references_for_events_txn
  438. )
  439. @cached() # type: ignore[synapse-@cached-mutable]
  440. def get_applicable_edit(self, event_id: str) -> Optional[EventBase]:
  441. raise NotImplementedError()
  442. # TODO: This returns a mutable object, which is generally bad.
  443. @cachedList(cached_method_name="get_applicable_edit", list_name="event_ids") # type: ignore[synapse-@cached-mutable]
  444. async def get_applicable_edits(
  445. self, event_ids: Collection[str]
  446. ) -> Mapping[str, Optional[EventBase]]:
  447. """Get the most recent edit (if any) that has happened for the given
  448. events.
  449. Correctly handles checking whether edits were allowed to happen.
  450. Args:
  451. event_ids: The original event IDs
  452. Returns:
  453. A map of the most recent edit for each event. If there are no edits,
  454. the event will map to None.
  455. """
  456. # We only allow edits for events that have the same sender and event type.
  457. # We can't assert these things during regular event auth so we have to do
  458. # the checks post hoc.
  459. # Fetches latest edit that has the same type and sender as the original.
  460. if isinstance(self.database_engine, PostgresEngine):
  461. # The `DISTINCT ON` clause will pick the *first* row it encounters,
  462. # so ordering by origin server ts + event ID desc will ensure we get
  463. # the latest edit.
  464. sql = """
  465. SELECT DISTINCT ON (original.event_id) original.event_id, edit.event_id FROM events AS edit
  466. INNER JOIN event_relations USING (event_id)
  467. INNER JOIN events AS original ON
  468. original.event_id = relates_to_id
  469. AND edit.type = original.type
  470. AND edit.sender = original.sender
  471. AND edit.room_id = original.room_id
  472. WHERE
  473. %s
  474. AND relation_type = ?
  475. ORDER by original.event_id DESC, edit.origin_server_ts DESC, edit.event_id DESC
  476. """
  477. else:
  478. # SQLite uses a simplified query which returns all edits for an
  479. # original event. The results are then de-duplicated when turned into
  480. # a dict. Due to the chosen ordering, the latest edit stomps on
  481. # earlier edits.
  482. sql = """
  483. SELECT original.event_id, edit.event_id FROM events AS edit
  484. INNER JOIN event_relations USING (event_id)
  485. INNER JOIN events AS original ON
  486. original.event_id = relates_to_id
  487. AND edit.type = original.type
  488. AND edit.sender = original.sender
  489. AND edit.room_id = original.room_id
  490. WHERE
  491. %s
  492. AND relation_type = ?
  493. ORDER by edit.origin_server_ts, edit.event_id
  494. """
  495. def _get_applicable_edits_txn(txn: LoggingTransaction) -> Dict[str, str]:
  496. clause, args = make_in_list_sql_clause(
  497. txn.database_engine, "relates_to_id", event_ids
  498. )
  499. args.append(RelationTypes.REPLACE)
  500. txn.execute(sql % (clause,), args)
  501. return dict(cast(Iterable[Tuple[str, str]], txn.fetchall()))
  502. edit_ids = await self.db_pool.runInteraction(
  503. "get_applicable_edits", _get_applicable_edits_txn
  504. )
  505. edits = await self.get_events(edit_ids.values()) # type: ignore[attr-defined]
  506. # Map to the original event IDs to the edit events.
  507. #
  508. # There might not be an edit event due to there being no edits or
  509. # due to the event not being known, either case is treated the same.
  510. return {
  511. original_event_id: edits.get(edit_ids.get(original_event_id))
  512. for original_event_id in event_ids
  513. }
  514. @cached() # type: ignore[synapse-@cached-mutable]
  515. def get_thread_summary(self, event_id: str) -> Optional[Tuple[int, EventBase]]:
  516. raise NotImplementedError()
  517. # TODO: This returns a mutable object, which is generally bad.
  518. @cachedList(cached_method_name="get_thread_summary", list_name="event_ids") # type: ignore[synapse-@cached-mutable]
  519. async def get_thread_summaries(
  520. self, event_ids: Collection[str]
  521. ) -> Mapping[str, Optional[Tuple[int, EventBase]]]:
  522. """Get the number of threaded replies and the latest reply (if any) for the given events.
  523. Args:
  524. event_ids: Summarize the thread related to this event ID.
  525. Returns:
  526. A map of the thread summary each event. A missing event implies there
  527. are no threaded replies.
  528. Each summary is a tuple of:
  529. The number of events in the thread.
  530. The most recent event in the thread.
  531. """
  532. def _get_thread_summaries_txn(
  533. txn: LoggingTransaction,
  534. ) -> Tuple[Dict[str, int], Dict[str, str]]:
  535. # Fetch the count of threaded events and the latest event ID.
  536. # TODO Should this only allow m.room.message events.
  537. if isinstance(self.database_engine, PostgresEngine):
  538. # The `DISTINCT ON` clause will pick the *first* row it encounters,
  539. # so ordering by topological ordering + stream ordering desc will
  540. # ensure we get the latest event in the thread.
  541. sql = """
  542. SELECT DISTINCT ON (parent.event_id) parent.event_id, child.event_id FROM events AS child
  543. INNER JOIN event_relations USING (event_id)
  544. INNER JOIN events AS parent ON
  545. parent.event_id = relates_to_id
  546. AND parent.room_id = child.room_id
  547. WHERE
  548. %s
  549. AND relation_type = ?
  550. ORDER BY parent.event_id, child.topological_ordering DESC, child.stream_ordering DESC
  551. """
  552. else:
  553. # SQLite uses a simplified query which returns all entries for a
  554. # thread. The first result for each thread is chosen to and subsequent
  555. # results for a thread are ignored.
  556. sql = """
  557. SELECT parent.event_id, child.event_id FROM events AS child
  558. INNER JOIN event_relations USING (event_id)
  559. INNER JOIN events AS parent ON
  560. parent.event_id = relates_to_id
  561. AND parent.room_id = child.room_id
  562. WHERE
  563. %s
  564. AND relation_type = ?
  565. ORDER BY child.topological_ordering DESC, child.stream_ordering DESC
  566. """
  567. clause, args = make_in_list_sql_clause(
  568. txn.database_engine, "relates_to_id", event_ids
  569. )
  570. args.append(RelationTypes.THREAD)
  571. txn.execute(sql % (clause,), args)
  572. latest_event_ids = {}
  573. for parent_event_id, child_event_id in txn:
  574. # Only consider the latest threaded reply (by topological ordering).
  575. if parent_event_id not in latest_event_ids:
  576. latest_event_ids[parent_event_id] = child_event_id
  577. # If no threads were found, bail.
  578. if not latest_event_ids:
  579. return {}, latest_event_ids
  580. # Fetch the number of threaded replies.
  581. sql = """
  582. SELECT parent.event_id, COUNT(child.event_id) FROM events AS child
  583. INNER JOIN event_relations USING (event_id)
  584. INNER JOIN events AS parent ON
  585. parent.event_id = relates_to_id
  586. AND parent.room_id = child.room_id
  587. WHERE
  588. %s
  589. AND relation_type = ?
  590. GROUP BY parent.event_id
  591. """
  592. # Regenerate the arguments since only threads found above could
  593. # possibly have any replies.
  594. clause, args = make_in_list_sql_clause(
  595. txn.database_engine, "relates_to_id", latest_event_ids.keys()
  596. )
  597. args.append(RelationTypes.THREAD)
  598. txn.execute(sql % (clause,), args)
  599. counts = dict(cast(List[Tuple[str, int]], txn.fetchall()))
  600. return counts, latest_event_ids
  601. counts, latest_event_ids = await self.db_pool.runInteraction(
  602. "get_thread_summaries", _get_thread_summaries_txn
  603. )
  604. latest_events = await self.get_events(latest_event_ids.values()) # type: ignore[attr-defined]
  605. # Map to the event IDs to the thread summary.
  606. #
  607. # There might not be a summary due to there not being a thread or
  608. # due to the latest event not being known, either case is treated the same.
  609. summaries = {}
  610. for parent_event_id, latest_event_id in latest_event_ids.items():
  611. latest_event = latest_events.get(latest_event_id)
  612. summary = None
  613. if latest_event:
  614. summary = (counts[parent_event_id], latest_event)
  615. summaries[parent_event_id] = summary
  616. return summaries
  617. async def get_threaded_messages_per_user(
  618. self,
  619. event_ids: Collection[str],
  620. users: FrozenSet[str] = frozenset(),
  621. ) -> Dict[Tuple[str, str], int]:
  622. """Get the number of threaded replies for a set of users.
  623. This is used, in conjunction with get_thread_summaries, to calculate an
  624. accurate count of the replies to a thread by subtracting ignored users.
  625. Args:
  626. event_ids: The events to check for threaded replies.
  627. users: The user to calculate the count of their replies.
  628. Returns:
  629. A map of the (event_id, sender) to the count of their replies.
  630. """
  631. if not users:
  632. return {}
  633. # Fetch the number of threaded replies.
  634. sql = """
  635. SELECT parent.event_id, child.sender, COUNT(child.event_id) FROM events AS child
  636. INNER JOIN event_relations USING (event_id)
  637. INNER JOIN events AS parent ON
  638. parent.event_id = relates_to_id
  639. AND parent.room_id = child.room_id
  640. WHERE
  641. relation_type = ?
  642. AND %s
  643. AND %s
  644. GROUP BY parent.event_id, child.sender
  645. """
  646. def _get_threaded_messages_per_user_txn(
  647. txn: LoggingTransaction,
  648. ) -> Dict[Tuple[str, str], int]:
  649. users_sql, users_args = make_in_list_sql_clause(
  650. self.database_engine, "child.sender", users
  651. )
  652. events_clause, events_args = make_in_list_sql_clause(
  653. txn.database_engine, "relates_to_id", event_ids
  654. )
  655. txn.execute(
  656. sql % (users_sql, events_clause),
  657. [RelationTypes.THREAD] + users_args + events_args,
  658. )
  659. return {(row[0], row[1]): row[2] for row in txn}
  660. return await self.db_pool.runInteraction(
  661. "get_threaded_messages_per_user", _get_threaded_messages_per_user_txn
  662. )
  663. @cached()
  664. def get_thread_participated(self, event_id: str, user_id: str) -> bool:
  665. raise NotImplementedError()
  666. @cachedList(cached_method_name="get_thread_participated", list_name="event_ids")
  667. async def get_threads_participated(
  668. self, event_ids: Collection[str], user_id: str
  669. ) -> Mapping[str, bool]:
  670. """Get whether the requesting user participated in the given threads.
  671. This is separate from get_thread_summaries since that can be cached across
  672. all users while this value is specific to the requester.
  673. Args:
  674. event_ids: The thread related to these event IDs.
  675. user_id: The user requesting the summary.
  676. Returns:
  677. A map of event ID to a boolean which represents if the requesting
  678. user participated in that event's thread, otherwise false.
  679. """
  680. def _get_threads_participated_txn(txn: LoggingTransaction) -> Set[str]:
  681. # Fetch whether the requester has participated or not.
  682. sql = """
  683. SELECT DISTINCT relates_to_id
  684. FROM events AS child
  685. INNER JOIN event_relations USING (event_id)
  686. INNER JOIN events AS parent ON
  687. parent.event_id = relates_to_id
  688. AND parent.room_id = child.room_id
  689. WHERE
  690. %s
  691. AND relation_type = ?
  692. AND child.sender = ?
  693. """
  694. clause, args = make_in_list_sql_clause(
  695. txn.database_engine, "relates_to_id", event_ids
  696. )
  697. args.extend([RelationTypes.THREAD, user_id])
  698. txn.execute(sql % (clause,), args)
  699. return {row[0] for row in txn.fetchall()}
  700. participated_threads = await self.db_pool.runInteraction(
  701. "get_threads_participated", _get_threads_participated_txn
  702. )
  703. return {event_id: event_id in participated_threads for event_id in event_ids}
  704. async def events_have_relations(
  705. self,
  706. parent_ids: List[str],
  707. relation_senders: Optional[List[str]],
  708. relation_types: Optional[List[str]],
  709. ) -> List[str]:
  710. """Check which events have a relationship from the given senders of the
  711. given types.
  712. Args:
  713. parent_ids: The events being annotated
  714. relation_senders: The relation senders to check.
  715. relation_types: The relation types to check.
  716. Returns:
  717. True if the event has at least one relationship from one of the given senders of the given type.
  718. """
  719. # If no restrictions are given then the event has the required relations.
  720. if not relation_senders and not relation_types:
  721. return parent_ids
  722. sql = """
  723. SELECT relates_to_id FROM event_relations
  724. INNER JOIN events USING (event_id)
  725. WHERE
  726. %s;
  727. """
  728. def _get_if_events_have_relations(txn: LoggingTransaction) -> List[str]:
  729. clauses: List[str] = []
  730. clause, args = make_in_list_sql_clause(
  731. txn.database_engine, "relates_to_id", parent_ids
  732. )
  733. clauses.append(clause)
  734. if relation_senders:
  735. clause, temp_args = make_in_list_sql_clause(
  736. txn.database_engine, "sender", relation_senders
  737. )
  738. clauses.append(clause)
  739. args.extend(temp_args)
  740. if relation_types:
  741. clause, temp_args = make_in_list_sql_clause(
  742. txn.database_engine, "relation_type", relation_types
  743. )
  744. clauses.append(clause)
  745. args.extend(temp_args)
  746. txn.execute(sql % " AND ".join(clauses), args)
  747. return [row[0] for row in txn]
  748. return await self.db_pool.runInteraction(
  749. "get_if_events_have_relations", _get_if_events_have_relations
  750. )
  751. async def has_user_annotated_event(
  752. self, parent_id: str, event_type: str, aggregation_key: str, sender: str
  753. ) -> bool:
  754. """Check if a user has already annotated an event with the same key
  755. (e.g. already liked an event).
  756. Args:
  757. parent_id: The event being annotated
  758. event_type: The event type of the annotation
  759. aggregation_key: The aggregation key of the annotation
  760. sender: The sender of the annotation
  761. Returns:
  762. True if the event is already annotated.
  763. """
  764. sql = """
  765. SELECT 1 FROM event_relations
  766. INNER JOIN events USING (event_id)
  767. WHERE
  768. relates_to_id = ?
  769. AND relation_type = ?
  770. AND type = ?
  771. AND sender = ?
  772. AND aggregation_key = ?
  773. LIMIT 1;
  774. """
  775. def _get_if_user_has_annotated_event(txn: LoggingTransaction) -> bool:
  776. txn.execute(
  777. sql,
  778. (
  779. parent_id,
  780. RelationTypes.ANNOTATION,
  781. event_type,
  782. sender,
  783. aggregation_key,
  784. ),
  785. )
  786. return bool(txn.fetchone())
  787. return await self.db_pool.runInteraction(
  788. "get_if_user_has_annotated_event", _get_if_user_has_annotated_event
  789. )
  790. @cached(tree=True)
  791. async def get_threads(
  792. self,
  793. room_id: str,
  794. limit: int = 5,
  795. from_token: Optional[ThreadsNextBatch] = None,
  796. ) -> Tuple[Sequence[str], Optional[ThreadsNextBatch]]:
  797. """Get a list of thread IDs, ordered by topological ordering of their
  798. latest reply.
  799. Args:
  800. room_id: The room the event belongs to.
  801. limit: Only fetch the most recent `limit` threads.
  802. from_token: Fetch rows from a previous next_batch, or from the start if None.
  803. Returns:
  804. A tuple of:
  805. A list of thread root event IDs.
  806. The next_batch, if one exists.
  807. """
  808. # Generate the pagination clause, if necessary.
  809. #
  810. # Find any threads where the latest reply is equal / before the last
  811. # thread's topo ordering and earlier in stream ordering.
  812. pagination_clause = ""
  813. pagination_args: tuple = ()
  814. if from_token:
  815. pagination_clause = "AND topological_ordering <= ? AND stream_ordering < ?"
  816. pagination_args = (
  817. from_token.topological_ordering,
  818. from_token.stream_ordering,
  819. )
  820. sql = f"""
  821. SELECT thread_id, topological_ordering, stream_ordering
  822. FROM threads
  823. WHERE
  824. room_id = ?
  825. {pagination_clause}
  826. ORDER BY topological_ordering DESC, stream_ordering DESC
  827. LIMIT ?
  828. """
  829. def _get_threads_txn(
  830. txn: LoggingTransaction,
  831. ) -> Tuple[List[str], Optional[ThreadsNextBatch]]:
  832. txn.execute(sql, (room_id, *pagination_args, limit + 1))
  833. rows = cast(List[Tuple[str, int, int]], txn.fetchall())
  834. thread_ids = [r[0] for r in rows]
  835. # If there are more events, generate the next pagination key from the
  836. # last thread which will be returned.
  837. next_token = None
  838. if len(thread_ids) > limit:
  839. last_topo_id = rows[-2][1]
  840. last_stream_id = rows[-2][2]
  841. next_token = ThreadsNextBatch(last_topo_id, last_stream_id)
  842. return thread_ids[:limit], next_token
  843. return await self.db_pool.runInteraction("get_threads", _get_threads_txn)
  844. @cached()
  845. async def get_thread_id(self, event_id: str) -> str:
  846. """
  847. Get the thread ID for an event. This considers multi-level relations,
  848. e.g. an annotation to an event which is part of a thread.
  849. It only searches up the relations tree, i.e. it only searches for events
  850. which the given event is related to (and which those events are related
  851. to, etc.)
  852. Given the following DAG:
  853. A <---[m.thread]-- B <--[m.annotation]-- C
  854. ^
  855. |--[m.reference]-- D <--[m.annotation]-- E
  856. get_thread_id(X) considers events B and C as part of thread A.
  857. See also get_thread_id_for_receipts.
  858. Args:
  859. event_id: The event ID to fetch the thread ID for.
  860. Returns:
  861. The event ID of the root event in the thread, if this event is part
  862. of a thread. "main", otherwise.
  863. """
  864. # Recurse event relations up to the *root* event, then search that chain
  865. # of relations for a thread relation. If one is found, the root event is
  866. # returned.
  867. #
  868. # Note that this should only ever find 0 or 1 entries since it is invalid
  869. # for an event to have a thread relation to an event which also has a
  870. # relation.
  871. sql = """
  872. WITH RECURSIVE related_events AS (
  873. SELECT event_id, relates_to_id, relation_type, 0 AS depth
  874. FROM event_relations
  875. WHERE event_id = ?
  876. UNION SELECT e.event_id, e.relates_to_id, e.relation_type, depth + 1
  877. FROM event_relations e
  878. INNER JOIN related_events r ON r.relates_to_id = e.event_id
  879. WHERE depth <= 3
  880. )
  881. SELECT relates_to_id FROM related_events
  882. WHERE relation_type = 'm.thread'
  883. ORDER BY depth DESC
  884. LIMIT 1;
  885. """
  886. def _get_thread_id(txn: LoggingTransaction) -> str:
  887. txn.execute(sql, (event_id,))
  888. row = txn.fetchone()
  889. if row:
  890. return row[0]
  891. # If no thread was found, it is part of the main timeline.
  892. return MAIN_TIMELINE
  893. return await self.db_pool.runInteraction("get_thread_id", _get_thread_id)
  894. @cached()
  895. async def get_thread_id_for_receipts(self, event_id: str) -> str:
  896. """
  897. Get the thread ID for an event by traversing to the top-most related event
  898. and confirming any children events form a thread.
  899. Given the following DAG:
  900. A <---[m.thread]-- B <--[m.annotation]-- C
  901. ^
  902. |--[m.reference]-- D <--[m.annotation]-- E
  903. get_thread_id_for_receipts(X) considers events A, B, C, D, and E as part
  904. of thread A.
  905. See also get_thread_id.
  906. Args:
  907. event_id: The event ID to fetch the thread ID for.
  908. Returns:
  909. The event ID of the root event in the thread, if this event is part
  910. of a thread. "main", otherwise.
  911. """
  912. # Recurse event relations up to the *root* event, then search for any events
  913. # related to that root node for a thread relation. If one is found, the
  914. # root event is returned.
  915. #
  916. # Note that there cannot be thread relations in the middle of the chain since
  917. # it is invalid for an event to have a thread relation to an event which also
  918. # has a relation.
  919. sql = """
  920. SELECT relates_to_id FROM event_relations WHERE relates_to_id = COALESCE((
  921. WITH RECURSIVE related_events AS (
  922. SELECT event_id, relates_to_id, relation_type, 0 AS depth
  923. FROM event_relations
  924. WHERE event_id = ?
  925. UNION SELECT e.event_id, e.relates_to_id, e.relation_type, depth + 1
  926. FROM event_relations e
  927. INNER JOIN related_events r ON r.relates_to_id = e.event_id
  928. WHERE depth <= 3
  929. )
  930. SELECT relates_to_id FROM related_events
  931. ORDER BY depth DESC
  932. LIMIT 1
  933. ), ?) AND relation_type = 'm.thread' LIMIT 1;
  934. """
  935. def _get_related_thread_id(txn: LoggingTransaction) -> str:
  936. txn.execute(sql, (event_id, event_id))
  937. row = txn.fetchone()
  938. if row:
  939. return row[0]
  940. # If no thread was found, it is part of the main timeline.
  941. return MAIN_TIMELINE
  942. return await self.db_pool.runInteraction(
  943. "get_related_thread_id", _get_related_thread_id
  944. )
  945. class RelationsStore(RelationsWorkerStore):
  946. pass