relations.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. import attr
  17. from twisted.internet import defer
  18. from synapse.api.constants import RelationTypes
  19. from synapse.api.errors import SynapseError
  20. from synapse.storage._base import SQLBaseStore
  21. from synapse.storage.stream import generate_pagination_where_clause
  22. from synapse.util.caches.descriptors import cached, cachedInlineCallbacks
  23. logger = logging.getLogger(__name__)
  24. @attr.s
  25. class PaginationChunk(object):
  26. """Returned by relation pagination APIs.
  27. Attributes:
  28. chunk (list): The rows returned by pagination
  29. next_batch (Any|None): Token to fetch next set of results with, if
  30. None then there are no more results.
  31. prev_batch (Any|None): Token to fetch previous set of results with, if
  32. None then there are no previous results.
  33. """
  34. chunk = attr.ib()
  35. next_batch = attr.ib(default=None)
  36. prev_batch = attr.ib(default=None)
  37. def to_dict(self):
  38. d = {"chunk": self.chunk}
  39. if self.next_batch:
  40. d["next_batch"] = self.next_batch.to_string()
  41. if self.prev_batch:
  42. d["prev_batch"] = self.prev_batch.to_string()
  43. return d
  44. @attr.s(frozen=True, slots=True)
  45. class RelationPaginationToken(object):
  46. """Pagination token for relation pagination API.
  47. As the results are order by topological ordering, we can use the
  48. `topological_ordering` and `stream_ordering` fields of the events at the
  49. boundaries of the chunk as pagination tokens.
  50. Attributes:
  51. topological (int): The topological ordering of the boundary event
  52. stream (int): The stream ordering of the boundary event.
  53. """
  54. topological = attr.ib()
  55. stream = attr.ib()
  56. @staticmethod
  57. def from_string(string):
  58. try:
  59. t, s = string.split("-")
  60. return RelationPaginationToken(int(t), int(s))
  61. except ValueError:
  62. raise SynapseError(400, "Invalid token")
  63. def to_string(self):
  64. return "%d-%d" % (self.topological, self.stream)
  65. def as_tuple(self):
  66. return attr.astuple(self)
  67. @attr.s(frozen=True, slots=True)
  68. class AggregationPaginationToken(object):
  69. """Pagination token for relation aggregation pagination API.
  70. As the results are order by count and then MAX(stream_ordering) of the
  71. aggregation groups, we can just use them as our pagination token.
  72. Attributes:
  73. count (int): The count of relations in the boundar group.
  74. stream (int): The MAX stream ordering in the boundary group.
  75. """
  76. count = attr.ib()
  77. stream = attr.ib()
  78. @staticmethod
  79. def from_string(string):
  80. try:
  81. c, s = string.split("-")
  82. return AggregationPaginationToken(int(c), int(s))
  83. except ValueError:
  84. raise SynapseError(400, "Invalid token")
  85. def to_string(self):
  86. return "%d-%d" % (self.count, self.stream)
  87. def as_tuple(self):
  88. return attr.astuple(self)
  89. class RelationsWorkerStore(SQLBaseStore):
  90. @cached(tree=True)
  91. def get_relations_for_event(
  92. self,
  93. event_id,
  94. relation_type=None,
  95. event_type=None,
  96. aggregation_key=None,
  97. limit=5,
  98. direction="b",
  99. from_token=None,
  100. to_token=None,
  101. ):
  102. """Get a list of relations for an event, ordered by topological ordering.
  103. Args:
  104. event_id (str): Fetch events that relate to this event ID.
  105. relation_type (str|None): Only fetch events with this relation
  106. type, if given.
  107. event_type (str|None): Only fetch events with this event type, if
  108. given.
  109. aggregation_key (str|None): Only fetch events with this aggregation
  110. key, if given.
  111. limit (int): Only fetch the most recent `limit` events.
  112. direction (str): Whether to fetch the most recent first (`"b"`) or
  113. the oldest first (`"f"`).
  114. from_token (RelationPaginationToken|None): Fetch rows from the given
  115. token, or from the start if None.
  116. to_token (RelationPaginationToken|None): Fetch rows up to the given
  117. token, or up to the end if None.
  118. Returns:
  119. Deferred[PaginationChunk]: List of event IDs that match relations
  120. requested. The rows are of the form `{"event_id": "..."}`.
  121. """
  122. where_clause = ["relates_to_id = ?"]
  123. where_args = [event_id]
  124. if relation_type is not None:
  125. where_clause.append("relation_type = ?")
  126. where_args.append(relation_type)
  127. if event_type is not None:
  128. where_clause.append("type = ?")
  129. where_args.append(event_type)
  130. if aggregation_key:
  131. where_clause.append("aggregation_key = ?")
  132. where_args.append(aggregation_key)
  133. pagination_clause = generate_pagination_where_clause(
  134. direction=direction,
  135. column_names=("topological_ordering", "stream_ordering"),
  136. from_token=attr.astuple(from_token) if from_token else None,
  137. to_token=attr.astuple(to_token) if to_token else None,
  138. engine=self.database_engine,
  139. )
  140. if pagination_clause:
  141. where_clause.append(pagination_clause)
  142. if direction == "b":
  143. order = "DESC"
  144. else:
  145. order = "ASC"
  146. sql = """
  147. SELECT event_id, topological_ordering, stream_ordering
  148. FROM event_relations
  149. INNER JOIN events USING (event_id)
  150. WHERE %s
  151. ORDER BY topological_ordering %s, stream_ordering %s
  152. LIMIT ?
  153. """ % (
  154. " AND ".join(where_clause),
  155. order,
  156. order,
  157. )
  158. def _get_recent_references_for_event_txn(txn):
  159. txn.execute(sql, where_args + [limit + 1])
  160. last_topo_id = None
  161. last_stream_id = None
  162. events = []
  163. for row in txn:
  164. events.append({"event_id": row[0]})
  165. last_topo_id = row[1]
  166. last_stream_id = row[2]
  167. next_batch = None
  168. if len(events) > limit and last_topo_id and last_stream_id:
  169. next_batch = RelationPaginationToken(last_topo_id, last_stream_id)
  170. return PaginationChunk(
  171. chunk=list(events[:limit]), next_batch=next_batch, prev_batch=from_token
  172. )
  173. return self.runInteraction(
  174. "get_recent_references_for_event", _get_recent_references_for_event_txn
  175. )
  176. @cached(tree=True)
  177. def get_aggregation_groups_for_event(
  178. self,
  179. event_id,
  180. event_type=None,
  181. limit=5,
  182. direction="b",
  183. from_token=None,
  184. to_token=None,
  185. ):
  186. """Get a list of annotations on the event, grouped by event type and
  187. aggregation key, sorted by count.
  188. This is used e.g. to get the what and how many reactions have happend
  189. on an event.
  190. Args:
  191. event_id (str): Fetch events that relate to this event ID.
  192. event_type (str|None): Only fetch events with this event type, if
  193. given.
  194. limit (int): Only fetch the `limit` groups.
  195. direction (str): Whether to fetch the highest count first (`"b"`) or
  196. the lowest count first (`"f"`).
  197. from_token (AggregationPaginationToken|None): Fetch rows from the
  198. given token, or from the start if None.
  199. to_token (AggregationPaginationToken|None): Fetch rows up to the
  200. given token, or up to the end if None.
  201. Returns:
  202. Deferred[PaginationChunk]: List of groups of annotations that
  203. match. Each row is a dict with `type`, `key` and `count` fields.
  204. """
  205. where_clause = ["relates_to_id = ?", "relation_type = ?"]
  206. where_args = [event_id, RelationTypes.ANNOTATION]
  207. if event_type:
  208. where_clause.append("type = ?")
  209. where_args.append(event_type)
  210. having_clause = generate_pagination_where_clause(
  211. direction=direction,
  212. column_names=("COUNT(*)", "MAX(stream_ordering)"),
  213. from_token=attr.astuple(from_token) if from_token else None,
  214. to_token=attr.astuple(to_token) if to_token else None,
  215. engine=self.database_engine,
  216. )
  217. if direction == "b":
  218. order = "DESC"
  219. else:
  220. order = "ASC"
  221. if having_clause:
  222. having_clause = "HAVING " + having_clause
  223. else:
  224. having_clause = ""
  225. sql = """
  226. SELECT type, aggregation_key, COUNT(*), MAX(stream_ordering)
  227. FROM event_relations
  228. INNER JOIN events USING (event_id)
  229. WHERE {where_clause}
  230. GROUP BY relation_type, type, aggregation_key
  231. {having_clause}
  232. ORDER BY COUNT(*) {order}, MAX(stream_ordering) {order}
  233. LIMIT ?
  234. """.format(
  235. where_clause=" AND ".join(where_clause),
  236. order=order,
  237. having_clause=having_clause,
  238. )
  239. def _get_aggregation_groups_for_event_txn(txn):
  240. txn.execute(sql, where_args + [limit + 1])
  241. next_batch = None
  242. events = []
  243. for row in txn:
  244. events.append({"type": row[0], "key": row[1], "count": row[2]})
  245. next_batch = AggregationPaginationToken(row[2], row[3])
  246. if len(events) <= limit:
  247. next_batch = None
  248. return PaginationChunk(
  249. chunk=list(events[:limit]), next_batch=next_batch, prev_batch=from_token
  250. )
  251. return self.runInteraction(
  252. "get_aggregation_groups_for_event", _get_aggregation_groups_for_event_txn
  253. )
  254. @cachedInlineCallbacks()
  255. def get_applicable_edit(self, event_id):
  256. """Get the most recent edit (if any) that has happened for the given
  257. event.
  258. Correctly handles checking whether edits were allowed to happen.
  259. Args:
  260. event_id (str): The original event ID
  261. Returns:
  262. Deferred[EventBase|None]: Returns the most recent edit, if any.
  263. """
  264. # We only allow edits for `m.room.message` events that have the same sender
  265. # and event type. We can't assert these things during regular event auth so
  266. # we have to do the checks post hoc.
  267. # Fetches latest edit that has the same type and sender as the
  268. # original, and is an `m.room.message`.
  269. sql = """
  270. SELECT edit.event_id FROM events AS edit
  271. INNER JOIN event_relations USING (event_id)
  272. INNER JOIN events AS original ON
  273. original.event_id = relates_to_id
  274. AND edit.type = original.type
  275. AND edit.sender = original.sender
  276. WHERE
  277. relates_to_id = ?
  278. AND relation_type = ?
  279. AND edit.type = 'm.room.message'
  280. ORDER by edit.origin_server_ts DESC, edit.event_id DESC
  281. LIMIT 1
  282. """
  283. def _get_applicable_edit_txn(txn):
  284. txn.execute(sql, (event_id, RelationTypes.REPLACE))
  285. row = txn.fetchone()
  286. if row:
  287. return row[0]
  288. edit_id = yield self.runInteraction(
  289. "get_applicable_edit", _get_applicable_edit_txn
  290. )
  291. if not edit_id:
  292. return
  293. edit_event = yield self.get_event(edit_id, allow_none=True)
  294. defer.returnValue(edit_event)
  295. def has_user_annotated_event(self, parent_id, event_type, aggregation_key, sender):
  296. """Check if a user has already annotated an event with the same key
  297. (e.g. already liked an event).
  298. Args:
  299. parent_id (str): The event being annotated
  300. event_type (str): The event type of the annotation
  301. aggregation_key (str): The aggregation key of the annotation
  302. sender (str): The sender of the annotation
  303. Returns:
  304. Deferred[bool]
  305. """
  306. sql = """
  307. SELECT 1 FROM event_relations
  308. INNER JOIN events USING (event_id)
  309. WHERE
  310. relates_to_id = ?
  311. AND relation_type = ?
  312. AND type = ?
  313. AND sender = ?
  314. AND aggregation_key = ?
  315. LIMIT 1;
  316. """
  317. def _get_if_user_has_annotated_event(txn):
  318. txn.execute(
  319. sql,
  320. (
  321. parent_id,
  322. RelationTypes.ANNOTATION,
  323. event_type,
  324. sender,
  325. aggregation_key,
  326. ),
  327. )
  328. return bool(txn.fetchone())
  329. return self.runInteraction(
  330. "get_if_user_has_annotated_event", _get_if_user_has_annotated_event
  331. )
  332. class RelationsStore(RelationsWorkerStore):
  333. def _handle_event_relations(self, txn, event):
  334. """Handles inserting relation data during peristence of events
  335. Args:
  336. txn
  337. event (EventBase)
  338. """
  339. relation = event.content.get("m.relates_to")
  340. if not relation:
  341. # No relations
  342. return
  343. rel_type = relation.get("rel_type")
  344. if rel_type not in (
  345. RelationTypes.ANNOTATION,
  346. RelationTypes.REFERENCE,
  347. RelationTypes.REPLACE,
  348. ):
  349. # Unknown relation type
  350. return
  351. parent_id = relation.get("event_id")
  352. if not parent_id:
  353. # Invalid relation
  354. return
  355. aggregation_key = relation.get("key")
  356. self._simple_insert_txn(
  357. txn,
  358. table="event_relations",
  359. values={
  360. "event_id": event.event_id,
  361. "relates_to_id": parent_id,
  362. "relation_type": rel_type,
  363. "aggregation_key": aggregation_key,
  364. },
  365. )
  366. txn.call_after(self.get_relations_for_event.invalidate_many, (parent_id,))
  367. txn.call_after(
  368. self.get_aggregation_groups_for_event.invalidate_many, (parent_id,)
  369. )
  370. if rel_type == RelationTypes.REPLACE:
  371. txn.call_after(self.get_applicable_edit.invalidate, (parent_id,))
  372. def _handle_redaction(self, txn, redacted_event_id):
  373. """Handles receiving a redaction and checking whether we need to remove
  374. any redacted relations from the database.
  375. Args:
  376. txn
  377. redacted_event_id (str): The event that was redacted.
  378. """
  379. self._simple_delete_txn(
  380. txn,
  381. table="event_relations",
  382. keyvalues={
  383. "event_id": redacted_event_id,
  384. }
  385. )