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.
 
 
 
 
 
 

313 lines
11 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector Ltd
  3. # Copyright 2021 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. from typing import Any, Dict, Iterable, List, Tuple, cast
  18. from synapse.replication.tcp.streams import TagAccountDataStream
  19. from synapse.storage._base import db_to_json
  20. from synapse.storage.database import LoggingTransaction
  21. from synapse.storage.databases.main.account_data import AccountDataWorkerStore
  22. from synapse.storage.util.id_generators import AbstractStreamIdGenerator
  23. from synapse.types import JsonDict
  24. from synapse.util import json_encoder
  25. from synapse.util.caches.descriptors import cached
  26. logger = logging.getLogger(__name__)
  27. class TagsWorkerStore(AccountDataWorkerStore):
  28. @cached()
  29. async def get_tags_for_user(self, user_id: str) -> Dict[str, Dict[str, JsonDict]]:
  30. """Get all the tags for a user.
  31. Args:
  32. user_id: The user to get the tags for.
  33. Returns:
  34. A mapping from room_id strings to dicts mapping from tag strings to
  35. tag content.
  36. """
  37. rows = await self.db_pool.simple_select_list(
  38. "room_tags", {"user_id": user_id}, ["room_id", "tag", "content"]
  39. )
  40. tags_by_room: Dict[str, Dict[str, JsonDict]] = {}
  41. for row in rows:
  42. room_tags = tags_by_room.setdefault(row["room_id"], {})
  43. room_tags[row["tag"]] = db_to_json(row["content"])
  44. return tags_by_room
  45. async def get_all_updated_tags(
  46. self, instance_name: str, last_id: int, current_id: int, limit: int
  47. ) -> Tuple[List[Tuple[int, Tuple[str, str, str]]], int, bool]:
  48. """Get updates for tags replication stream.
  49. Args:
  50. instance_name: The writer we want to fetch updates from. Unused
  51. here since there is only ever one writer.
  52. last_id: The token to fetch updates from. Exclusive.
  53. current_id: The token to fetch updates up to. Inclusive.
  54. limit: The requested limit for the number of rows to return. The
  55. function may return more or fewer rows.
  56. Returns:
  57. A tuple consisting of: the updates, a token to use to fetch
  58. subsequent updates, and whether we returned fewer rows than exists
  59. between the requested tokens due to the limit.
  60. The token returned can be used in a subsequent call to this
  61. function to get further updatees.
  62. The updates are a list of 2-tuples of stream ID and the row data
  63. """
  64. if last_id == current_id:
  65. return [], current_id, False
  66. def get_all_updated_tags_txn(
  67. txn: LoggingTransaction,
  68. ) -> List[Tuple[int, str, str]]:
  69. sql = (
  70. "SELECT stream_id, user_id, room_id"
  71. " FROM room_tags_revisions as r"
  72. " WHERE ? < stream_id AND stream_id <= ?"
  73. " ORDER BY stream_id ASC LIMIT ?"
  74. )
  75. txn.execute(sql, (last_id, current_id, limit))
  76. # mypy doesn't understand what the query is selecting.
  77. return cast(List[Tuple[int, str, str]], txn.fetchall())
  78. tag_ids = await self.db_pool.runInteraction(
  79. "get_all_updated_tags", get_all_updated_tags_txn
  80. )
  81. def get_tag_content(
  82. txn: LoggingTransaction, tag_ids: List[Tuple[int, str, str]]
  83. ) -> List[Tuple[int, Tuple[str, str, str]]]:
  84. sql = "SELECT tag, content FROM room_tags WHERE user_id=? AND room_id=?"
  85. results = []
  86. for stream_id, user_id, room_id in tag_ids:
  87. txn.execute(sql, (user_id, room_id))
  88. tags = []
  89. for tag, content in txn:
  90. tags.append(json_encoder.encode(tag) + ":" + content)
  91. tag_json = "{" + ",".join(tags) + "}"
  92. results.append((stream_id, (user_id, room_id, tag_json)))
  93. return results
  94. batch_size = 50
  95. results = []
  96. for i in range(0, len(tag_ids), batch_size):
  97. tags = await self.db_pool.runInteraction(
  98. "get_all_updated_tag_content",
  99. get_tag_content,
  100. tag_ids[i : i + batch_size],
  101. )
  102. results.extend(tags)
  103. limited = False
  104. upto_token = current_id
  105. if len(results) >= limit:
  106. upto_token = results[-1][0]
  107. limited = True
  108. return results, upto_token, limited
  109. async def get_updated_tags(
  110. self, user_id: str, stream_id: int
  111. ) -> Dict[str, Dict[str, JsonDict]]:
  112. """Get all the tags for the rooms where the tags have changed since the
  113. given version
  114. Args:
  115. user_id: The user to get the tags for.
  116. stream_id: The earliest update to get for the user.
  117. Returns:
  118. A mapping from room_id strings to lists of tag strings for all the
  119. rooms that changed since the stream_id token.
  120. """
  121. def get_updated_tags_txn(txn: LoggingTransaction) -> List[str]:
  122. sql = (
  123. "SELECT room_id from room_tags_revisions"
  124. " WHERE user_id = ? AND stream_id > ?"
  125. )
  126. txn.execute(sql, (user_id, stream_id))
  127. room_ids = [row[0] for row in txn]
  128. return room_ids
  129. changed = self._account_data_stream_cache.has_entity_changed(
  130. user_id, int(stream_id)
  131. )
  132. if not changed:
  133. return {}
  134. room_ids = await self.db_pool.runInteraction(
  135. "get_updated_tags", get_updated_tags_txn
  136. )
  137. results = {}
  138. if room_ids:
  139. tags_by_room = await self.get_tags_for_user(user_id)
  140. for room_id in room_ids:
  141. results[room_id] = tags_by_room.get(room_id, {})
  142. return results
  143. async def get_tags_for_room(
  144. self, user_id: str, room_id: str
  145. ) -> Dict[str, JsonDict]:
  146. """Get all the tags for the given room
  147. Args:
  148. user_id: The user to get tags for
  149. room_id: The room to get tags for
  150. Returns:
  151. A mapping of tags to tag content.
  152. """
  153. rows = await self.db_pool.simple_select_list(
  154. table="room_tags",
  155. keyvalues={"user_id": user_id, "room_id": room_id},
  156. retcols=("tag", "content"),
  157. desc="get_tags_for_room",
  158. )
  159. return {row["tag"]: db_to_json(row["content"]) for row in rows}
  160. async def add_tag_to_room(
  161. self, user_id: str, room_id: str, tag: str, content: JsonDict
  162. ) -> int:
  163. """Add a tag to a room for a user.
  164. Args:
  165. user_id: The user to add a tag for.
  166. room_id: The room to add a tag for.
  167. tag: The tag name to add.
  168. content: A json object to associate with the tag.
  169. Returns:
  170. The next account data ID.
  171. """
  172. assert self._can_write_to_account_data
  173. assert isinstance(self._account_data_id_gen, AbstractStreamIdGenerator)
  174. content_json = json_encoder.encode(content)
  175. def add_tag_txn(txn: LoggingTransaction, next_id: int) -> None:
  176. self.db_pool.simple_upsert_txn(
  177. txn,
  178. table="room_tags",
  179. keyvalues={"user_id": user_id, "room_id": room_id, "tag": tag},
  180. values={"content": content_json},
  181. )
  182. self._update_revision_txn(txn, user_id, room_id, next_id)
  183. async with self._account_data_id_gen.get_next() as next_id:
  184. await self.db_pool.runInteraction("add_tag", add_tag_txn, next_id)
  185. self.get_tags_for_user.invalidate((user_id,))
  186. return self._account_data_id_gen.get_current_token()
  187. async def remove_tag_from_room(self, user_id: str, room_id: str, tag: str) -> int:
  188. """Remove a tag from a room for a user.
  189. Returns:
  190. The next account data ID.
  191. """
  192. assert self._can_write_to_account_data
  193. assert isinstance(self._account_data_id_gen, AbstractStreamIdGenerator)
  194. def remove_tag_txn(txn: LoggingTransaction, next_id: int) -> None:
  195. sql = (
  196. "DELETE FROM room_tags "
  197. " WHERE user_id = ? AND room_id = ? AND tag = ?"
  198. )
  199. txn.execute(sql, (user_id, room_id, tag))
  200. self._update_revision_txn(txn, user_id, room_id, next_id)
  201. async with self._account_data_id_gen.get_next() as next_id:
  202. await self.db_pool.runInteraction("remove_tag", remove_tag_txn, next_id)
  203. self.get_tags_for_user.invalidate((user_id,))
  204. return self._account_data_id_gen.get_current_token()
  205. def _update_revision_txn(
  206. self, txn: LoggingTransaction, user_id: str, room_id: str, next_id: int
  207. ) -> None:
  208. """Update the latest revision of the tags for the given user and room.
  209. Args:
  210. txn: The database cursor
  211. user_id: The ID of the user.
  212. room_id: The ID of the room.
  213. next_id: The the revision to advance to.
  214. """
  215. assert self._can_write_to_account_data
  216. assert isinstance(self._account_data_id_gen, AbstractStreamIdGenerator)
  217. txn.call_after(
  218. self._account_data_stream_cache.entity_has_changed, user_id, next_id
  219. )
  220. update_sql = (
  221. "UPDATE room_tags_revisions"
  222. " SET stream_id = ?"
  223. " WHERE user_id = ?"
  224. " AND room_id = ?"
  225. )
  226. txn.execute(update_sql, (next_id, user_id, room_id))
  227. if txn.rowcount == 0:
  228. insert_sql = (
  229. "INSERT INTO room_tags_revisions (user_id, room_id, stream_id)"
  230. " VALUES (?, ?, ?)"
  231. )
  232. try:
  233. txn.execute(insert_sql, (user_id, room_id, next_id))
  234. except self.database_engine.module.IntegrityError:
  235. # Ignore insertion errors. It doesn't matter if the row wasn't
  236. # inserted because if two updates happend concurrently the one
  237. # with the higher stream_id will not be reported to a client
  238. # unless the previous update has completed. It doesn't matter
  239. # which stream_id ends up in the table, as long as it is higher
  240. # than the id that the client has.
  241. pass
  242. def process_replication_rows(
  243. self,
  244. stream_name: str,
  245. instance_name: str,
  246. token: int,
  247. rows: Iterable[Any],
  248. ) -> None:
  249. if stream_name == TagAccountDataStream.NAME:
  250. self._account_data_id_gen.advance(instance_name, token)
  251. for row in rows:
  252. self.get_tags_for_user.invalidate((row.user_id,))
  253. self._account_data_stream_cache.entity_has_changed(row.user_id, token)
  254. super().process_replication_rows(stream_name, instance_name, token, rows)
  255. class TagsStore(TagsWorkerStore):
  256. pass