Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

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