tags.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  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 List, Tuple
  18. from canonicaljson import json
  19. from twisted.internet import defer
  20. from synapse.storage._base import db_to_json
  21. from synapse.storage.databases.main.account_data import AccountDataWorkerStore
  22. from synapse.util.caches.descriptors import cached
  23. logger = logging.getLogger(__name__)
  24. class TagsWorkerStore(AccountDataWorkerStore):
  25. @cached()
  26. def get_tags_for_user(self, user_id):
  27. """Get all the tags for a user.
  28. Args:
  29. user_id(str): The user to get the tags for.
  30. Returns:
  31. A deferred dict mapping from room_id strings to dicts mapping from
  32. tag strings to tag content.
  33. """
  34. deferred = self.db_pool.simple_select_list(
  35. "room_tags", {"user_id": user_id}, ["room_id", "tag", "content"]
  36. )
  37. @deferred.addCallback
  38. def tags_by_room(rows):
  39. tags_by_room = {}
  40. for row in rows:
  41. room_tags = tags_by_room.setdefault(row["room_id"], {})
  42. room_tags[row["tag"]] = db_to_json(row["content"])
  43. return tags_by_room
  44. return deferred
  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]], 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(txn):
  67. sql = (
  68. "SELECT stream_id, user_id, room_id"
  69. " FROM room_tags_revisions as r"
  70. " WHERE ? < stream_id AND stream_id <= ?"
  71. " ORDER BY stream_id ASC LIMIT ?"
  72. )
  73. txn.execute(sql, (last_id, current_id, limit))
  74. return txn.fetchall()
  75. tag_ids = await self.db_pool.runInteraction(
  76. "get_all_updated_tags", get_all_updated_tags_txn
  77. )
  78. def get_tag_content(txn, tag_ids):
  79. sql = "SELECT tag, content FROM room_tags WHERE user_id=? AND room_id=?"
  80. results = []
  81. for stream_id, user_id, room_id in tag_ids:
  82. txn.execute(sql, (user_id, room_id))
  83. tags = []
  84. for tag, content in txn:
  85. tags.append(json.dumps(tag) + ":" + content)
  86. tag_json = "{" + ",".join(tags) + "}"
  87. results.append((stream_id, (user_id, room_id, tag_json)))
  88. return results
  89. batch_size = 50
  90. results = []
  91. for i in range(0, len(tag_ids), batch_size):
  92. tags = await self.db_pool.runInteraction(
  93. "get_all_updated_tag_content",
  94. get_tag_content,
  95. tag_ids[i : i + batch_size],
  96. )
  97. results.extend(tags)
  98. limited = False
  99. upto_token = current_id
  100. if len(results) >= limit:
  101. upto_token = results[-1][0]
  102. limited = True
  103. return results, upto_token, limited
  104. @defer.inlineCallbacks
  105. def get_updated_tags(self, user_id, stream_id):
  106. """Get all the tags for the rooms where the tags have changed since the
  107. given version
  108. Args:
  109. user_id(str): The user to get the tags for.
  110. stream_id(int): The earliest update to get for the user.
  111. Returns:
  112. A deferred dict mapping from room_id strings to lists of tag
  113. strings for all the rooms that changed since the stream_id token.
  114. """
  115. def get_updated_tags_txn(txn):
  116. sql = (
  117. "SELECT room_id from room_tags_revisions"
  118. " WHERE user_id = ? AND stream_id > ?"
  119. )
  120. txn.execute(sql, (user_id, stream_id))
  121. room_ids = [row[0] for row in txn]
  122. return room_ids
  123. changed = self._account_data_stream_cache.has_entity_changed(
  124. user_id, int(stream_id)
  125. )
  126. if not changed:
  127. return {}
  128. room_ids = yield self.db_pool.runInteraction(
  129. "get_updated_tags", get_updated_tags_txn
  130. )
  131. results = {}
  132. if room_ids:
  133. tags_by_room = yield self.get_tags_for_user(user_id)
  134. for room_id in room_ids:
  135. results[room_id] = tags_by_room.get(room_id, {})
  136. return results
  137. def get_tags_for_room(self, user_id, room_id):
  138. """Get all the tags for the given room
  139. Args:
  140. user_id(str): The user to get tags for
  141. room_id(str): The room to get tags for
  142. Returns:
  143. A deferred list of string tags.
  144. """
  145. return self.db_pool.simple_select_list(
  146. table="room_tags",
  147. keyvalues={"user_id": user_id, "room_id": room_id},
  148. retcols=("tag", "content"),
  149. desc="get_tags_for_room",
  150. ).addCallback(
  151. lambda rows: {row["tag"]: db_to_json(row["content"]) for row in rows}
  152. )
  153. class TagsStore(TagsWorkerStore):
  154. @defer.inlineCallbacks
  155. def add_tag_to_room(self, user_id, room_id, tag, content):
  156. """Add a tag to a room for a user.
  157. Args:
  158. user_id(str): The user to add a tag for.
  159. room_id(str): The room to add a tag for.
  160. tag(str): The tag name to add.
  161. content(dict): A json object to associate with the tag.
  162. Returns:
  163. A deferred that completes once the tag has been added.
  164. """
  165. content_json = json.dumps(content)
  166. def add_tag_txn(txn, next_id):
  167. self.db_pool.simple_upsert_txn(
  168. txn,
  169. table="room_tags",
  170. keyvalues={"user_id": user_id, "room_id": room_id, "tag": tag},
  171. values={"content": content_json},
  172. )
  173. self._update_revision_txn(txn, user_id, room_id, next_id)
  174. with self._account_data_id_gen.get_next() as next_id:
  175. yield self.db_pool.runInteraction("add_tag", add_tag_txn, next_id)
  176. self.get_tags_for_user.invalidate((user_id,))
  177. result = self._account_data_id_gen.get_current_token()
  178. return result
  179. @defer.inlineCallbacks
  180. def remove_tag_from_room(self, user_id, room_id, tag):
  181. """Remove a tag from a room for a user.
  182. Returns:
  183. A deferred that completes once the tag has been removed
  184. """
  185. def remove_tag_txn(txn, next_id):
  186. sql = (
  187. "DELETE FROM room_tags "
  188. " WHERE user_id = ? AND room_id = ? AND tag = ?"
  189. )
  190. txn.execute(sql, (user_id, room_id, tag))
  191. self._update_revision_txn(txn, user_id, room_id, next_id)
  192. with self._account_data_id_gen.get_next() as next_id:
  193. yield self.db_pool.runInteraction("remove_tag", remove_tag_txn, next_id)
  194. self.get_tags_for_user.invalidate((user_id,))
  195. result = self._account_data_id_gen.get_current_token()
  196. return result
  197. def _update_revision_txn(self, txn, user_id, room_id, next_id):
  198. """Update the latest revision of the tags for the given user and room.
  199. Args:
  200. txn: The database cursor
  201. user_id(str): The ID of the user.
  202. room_id(str): The ID of the room.
  203. next_id(int): The the revision to advance to.
  204. """
  205. txn.call_after(
  206. self._account_data_stream_cache.entity_has_changed, user_id, next_id
  207. )
  208. # Note: This is only here for backwards compat to allow admins to
  209. # roll back to a previous Synapse version. Next time we update the
  210. # database version we can remove this table.
  211. update_max_id_sql = (
  212. "UPDATE account_data_max_stream_id"
  213. " SET stream_id = ?"
  214. " WHERE stream_id < ?"
  215. )
  216. txn.execute(update_max_id_sql, (next_id, next_id))
  217. update_sql = (
  218. "UPDATE room_tags_revisions"
  219. " SET stream_id = ?"
  220. " WHERE user_id = ?"
  221. " AND room_id = ?"
  222. )
  223. txn.execute(update_sql, (next_id, user_id, room_id))
  224. if txn.rowcount == 0:
  225. insert_sql = (
  226. "INSERT INTO room_tags_revisions (user_id, room_id, stream_id)"
  227. " VALUES (?, ?, ?)"
  228. )
  229. try:
  230. txn.execute(insert_sql, (user_id, room_id, next_id))
  231. except self.database_engine.module.IntegrityError:
  232. # Ignore insertion errors. It doesn't matter if the row wasn't
  233. # inserted because if two updates happend concurrently the one
  234. # with the higher stream_id will not be reported to a client
  235. # unless the previous update has completed. It doesn't matter
  236. # which stream_id ends up in the table, as long as it is higher
  237. # than the id that the client has.
  238. pass