account_data.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 abc
  17. import logging
  18. from canonicaljson import json
  19. from twisted.internet import defer
  20. from synapse.storage._base import SQLBaseStore
  21. from synapse.storage.database import Database
  22. from synapse.storage.util.id_generators import StreamIdGenerator
  23. from synapse.util.caches.descriptors import cached, cachedInlineCallbacks
  24. from synapse.util.caches.stream_change_cache import StreamChangeCache
  25. logger = logging.getLogger(__name__)
  26. class AccountDataWorkerStore(SQLBaseStore):
  27. """This is an abstract base class where subclasses must implement
  28. `get_max_account_data_stream_id` which can be called in the initializer.
  29. """
  30. # This ABCMeta metaclass ensures that we cannot be instantiated without
  31. # the abstract methods being implemented.
  32. __metaclass__ = abc.ABCMeta
  33. def __init__(self, database: Database, db_conn, hs):
  34. account_max = self.get_max_account_data_stream_id()
  35. self._account_data_stream_cache = StreamChangeCache(
  36. "AccountDataAndTagsChangeCache", account_max
  37. )
  38. super(AccountDataWorkerStore, self).__init__(database, db_conn, hs)
  39. @abc.abstractmethod
  40. def get_max_account_data_stream_id(self):
  41. """Get the current max stream ID for account data stream
  42. Returns:
  43. int
  44. """
  45. raise NotImplementedError()
  46. @cached()
  47. def get_account_data_for_user(self, user_id):
  48. """Get all the client account_data for a user.
  49. Args:
  50. user_id(str): The user to get the account_data for.
  51. Returns:
  52. A deferred pair of a dict of global account_data and a dict
  53. mapping from room_id string to per room account_data dicts.
  54. """
  55. def get_account_data_for_user_txn(txn):
  56. rows = self.db.simple_select_list_txn(
  57. txn,
  58. "account_data",
  59. {"user_id": user_id},
  60. ["account_data_type", "content"],
  61. )
  62. global_account_data = {
  63. row["account_data_type"]: json.loads(row["content"]) for row in rows
  64. }
  65. rows = self.db.simple_select_list_txn(
  66. txn,
  67. "room_account_data",
  68. {"user_id": user_id},
  69. ["room_id", "account_data_type", "content"],
  70. )
  71. by_room = {}
  72. for row in rows:
  73. room_data = by_room.setdefault(row["room_id"], {})
  74. room_data[row["account_data_type"]] = json.loads(row["content"])
  75. return global_account_data, by_room
  76. return self.db.runInteraction(
  77. "get_account_data_for_user", get_account_data_for_user_txn
  78. )
  79. @cachedInlineCallbacks(num_args=2, max_entries=5000)
  80. def get_global_account_data_by_type_for_user(self, data_type, user_id):
  81. """
  82. Returns:
  83. Deferred: A dict
  84. """
  85. result = yield self.db.simple_select_one_onecol(
  86. table="account_data",
  87. keyvalues={"user_id": user_id, "account_data_type": data_type},
  88. retcol="content",
  89. desc="get_global_account_data_by_type_for_user",
  90. allow_none=True,
  91. )
  92. if result:
  93. return json.loads(result)
  94. else:
  95. return None
  96. @cached(num_args=2)
  97. def get_account_data_for_room(self, user_id, room_id):
  98. """Get all the client account_data for a user for a room.
  99. Args:
  100. user_id(str): The user to get the account_data for.
  101. room_id(str): The room to get the account_data for.
  102. Returns:
  103. A deferred dict of the room account_data
  104. """
  105. def get_account_data_for_room_txn(txn):
  106. rows = self.db.simple_select_list_txn(
  107. txn,
  108. "room_account_data",
  109. {"user_id": user_id, "room_id": room_id},
  110. ["account_data_type", "content"],
  111. )
  112. return {
  113. row["account_data_type"]: json.loads(row["content"]) for row in rows
  114. }
  115. return self.db.runInteraction(
  116. "get_account_data_for_room", get_account_data_for_room_txn
  117. )
  118. @cached(num_args=3, max_entries=5000)
  119. def get_account_data_for_room_and_type(self, user_id, room_id, account_data_type):
  120. """Get the client account_data of given type for a user for a room.
  121. Args:
  122. user_id(str): The user to get the account_data for.
  123. room_id(str): The room to get the account_data for.
  124. account_data_type (str): The account data type to get.
  125. Returns:
  126. A deferred of the room account_data for that type, or None if
  127. there isn't any set.
  128. """
  129. def get_account_data_for_room_and_type_txn(txn):
  130. content_json = self.db.simple_select_one_onecol_txn(
  131. txn,
  132. table="room_account_data",
  133. keyvalues={
  134. "user_id": user_id,
  135. "room_id": room_id,
  136. "account_data_type": account_data_type,
  137. },
  138. retcol="content",
  139. allow_none=True,
  140. )
  141. return json.loads(content_json) if content_json else None
  142. return self.db.runInteraction(
  143. "get_account_data_for_room_and_type", get_account_data_for_room_and_type_txn
  144. )
  145. def get_all_updated_account_data(
  146. self, last_global_id, last_room_id, current_id, limit
  147. ):
  148. """Get all the client account_data that has changed on the server
  149. Args:
  150. last_global_id(int): The position to fetch from for top level data
  151. last_room_id(int): The position to fetch from for per room data
  152. current_id(int): The position to fetch up to.
  153. Returns:
  154. A deferred pair of lists of tuples of stream_id int, user_id string,
  155. room_id string, and type string.
  156. """
  157. if last_room_id == current_id and last_global_id == current_id:
  158. return defer.succeed(([], []))
  159. def get_updated_account_data_txn(txn):
  160. sql = (
  161. "SELECT stream_id, user_id, account_data_type"
  162. " FROM account_data WHERE ? < stream_id AND stream_id <= ?"
  163. " ORDER BY stream_id ASC LIMIT ?"
  164. )
  165. txn.execute(sql, (last_global_id, current_id, limit))
  166. global_results = txn.fetchall()
  167. sql = (
  168. "SELECT stream_id, user_id, room_id, account_data_type"
  169. " FROM room_account_data WHERE ? < stream_id AND stream_id <= ?"
  170. " ORDER BY stream_id ASC LIMIT ?"
  171. )
  172. txn.execute(sql, (last_room_id, current_id, limit))
  173. room_results = txn.fetchall()
  174. return global_results, room_results
  175. return self.db.runInteraction(
  176. "get_all_updated_account_data_txn", get_updated_account_data_txn
  177. )
  178. def get_updated_account_data_for_user(self, user_id, stream_id):
  179. """Get all the client account_data for a that's changed for a user
  180. Args:
  181. user_id(str): The user to get the account_data for.
  182. stream_id(int): The point in the stream since which to get updates
  183. Returns:
  184. A deferred pair of a dict of global account_data and a dict
  185. mapping from room_id string to per room account_data dicts.
  186. """
  187. def get_updated_account_data_for_user_txn(txn):
  188. sql = (
  189. "SELECT account_data_type, content FROM account_data"
  190. " WHERE user_id = ? AND stream_id > ?"
  191. )
  192. txn.execute(sql, (user_id, stream_id))
  193. global_account_data = {row[0]: json.loads(row[1]) for row in txn}
  194. sql = (
  195. "SELECT room_id, account_data_type, content FROM room_account_data"
  196. " WHERE user_id = ? AND stream_id > ?"
  197. )
  198. txn.execute(sql, (user_id, stream_id))
  199. account_data_by_room = {}
  200. for row in txn:
  201. room_account_data = account_data_by_room.setdefault(row[0], {})
  202. room_account_data[row[1]] = json.loads(row[2])
  203. return global_account_data, account_data_by_room
  204. changed = self._account_data_stream_cache.has_entity_changed(
  205. user_id, int(stream_id)
  206. )
  207. if not changed:
  208. return defer.succeed(({}, {}))
  209. return self.db.runInteraction(
  210. "get_updated_account_data_for_user", get_updated_account_data_for_user_txn
  211. )
  212. @cachedInlineCallbacks(num_args=2, cache_context=True, max_entries=5000)
  213. def is_ignored_by(self, ignored_user_id, ignorer_user_id, cache_context):
  214. ignored_account_data = yield self.get_global_account_data_by_type_for_user(
  215. "m.ignored_user_list",
  216. ignorer_user_id,
  217. on_invalidate=cache_context.invalidate,
  218. )
  219. if not ignored_account_data:
  220. return False
  221. return ignored_user_id in ignored_account_data.get("ignored_users", {})
  222. class AccountDataStore(AccountDataWorkerStore):
  223. def __init__(self, database: Database, db_conn, hs):
  224. self._account_data_id_gen = StreamIdGenerator(
  225. db_conn, "account_data_max_stream_id", "stream_id"
  226. )
  227. super(AccountDataStore, self).__init__(database, db_conn, hs)
  228. def get_max_account_data_stream_id(self):
  229. """Get the current max stream id for the private user data stream
  230. Returns:
  231. A deferred int.
  232. """
  233. return self._account_data_id_gen.get_current_token()
  234. @defer.inlineCallbacks
  235. def add_account_data_to_room(self, user_id, room_id, account_data_type, content):
  236. """Add some account_data to a room for a user.
  237. Args:
  238. user_id(str): The user to add a tag for.
  239. room_id(str): The room to add a tag for.
  240. account_data_type(str): The type of account_data to add.
  241. content(dict): A json object to associate with the tag.
  242. Returns:
  243. A deferred that completes once the account_data has been added.
  244. """
  245. content_json = json.dumps(content)
  246. with self._account_data_id_gen.get_next() as next_id:
  247. # no need to lock here as room_account_data has a unique constraint
  248. # on (user_id, room_id, account_data_type) so simple_upsert will
  249. # retry if there is a conflict.
  250. yield self.db.simple_upsert(
  251. desc="add_room_account_data",
  252. table="room_account_data",
  253. keyvalues={
  254. "user_id": user_id,
  255. "room_id": room_id,
  256. "account_data_type": account_data_type,
  257. },
  258. values={"stream_id": next_id, "content": content_json},
  259. lock=False,
  260. )
  261. # it's theoretically possible for the above to succeed and the
  262. # below to fail - in which case we might reuse a stream id on
  263. # restart, and the above update might not get propagated. That
  264. # doesn't sound any worse than the whole update getting lost,
  265. # which is what would happen if we combined the two into one
  266. # transaction.
  267. yield self._update_max_stream_id(next_id)
  268. self._account_data_stream_cache.entity_has_changed(user_id, next_id)
  269. self.get_account_data_for_user.invalidate((user_id,))
  270. self.get_account_data_for_room.invalidate((user_id, room_id))
  271. self.get_account_data_for_room_and_type.prefill(
  272. (user_id, room_id, account_data_type), content
  273. )
  274. result = self._account_data_id_gen.get_current_token()
  275. return result
  276. @defer.inlineCallbacks
  277. def add_account_data_for_user(self, user_id, account_data_type, content):
  278. """Add some account_data to a room for a user.
  279. Args:
  280. user_id(str): The user to add a tag for.
  281. account_data_type(str): The type of account_data to add.
  282. content(dict): A json object to associate with the tag.
  283. Returns:
  284. A deferred that completes once the account_data has been added.
  285. """
  286. content_json = json.dumps(content)
  287. with self._account_data_id_gen.get_next() as next_id:
  288. # no need to lock here as account_data has a unique constraint on
  289. # (user_id, account_data_type) so simple_upsert will retry if
  290. # there is a conflict.
  291. yield self.db.simple_upsert(
  292. desc="add_user_account_data",
  293. table="account_data",
  294. keyvalues={"user_id": user_id, "account_data_type": account_data_type},
  295. values={"stream_id": next_id, "content": content_json},
  296. lock=False,
  297. )
  298. # it's theoretically possible for the above to succeed and the
  299. # below to fail - in which case we might reuse a stream id on
  300. # restart, and the above update might not get propagated. That
  301. # doesn't sound any worse than the whole update getting lost,
  302. # which is what would happen if we combined the two into one
  303. # transaction.
  304. yield self._update_max_stream_id(next_id)
  305. self._account_data_stream_cache.entity_has_changed(user_id, next_id)
  306. self.get_account_data_for_user.invalidate((user_id,))
  307. self.get_global_account_data_by_type_for_user.invalidate(
  308. (account_data_type, user_id)
  309. )
  310. result = self._account_data_id_gen.get_current_token()
  311. return result
  312. def _update_max_stream_id(self, next_id):
  313. """Update the max stream_id
  314. Args:
  315. next_id(int): The the revision to advance to.
  316. """
  317. def _update(txn):
  318. update_max_id_sql = (
  319. "UPDATE account_data_max_stream_id"
  320. " SET stream_id = ?"
  321. " WHERE stream_id < ?"
  322. )
  323. txn.execute(update_max_id_sql, (next_id, next_id))
  324. return self.db.runInteraction("update_account_data_max_stream_id", _update)