tags.py 10 KB

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