deviceinbox.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 OpenMarket 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 ujson
  17. from twisted.internet import defer
  18. from ._base import SQLBaseStore
  19. logger = logging.getLogger(__name__)
  20. class DeviceInboxStore(SQLBaseStore):
  21. @defer.inlineCallbacks
  22. def add_messages_to_device_inbox(self, local_messages_by_user_then_device,
  23. remote_messages_by_destination):
  24. """Used to send messages from this server.
  25. Args:
  26. sender_user_id(str): The ID of the user sending these messages.
  27. local_messages_by_user_and_device(dict):
  28. Dictionary of user_id to device_id to message.
  29. remote_messages_by_destination(dict):
  30. Dictionary of destination server_name to the EDU JSON to send.
  31. Returns:
  32. A deferred stream_id that resolves when the messages have been
  33. inserted.
  34. """
  35. def add_messages_txn(txn, now_ms, stream_id):
  36. # Add the local messages directly to the local inbox.
  37. self._add_messages_to_local_device_inbox_txn(
  38. txn, stream_id, local_messages_by_user_then_device
  39. )
  40. # Add the remote messages to the federation outbox.
  41. # We'll send them to a remote server when we next send a
  42. # federation transaction to that destination.
  43. sql = (
  44. "INSERT INTO device_federation_outbox"
  45. " (destination, stream_id, queued_ts, messages_json)"
  46. " VALUES (?,?,?,?)"
  47. )
  48. rows = []
  49. for destination, edu in remote_messages_by_destination.items():
  50. edu_json = ujson.dumps(edu)
  51. rows.append((destination, stream_id, now_ms, edu_json))
  52. txn.executemany(sql, rows)
  53. with self._device_inbox_id_gen.get_next() as stream_id:
  54. now_ms = self.clock.time_msec()
  55. yield self.runInteraction(
  56. "add_messages_to_device_inbox",
  57. add_messages_txn,
  58. now_ms,
  59. stream_id,
  60. )
  61. for user_id in local_messages_by_user_then_device.keys():
  62. self._device_inbox_stream_cache.entity_has_changed(
  63. user_id, stream_id
  64. )
  65. for destination in remote_messages_by_destination.keys():
  66. self._device_federation_outbox_stream_cache.entity_has_changed(
  67. destination, stream_id
  68. )
  69. defer.returnValue(self._device_inbox_id_gen.get_current_token())
  70. @defer.inlineCallbacks
  71. def add_messages_from_remote_to_device_inbox(
  72. self, origin, message_id, local_messages_by_user_then_device
  73. ):
  74. def add_messages_txn(txn, now_ms, stream_id):
  75. # Check if we've already inserted a matching message_id for that
  76. # origin. This can happen if the origin doesn't receive our
  77. # acknowledgement from the first time we received the message.
  78. already_inserted = self._simple_select_one_txn(
  79. txn, table="device_federation_inbox",
  80. keyvalues={"origin": origin, "message_id": message_id},
  81. retcols=("message_id",),
  82. allow_none=True,
  83. )
  84. if already_inserted is not None:
  85. return
  86. # Add an entry for this message_id so that we know we've processed
  87. # it.
  88. self._simple_insert_txn(
  89. txn, table="device_federation_inbox",
  90. values={
  91. "origin": origin,
  92. "message_id": message_id,
  93. "received_ts": now_ms,
  94. },
  95. )
  96. # Add the messages to the approriate local device inboxes so that
  97. # they'll be sent to the devices when they next sync.
  98. self._add_messages_to_local_device_inbox_txn(
  99. txn, stream_id, local_messages_by_user_then_device
  100. )
  101. with self._device_inbox_id_gen.get_next() as stream_id:
  102. now_ms = self.clock.time_msec()
  103. yield self.runInteraction(
  104. "add_messages_from_remote_to_device_inbox",
  105. add_messages_txn,
  106. now_ms,
  107. stream_id,
  108. )
  109. for user_id in local_messages_by_user_then_device.keys():
  110. self._device_inbox_stream_cache.entity_has_changed(
  111. user_id, stream_id
  112. )
  113. defer.returnValue(stream_id)
  114. def _add_messages_to_local_device_inbox_txn(self, txn, stream_id,
  115. messages_by_user_then_device):
  116. sql = (
  117. "UPDATE device_max_stream_id"
  118. " SET stream_id = ?"
  119. " WHERE stream_id < ?"
  120. )
  121. txn.execute(sql, (stream_id, stream_id))
  122. local_by_user_then_device = {}
  123. for user_id, messages_by_device in messages_by_user_then_device.items():
  124. messages_json_for_user = {}
  125. devices = messages_by_device.keys()
  126. if len(devices) == 1 and devices[0] == "*":
  127. # Handle wildcard device_ids.
  128. sql = (
  129. "SELECT device_id FROM devices"
  130. " WHERE user_id = ?"
  131. )
  132. txn.execute(sql, (user_id,))
  133. message_json = ujson.dumps(messages_by_device["*"])
  134. for row in txn.fetchall():
  135. # Add the message for all devices for this user on this
  136. # server.
  137. device = row[0]
  138. messages_json_for_user[device] = message_json
  139. else:
  140. if not devices:
  141. continue
  142. sql = (
  143. "SELECT device_id FROM devices"
  144. " WHERE user_id = ? AND device_id IN ("
  145. + ",".join("?" * len(devices))
  146. + ")"
  147. )
  148. # TODO: Maybe this needs to be done in batches if there are
  149. # too many local devices for a given user.
  150. txn.execute(sql, [user_id] + devices)
  151. for row in txn.fetchall():
  152. # Only insert into the local inbox if the device exists on
  153. # this server
  154. device = row[0]
  155. message_json = ujson.dumps(messages_by_device[device])
  156. messages_json_for_user[device] = message_json
  157. if messages_json_for_user:
  158. local_by_user_then_device[user_id] = messages_json_for_user
  159. if not local_by_user_then_device:
  160. return
  161. sql = (
  162. "INSERT INTO device_inbox"
  163. " (user_id, device_id, stream_id, message_json)"
  164. " VALUES (?,?,?,?)"
  165. )
  166. rows = []
  167. for user_id, messages_by_device in local_by_user_then_device.items():
  168. for device_id, message_json in messages_by_device.items():
  169. rows.append((user_id, device_id, stream_id, message_json))
  170. txn.executemany(sql, rows)
  171. def get_new_messages_for_device(
  172. self, user_id, device_id, last_stream_id, current_stream_id, limit=100
  173. ):
  174. """
  175. Args:
  176. user_id(str): The recipient user_id.
  177. device_id(str): The recipient device_id.
  178. current_stream_id(int): The current position of the to device
  179. message stream.
  180. Returns:
  181. Deferred ([dict], int): List of messages for the device and where
  182. in the stream the messages got to.
  183. """
  184. has_changed = self._device_inbox_stream_cache.has_entity_changed(
  185. user_id, last_stream_id
  186. )
  187. if not has_changed:
  188. return defer.succeed(([], current_stream_id))
  189. def get_new_messages_for_device_txn(txn):
  190. sql = (
  191. "SELECT stream_id, message_json FROM device_inbox"
  192. " WHERE user_id = ? AND device_id = ?"
  193. " AND ? < stream_id AND stream_id <= ?"
  194. " ORDER BY stream_id ASC"
  195. " LIMIT ?"
  196. )
  197. txn.execute(sql, (
  198. user_id, device_id, last_stream_id, current_stream_id, limit
  199. ))
  200. messages = []
  201. for row in txn.fetchall():
  202. stream_pos = row[0]
  203. messages.append(ujson.loads(row[1]))
  204. if len(messages) < limit:
  205. stream_pos = current_stream_id
  206. return (messages, stream_pos)
  207. return self.runInteraction(
  208. "get_new_messages_for_device", get_new_messages_for_device_txn,
  209. )
  210. def delete_messages_for_device(self, user_id, device_id, up_to_stream_id):
  211. """
  212. Args:
  213. user_id(str): The recipient user_id.
  214. device_id(str): The recipient device_id.
  215. up_to_stream_id(int): Where to delete messages up to.
  216. Returns:
  217. A deferred that resolves when the messages have been deleted.
  218. """
  219. def delete_messages_for_device_txn(txn):
  220. sql = (
  221. "DELETE FROM device_inbox"
  222. " WHERE user_id = ? AND device_id = ?"
  223. " AND stream_id <= ?"
  224. )
  225. txn.execute(sql, (user_id, device_id, up_to_stream_id))
  226. return self.runInteraction(
  227. "delete_messages_for_device", delete_messages_for_device_txn
  228. )
  229. def get_all_new_device_messages(self, last_pos, current_pos, limit):
  230. """
  231. Args:
  232. last_pos(int):
  233. current_pos(int):
  234. limit(int):
  235. Returns:
  236. A deferred list of rows from the device inbox
  237. """
  238. if last_pos == current_pos:
  239. return defer.succeed([])
  240. def get_all_new_device_messages_txn(txn):
  241. # We limit like this as we might have multiple rows per stream_id, and
  242. # we want to make sure we always get all entries for any stream_id
  243. # we return.
  244. upper_pos = min(current_pos, last_pos + limit)
  245. sql = (
  246. "SELECT stream_id, user_id"
  247. " FROM device_inbox"
  248. " WHERE ? < stream_id AND stream_id <= ?"
  249. " ORDER BY stream_id ASC"
  250. )
  251. txn.execute(sql, (last_pos, upper_pos))
  252. rows = txn.fetchall()
  253. sql = (
  254. "SELECT stream_id, destination"
  255. " FROM device_federation_outbox"
  256. " WHERE ? < stream_id AND stream_id <= ?"
  257. " ORDER BY stream_id ASC"
  258. )
  259. txn.execute(sql, (last_pos, upper_pos))
  260. rows.extend(txn.fetchall())
  261. return rows
  262. return self.runInteraction(
  263. "get_all_new_device_messages", get_all_new_device_messages_txn
  264. )
  265. def get_to_device_stream_token(self):
  266. return self._device_inbox_id_gen.get_current_token()
  267. def get_new_device_msgs_for_remote(
  268. self, destination, last_stream_id, current_stream_id, limit=100
  269. ):
  270. """
  271. Args:
  272. destination(str): The name of the remote server.
  273. last_stream_id(int): The last position of the device message stream
  274. that the server sent up to.
  275. current_stream_id(int): The current position of the device
  276. message stream.
  277. Returns:
  278. Deferred ([dict], int): List of messages for the device and where
  279. in the stream the messages got to.
  280. """
  281. has_changed = self._device_federation_outbox_stream_cache.has_entity_changed(
  282. destination, last_stream_id
  283. )
  284. if not has_changed or last_stream_id == current_stream_id:
  285. return defer.succeed(([], current_stream_id))
  286. def get_new_messages_for_remote_destination_txn(txn):
  287. sql = (
  288. "SELECT stream_id, messages_json FROM device_federation_outbox"
  289. " WHERE destination = ?"
  290. " AND ? < stream_id AND stream_id <= ?"
  291. " ORDER BY stream_id ASC"
  292. " LIMIT ?"
  293. )
  294. txn.execute(sql, (
  295. destination, last_stream_id, current_stream_id, limit
  296. ))
  297. messages = []
  298. for row in txn.fetchall():
  299. stream_pos = row[0]
  300. messages.append(ujson.loads(row[1]))
  301. if len(messages) < limit:
  302. stream_pos = current_stream_id
  303. return (messages, stream_pos)
  304. return self.runInteraction(
  305. "get_new_device_msgs_for_remote",
  306. get_new_messages_for_remote_destination_txn,
  307. )
  308. def delete_device_msgs_for_remote(self, destination, up_to_stream_id):
  309. """Used to delete messages when the remote destination acknowledges
  310. their receipt.
  311. Args:
  312. destination(str): The destination server_name
  313. up_to_stream_id(int): Where to delete messages up to.
  314. Returns:
  315. A deferred that resolves when the messages have been deleted.
  316. """
  317. def delete_messages_for_remote_destination_txn(txn):
  318. sql = (
  319. "DELETE FROM device_federation_outbox"
  320. " WHERE destination = ?"
  321. " AND stream_id <= ?"
  322. )
  323. txn.execute(sql, (destination, up_to_stream_id))
  324. return self.runInteraction(
  325. "delete_device_msgs_for_remote",
  326. delete_messages_for_remote_destination_txn
  327. )