Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

1098 lignes
42 KiB

  1. # Copyright 2016 OpenMarket Ltd
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  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. from typing import (
  17. TYPE_CHECKING,
  18. Collection,
  19. Dict,
  20. Iterable,
  21. List,
  22. Optional,
  23. Set,
  24. Tuple,
  25. cast,
  26. )
  27. from synapse.api.constants import EventContentFields
  28. from synapse.logging import issue9533_logger
  29. from synapse.logging.opentracing import (
  30. SynapseTags,
  31. log_kv,
  32. set_tag,
  33. start_active_span,
  34. trace,
  35. )
  36. from synapse.replication.tcp.streams import ToDeviceStream
  37. from synapse.storage._base import SQLBaseStore, db_to_json
  38. from synapse.storage.database import (
  39. DatabasePool,
  40. LoggingDatabaseConnection,
  41. LoggingTransaction,
  42. make_in_list_sql_clause,
  43. )
  44. from synapse.storage.engines import PostgresEngine
  45. from synapse.storage.util.id_generators import (
  46. AbstractStreamIdGenerator,
  47. MultiWriterIdGenerator,
  48. StreamIdGenerator,
  49. )
  50. from synapse.types import JsonDict
  51. from synapse.util import json_encoder
  52. from synapse.util.caches.expiringcache import ExpiringCache
  53. from synapse.util.caches.stream_change_cache import StreamChangeCache
  54. if TYPE_CHECKING:
  55. from synapse.server import HomeServer
  56. logger = logging.getLogger(__name__)
  57. class DeviceInboxWorkerStore(SQLBaseStore):
  58. def __init__(
  59. self,
  60. database: DatabasePool,
  61. db_conn: LoggingDatabaseConnection,
  62. hs: "HomeServer",
  63. ):
  64. super().__init__(database, db_conn, hs)
  65. self._instance_name = hs.get_instance_name()
  66. # Map of (user_id, device_id) to the last stream_id that has been
  67. # deleted up to. This is so that we can no op deletions.
  68. self._last_device_delete_cache: ExpiringCache[
  69. Tuple[str, Optional[str]], int
  70. ] = ExpiringCache(
  71. cache_name="last_device_delete_cache",
  72. clock=self._clock,
  73. max_len=10000,
  74. expiry_ms=30 * 60 * 1000,
  75. )
  76. if isinstance(database.engine, PostgresEngine):
  77. self._can_write_to_device = (
  78. self._instance_name in hs.config.worker.writers.to_device
  79. )
  80. self._to_device_msg_id_gen: AbstractStreamIdGenerator = (
  81. MultiWriterIdGenerator(
  82. db_conn=db_conn,
  83. db=database,
  84. notifier=hs.get_replication_notifier(),
  85. stream_name="to_device",
  86. instance_name=self._instance_name,
  87. tables=[
  88. ("device_inbox", "instance_name", "stream_id"),
  89. ("device_federation_outbox", "instance_name", "stream_id"),
  90. ],
  91. sequence_name="device_inbox_sequence",
  92. writers=hs.config.worker.writers.to_device,
  93. )
  94. )
  95. else:
  96. self._can_write_to_device = True
  97. self._to_device_msg_id_gen = StreamIdGenerator(
  98. db_conn,
  99. hs.get_replication_notifier(),
  100. "device_inbox",
  101. "stream_id",
  102. extra_tables=[("device_federation_outbox", "stream_id")],
  103. )
  104. max_device_inbox_id = self._to_device_msg_id_gen.get_current_token()
  105. device_inbox_prefill, min_device_inbox_id = self.db_pool.get_cache_dict(
  106. db_conn,
  107. "device_inbox",
  108. entity_column="user_id",
  109. stream_column="stream_id",
  110. max_value=max_device_inbox_id,
  111. limit=1000,
  112. )
  113. self._device_inbox_stream_cache = StreamChangeCache(
  114. "DeviceInboxStreamChangeCache",
  115. min_device_inbox_id,
  116. prefilled_cache=device_inbox_prefill,
  117. )
  118. # The federation outbox and the local device inbox uses the same
  119. # stream_id generator.
  120. device_outbox_prefill, min_device_outbox_id = self.db_pool.get_cache_dict(
  121. db_conn,
  122. "device_federation_outbox",
  123. entity_column="destination",
  124. stream_column="stream_id",
  125. max_value=max_device_inbox_id,
  126. limit=1000,
  127. )
  128. self._device_federation_outbox_stream_cache = StreamChangeCache(
  129. "DeviceFederationOutboxStreamChangeCache",
  130. min_device_outbox_id,
  131. prefilled_cache=device_outbox_prefill,
  132. )
  133. def process_replication_rows(
  134. self,
  135. stream_name: str,
  136. instance_name: str,
  137. token: int,
  138. rows: Iterable[ToDeviceStream.ToDeviceStreamRow],
  139. ) -> None:
  140. if stream_name == ToDeviceStream.NAME:
  141. # If replication is happening than postgres must be being used.
  142. assert isinstance(self._to_device_msg_id_gen, MultiWriterIdGenerator)
  143. self._to_device_msg_id_gen.advance(instance_name, token)
  144. for row in rows:
  145. if row.entity.startswith("@"):
  146. self._device_inbox_stream_cache.entity_has_changed(
  147. row.entity, token
  148. )
  149. else:
  150. self._device_federation_outbox_stream_cache.entity_has_changed(
  151. row.entity, token
  152. )
  153. return super().process_replication_rows(stream_name, instance_name, token, rows)
  154. def process_replication_position(
  155. self, stream_name: str, instance_name: str, token: int
  156. ) -> None:
  157. if stream_name == ToDeviceStream.NAME:
  158. self._to_device_msg_id_gen.advance(instance_name, token)
  159. super().process_replication_position(stream_name, instance_name, token)
  160. def get_to_device_stream_token(self) -> int:
  161. return self._to_device_msg_id_gen.get_current_token()
  162. async def get_messages_for_user_devices(
  163. self,
  164. user_ids: Collection[str],
  165. from_stream_id: int,
  166. to_stream_id: int,
  167. ) -> Dict[Tuple[str, str], List[JsonDict]]:
  168. """
  169. Retrieve to-device messages for a given set of users.
  170. Only to-device messages with stream ids between the given boundaries
  171. (from < X <= to) are returned.
  172. Args:
  173. user_ids: The users to retrieve to-device messages for.
  174. from_stream_id: The lower boundary of stream id to filter with (exclusive).
  175. to_stream_id: The upper boundary of stream id to filter with (inclusive).
  176. Returns:
  177. A dictionary of (user id, device id) -> list of to-device messages.
  178. """
  179. # We expect the stream ID returned by _get_device_messages to always
  180. # be to_stream_id. So, no need to return it from this function.
  181. (
  182. user_id_device_id_to_messages,
  183. last_processed_stream_id,
  184. ) = await self._get_device_messages(
  185. user_ids=user_ids,
  186. from_stream_id=from_stream_id,
  187. to_stream_id=to_stream_id,
  188. )
  189. assert (
  190. last_processed_stream_id == to_stream_id
  191. ), "Expected _get_device_messages to process all to-device messages up to `to_stream_id`"
  192. return user_id_device_id_to_messages
  193. async def get_messages_for_device(
  194. self,
  195. user_id: str,
  196. device_id: str,
  197. from_stream_id: int,
  198. to_stream_id: int,
  199. limit: int = 100,
  200. ) -> Tuple[List[JsonDict], int]:
  201. """
  202. Retrieve to-device messages for a single user device.
  203. Only to-device messages with stream ids between the given boundaries
  204. (from < X <= to) are returned.
  205. Args:
  206. user_id: The ID of the user to retrieve messages for.
  207. device_id: The ID of the device to retrieve to-device messages for.
  208. from_stream_id: The lower boundary of stream id to filter with (exclusive).
  209. to_stream_id: The upper boundary of stream id to filter with (inclusive).
  210. limit: A limit on the number of to-device messages returned.
  211. Returns:
  212. A tuple containing:
  213. * A list of to-device messages within the given stream id range intended for
  214. the given user / device combo.
  215. * The last-processed stream ID. Subsequent calls of this function with the
  216. same device should pass this value as 'from_stream_id'.
  217. """
  218. (
  219. user_id_device_id_to_messages,
  220. last_processed_stream_id,
  221. ) = await self._get_device_messages(
  222. user_ids=[user_id],
  223. device_id=device_id,
  224. from_stream_id=from_stream_id,
  225. to_stream_id=to_stream_id,
  226. limit=limit,
  227. )
  228. if not user_id_device_id_to_messages:
  229. # There were no messages!
  230. return [], to_stream_id
  231. # Extract the messages, no need to return the user and device ID again
  232. to_device_messages = user_id_device_id_to_messages.get((user_id, device_id), [])
  233. return to_device_messages, last_processed_stream_id
  234. async def _get_device_messages(
  235. self,
  236. user_ids: Collection[str],
  237. from_stream_id: int,
  238. to_stream_id: int,
  239. device_id: Optional[str] = None,
  240. limit: Optional[int] = None,
  241. ) -> Tuple[Dict[Tuple[str, str], List[JsonDict]], int]:
  242. """
  243. Retrieve pending to-device messages for a collection of user devices.
  244. Only to-device messages with stream ids between the given boundaries
  245. (from < X <= to) are returned.
  246. Note that a stream ID can be shared by multiple copies of the same message with
  247. different recipient devices. Stream IDs are only unique in the context of a single
  248. user ID / device ID pair. Thus, applying a limit (of messages to return) when working
  249. with a sliding window of stream IDs is only possible when querying messages of a
  250. single user device.
  251. Finally, note that device IDs are not unique across users.
  252. Args:
  253. user_ids: The user IDs to filter device messages by.
  254. from_stream_id: The lower boundary of stream id to filter with (exclusive).
  255. to_stream_id: The upper boundary of stream id to filter with (inclusive).
  256. device_id: A device ID to query to-device messages for. If not provided, to-device
  257. messages from all device IDs for the given user IDs will be queried. May not be
  258. provided if `user_ids` contains more than one entry.
  259. limit: The maximum number of to-device messages to return. Can only be used when
  260. passing a single user ID / device ID tuple.
  261. Returns:
  262. A tuple containing:
  263. * A dict of (user_id, device_id) -> list of to-device messages
  264. * The last-processed stream ID. If this is less than `to_stream_id`, then
  265. there may be more messages to retrieve. If `limit` is not set, then this
  266. is always equal to 'to_stream_id'.
  267. """
  268. if not user_ids:
  269. logger.warning("No users provided upon querying for device IDs")
  270. return {}, to_stream_id
  271. # Prevent a query for one user's device also retrieving another user's device with
  272. # the same device ID (device IDs are not unique across users).
  273. if len(user_ids) > 1 and device_id is not None:
  274. raise AssertionError(
  275. "Programming error: 'device_id' cannot be supplied to "
  276. "_get_device_messages when >1 user_id has been provided"
  277. )
  278. # A limit can only be applied when querying for a single user ID / device ID tuple.
  279. # See the docstring of this function for more details.
  280. if limit is not None and device_id is None:
  281. raise AssertionError(
  282. "Programming error: _get_device_messages was passed 'limit' "
  283. "without a specific user_id/device_id"
  284. )
  285. user_ids_to_query: Set[str] = set()
  286. device_ids_to_query: Set[str] = set()
  287. # Note that a device ID could be an empty str
  288. if device_id is not None:
  289. # If a device ID was passed, use it to filter results.
  290. # Otherwise, device IDs will be derived from the given collection of user IDs.
  291. device_ids_to_query.add(device_id)
  292. # Determine which users have devices with pending messages
  293. for user_id in user_ids:
  294. if self._device_inbox_stream_cache.has_entity_changed(
  295. user_id, from_stream_id
  296. ):
  297. # This user has new messages sent to them. Query messages for them
  298. user_ids_to_query.add(user_id)
  299. if not user_ids_to_query:
  300. return {}, to_stream_id
  301. def get_device_messages_txn(
  302. txn: LoggingTransaction,
  303. ) -> Tuple[Dict[Tuple[str, str], List[JsonDict]], int]:
  304. # Build a query to select messages from any of the given devices that
  305. # are between the given stream id bounds.
  306. # If a list of device IDs was not provided, retrieve all devices IDs
  307. # for the given users. We explicitly do not query hidden devices, as
  308. # hidden devices should not receive to-device messages.
  309. # Note that this is more efficient than just dropping `device_id` from the query,
  310. # since device_inbox has an index on `(user_id, device_id, stream_id)`
  311. if not device_ids_to_query:
  312. user_device_dicts = cast(
  313. List[Tuple[str]],
  314. self.db_pool.simple_select_many_txn(
  315. txn,
  316. table="devices",
  317. column="user_id",
  318. iterable=user_ids_to_query,
  319. keyvalues={"hidden": False},
  320. retcols=("device_id",),
  321. ),
  322. )
  323. device_ids_to_query.update({row[0] for row in user_device_dicts})
  324. if not device_ids_to_query:
  325. # We've ended up with no devices to query.
  326. return {}, to_stream_id
  327. # We include both user IDs and device IDs in this query, as we have an index
  328. # (device_inbox_user_stream_id) for them.
  329. user_id_many_clause_sql, user_id_many_clause_args = make_in_list_sql_clause(
  330. self.database_engine, "user_id", user_ids_to_query
  331. )
  332. (
  333. device_id_many_clause_sql,
  334. device_id_many_clause_args,
  335. ) = make_in_list_sql_clause(
  336. self.database_engine, "device_id", device_ids_to_query
  337. )
  338. sql = f"""
  339. SELECT stream_id, user_id, device_id, message_json FROM device_inbox
  340. WHERE {user_id_many_clause_sql}
  341. AND {device_id_many_clause_sql}
  342. AND ? < stream_id AND stream_id <= ?
  343. ORDER BY stream_id ASC
  344. """
  345. sql_args = (
  346. *user_id_many_clause_args,
  347. *device_id_many_clause_args,
  348. from_stream_id,
  349. to_stream_id,
  350. )
  351. # If a limit was provided, limit the data retrieved from the database
  352. if limit is not None:
  353. sql += "LIMIT ?"
  354. sql_args += (limit,)
  355. txn.execute(sql, sql_args)
  356. # Create and fill a dictionary of (user ID, device ID) -> list of messages
  357. # intended for each device.
  358. last_processed_stream_pos = to_stream_id
  359. recipient_device_to_messages: Dict[Tuple[str, str], List[JsonDict]] = {}
  360. rowcount = 0
  361. for row in txn:
  362. rowcount += 1
  363. last_processed_stream_pos = row[0]
  364. recipient_user_id = row[1]
  365. recipient_device_id = row[2]
  366. message_dict = db_to_json(row[3])
  367. # Store the device details
  368. recipient_device_to_messages.setdefault(
  369. (recipient_user_id, recipient_device_id), []
  370. ).append(message_dict)
  371. # start a new span for each message, so that we can tag each separately
  372. with start_active_span("get_to_device_message"):
  373. set_tag(SynapseTags.TO_DEVICE_TYPE, message_dict["type"])
  374. set_tag(SynapseTags.TO_DEVICE_SENDER, message_dict["sender"])
  375. set_tag(SynapseTags.TO_DEVICE_RECIPIENT, recipient_user_id)
  376. set_tag(SynapseTags.TO_DEVICE_RECIPIENT_DEVICE, recipient_device_id)
  377. set_tag(
  378. SynapseTags.TO_DEVICE_MSGID,
  379. message_dict["content"].get(EventContentFields.TO_DEVICE_MSGID),
  380. )
  381. if limit is not None and rowcount == limit:
  382. # We ended up bumping up against the message limit. There may be more messages
  383. # to retrieve. Return what we have, as well as the last stream position that
  384. # was processed.
  385. #
  386. # The caller is expected to set this as the lower (exclusive) bound
  387. # for the next query of this device.
  388. return recipient_device_to_messages, last_processed_stream_pos
  389. # The limit was not reached, thus we know that recipient_device_to_messages
  390. # contains all to-device messages for the given device and stream id range.
  391. #
  392. # We return to_stream_id, which the caller should then provide as the lower
  393. # (exclusive) bound on the next query of this device.
  394. return recipient_device_to_messages, to_stream_id
  395. return await self.db_pool.runInteraction(
  396. "get_device_messages", get_device_messages_txn
  397. )
  398. @trace
  399. async def delete_messages_for_device(
  400. self,
  401. user_id: str,
  402. device_id: Optional[str],
  403. up_to_stream_id: int,
  404. ) -> int:
  405. """
  406. Args:
  407. user_id: The recipient user_id.
  408. device_id: The recipient device_id.
  409. up_to_stream_id: Where to delete messages up to.
  410. Returns:
  411. The number of messages deleted.
  412. """
  413. # If we have cached the last stream id we've deleted up to, we can
  414. # check if there is likely to be anything that needs deleting
  415. last_deleted_stream_id = self._last_device_delete_cache.get(
  416. (user_id, device_id), None
  417. )
  418. set_tag("last_deleted_stream_id", str(last_deleted_stream_id))
  419. if last_deleted_stream_id:
  420. has_changed = self._device_inbox_stream_cache.has_entity_changed(
  421. user_id, last_deleted_stream_id
  422. )
  423. if not has_changed:
  424. log_kv({"message": "No changes in cache since last check"})
  425. return 0
  426. from_stream_id = None
  427. count = 0
  428. while True:
  429. from_stream_id, loop_count = await self.delete_messages_for_device_between(
  430. user_id,
  431. device_id,
  432. from_stream_id=from_stream_id,
  433. to_stream_id=up_to_stream_id,
  434. limit=1000,
  435. )
  436. count += loop_count
  437. if from_stream_id is None:
  438. break
  439. log_kv({"message": f"deleted {count} messages for device", "count": count})
  440. # Update the cache, ensuring that we only ever increase the value
  441. updated_last_deleted_stream_id = self._last_device_delete_cache.get(
  442. (user_id, device_id), 0
  443. )
  444. self._last_device_delete_cache[(user_id, device_id)] = max(
  445. updated_last_deleted_stream_id, up_to_stream_id
  446. )
  447. return count
  448. @trace
  449. async def delete_messages_for_device_between(
  450. self,
  451. user_id: str,
  452. device_id: Optional[str],
  453. from_stream_id: Optional[int],
  454. to_stream_id: int,
  455. limit: int,
  456. ) -> Tuple[Optional[int], int]:
  457. """Delete N device messages between the stream IDs, returning the
  458. highest stream ID deleted (or None if all messages in the range have
  459. been deleted) and the number of messages deleted.
  460. This is more efficient than `delete_messages_for_device` when calling in
  461. a loop to batch delete messages.
  462. """
  463. # Keeping track of a lower bound of stream ID where we've deleted
  464. # everything below makes the queries much faster. Otherwise, every time
  465. # we scan for rows to delete we'd re-scan across all the rows that have
  466. # previously deleted (until the next table VACUUM).
  467. if from_stream_id is None:
  468. # Minimum device stream ID is 1.
  469. from_stream_id = 0
  470. def delete_messages_for_device_between_txn(
  471. txn: LoggingTransaction,
  472. ) -> Tuple[Optional[int], int]:
  473. txn.execute(
  474. """
  475. SELECT MAX(stream_id) FROM (
  476. SELECT stream_id FROM device_inbox
  477. WHERE user_id = ? AND device_id = ?
  478. AND ? < stream_id AND stream_id <= ?
  479. ORDER BY stream_id
  480. LIMIT ?
  481. ) AS d
  482. """,
  483. (user_id, device_id, from_stream_id, to_stream_id, limit),
  484. )
  485. row = txn.fetchone()
  486. if row is None or row[0] is None:
  487. return None, 0
  488. (max_stream_id,) = row
  489. txn.execute(
  490. """
  491. DELETE FROM device_inbox
  492. WHERE user_id = ? AND device_id = ?
  493. AND ? < stream_id AND stream_id <= ?
  494. """,
  495. (user_id, device_id, from_stream_id, max_stream_id),
  496. )
  497. num_deleted = txn.rowcount
  498. if num_deleted < limit:
  499. return None, num_deleted
  500. return max_stream_id, num_deleted
  501. return await self.db_pool.runInteraction(
  502. "delete_messages_for_device_between",
  503. delete_messages_for_device_between_txn,
  504. db_autocommit=True, # We don't need to run in a transaction
  505. )
  506. @trace
  507. async def get_new_device_msgs_for_remote(
  508. self, destination: str, last_stream_id: int, current_stream_id: int, limit: int
  509. ) -> Tuple[List[JsonDict], int]:
  510. """
  511. Args:
  512. destination: The name of the remote server.
  513. last_stream_id: The last position of the device message stream
  514. that the server sent up to.
  515. current_stream_id: The current position of the device message stream.
  516. Returns:
  517. A list of messages for the device and where in the stream the messages got to.
  518. """
  519. set_tag("destination", destination)
  520. set_tag("last_stream_id", last_stream_id)
  521. set_tag("current_stream_id", current_stream_id)
  522. set_tag("limit", limit)
  523. has_changed = self._device_federation_outbox_stream_cache.has_entity_changed(
  524. destination, last_stream_id
  525. )
  526. if not has_changed or last_stream_id == current_stream_id:
  527. log_kv({"message": "No new messages in stream"})
  528. return [], current_stream_id
  529. if limit <= 0:
  530. # This can happen if we run out of room for EDUs in the transaction.
  531. return [], last_stream_id
  532. @trace
  533. def get_new_messages_for_remote_destination_txn(
  534. txn: LoggingTransaction,
  535. ) -> Tuple[List[JsonDict], int]:
  536. sql = (
  537. "SELECT stream_id, messages_json FROM device_federation_outbox"
  538. " WHERE destination = ?"
  539. " AND ? < stream_id AND stream_id <= ?"
  540. " ORDER BY stream_id ASC"
  541. " LIMIT ?"
  542. )
  543. txn.execute(sql, (destination, last_stream_id, current_stream_id, limit))
  544. messages = []
  545. stream_pos = current_stream_id
  546. for row in txn:
  547. stream_pos = row[0]
  548. messages.append(db_to_json(row[1]))
  549. # If the limit was not reached we know that there's no more data for this
  550. # user/device pair up to current_stream_id.
  551. if len(messages) < limit:
  552. log_kv({"message": "Set stream position to current position"})
  553. stream_pos = current_stream_id
  554. return messages, stream_pos
  555. return await self.db_pool.runInteraction(
  556. "get_new_device_msgs_for_remote",
  557. get_new_messages_for_remote_destination_txn,
  558. )
  559. @trace
  560. async def delete_device_msgs_for_remote(
  561. self, destination: str, up_to_stream_id: int
  562. ) -> None:
  563. """Used to delete messages when the remote destination acknowledges
  564. their receipt.
  565. Args:
  566. destination: The destination server_name
  567. up_to_stream_id: Where to delete messages up to.
  568. """
  569. def delete_messages_for_remote_destination_txn(txn: LoggingTransaction) -> None:
  570. sql = (
  571. "DELETE FROM device_federation_outbox"
  572. " WHERE destination = ?"
  573. " AND stream_id <= ?"
  574. )
  575. txn.execute(sql, (destination, up_to_stream_id))
  576. await self.db_pool.runInteraction(
  577. "delete_device_msgs_for_remote", delete_messages_for_remote_destination_txn
  578. )
  579. async def get_all_new_device_messages(
  580. self, instance_name: str, last_id: int, current_id: int, limit: int
  581. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  582. """Get updates for to device replication stream.
  583. Args:
  584. instance_name: The writer we want to fetch updates from. Unused
  585. here since there is only ever one writer.
  586. last_id: The token to fetch updates from. Exclusive.
  587. current_id: The token to fetch updates up to. Inclusive.
  588. limit: The requested limit for the number of rows to return. The
  589. function may return more or fewer rows.
  590. Returns:
  591. A tuple consisting of: the updates, a token to use to fetch
  592. subsequent updates, and whether we returned fewer rows than exists
  593. between the requested tokens due to the limit.
  594. The token returned can be used in a subsequent call to this
  595. function to get further updatees.
  596. The updates are a list of 2-tuples of stream ID and the row data
  597. """
  598. if last_id == current_id:
  599. return [], current_id, False
  600. def get_all_new_device_messages_txn(
  601. txn: LoggingTransaction,
  602. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  603. # We limit like this as we might have multiple rows per stream_id, and
  604. # we want to make sure we always get all entries for any stream_id
  605. # we return.
  606. upto_token = min(current_id, last_id + limit)
  607. sql = (
  608. "SELECT max(stream_id), user_id"
  609. " FROM device_inbox"
  610. " WHERE ? < stream_id AND stream_id <= ?"
  611. " GROUP BY user_id"
  612. )
  613. txn.execute(sql, (last_id, upto_token))
  614. updates = [(row[0], row[1:]) for row in txn]
  615. sql = (
  616. "SELECT max(stream_id), destination"
  617. " FROM device_federation_outbox"
  618. " WHERE ? < stream_id AND stream_id <= ?"
  619. " GROUP BY destination"
  620. )
  621. txn.execute(sql, (last_id, upto_token))
  622. updates.extend((row[0], row[1:]) for row in txn)
  623. # Order by ascending stream ordering
  624. updates.sort()
  625. return updates, upto_token, upto_token < current_id
  626. return await self.db_pool.runInteraction(
  627. "get_all_new_device_messages", get_all_new_device_messages_txn
  628. )
  629. @trace
  630. async def add_messages_to_device_inbox(
  631. self,
  632. local_messages_by_user_then_device: Dict[str, Dict[str, JsonDict]],
  633. remote_messages_by_destination: Dict[str, JsonDict],
  634. ) -> int:
  635. """Used to send messages from this server.
  636. Args:
  637. local_messages_by_user_then_device:
  638. Dictionary of recipient user_id to recipient device_id to message.
  639. remote_messages_by_destination:
  640. Dictionary of destination server_name to the EDU JSON to send.
  641. Returns:
  642. The new stream_id.
  643. """
  644. assert self._can_write_to_device
  645. def add_messages_txn(
  646. txn: LoggingTransaction, now_ms: int, stream_id: int
  647. ) -> None:
  648. # Add the local messages directly to the local inbox.
  649. self._add_messages_to_local_device_inbox_txn(
  650. txn, stream_id, local_messages_by_user_then_device
  651. )
  652. # Add the remote messages to the federation outbox.
  653. # We'll send them to a remote server when we next send a
  654. # federation transaction to that destination.
  655. self.db_pool.simple_insert_many_txn(
  656. txn,
  657. table="device_federation_outbox",
  658. keys=(
  659. "destination",
  660. "stream_id",
  661. "queued_ts",
  662. "messages_json",
  663. "instance_name",
  664. ),
  665. values=[
  666. (
  667. destination,
  668. stream_id,
  669. now_ms,
  670. json_encoder.encode(edu),
  671. self._instance_name,
  672. )
  673. for destination, edu in remote_messages_by_destination.items()
  674. ],
  675. )
  676. for destination, edu in remote_messages_by_destination.items():
  677. if issue9533_logger.isEnabledFor(logging.DEBUG):
  678. issue9533_logger.debug(
  679. "Queued outgoing to-device messages with "
  680. "stream_id %i, EDU message_id %s, type %s for %s: %s",
  681. stream_id,
  682. edu["message_id"],
  683. edu["type"],
  684. destination,
  685. [
  686. f"{user_id}/{device_id} (msgid "
  687. f"{msg.get(EventContentFields.TO_DEVICE_MSGID)})"
  688. for (user_id, messages_by_device) in edu["messages"].items()
  689. for (device_id, msg) in messages_by_device.items()
  690. ],
  691. )
  692. for user_id, messages_by_device in edu["messages"].items():
  693. for device_id, msg in messages_by_device.items():
  694. with start_active_span("store_outgoing_to_device_message"):
  695. set_tag(SynapseTags.TO_DEVICE_EDU_ID, edu["sender"])
  696. set_tag(SynapseTags.TO_DEVICE_EDU_ID, edu["message_id"])
  697. set_tag(SynapseTags.TO_DEVICE_TYPE, edu["type"])
  698. set_tag(SynapseTags.TO_DEVICE_RECIPIENT, user_id)
  699. set_tag(SynapseTags.TO_DEVICE_RECIPIENT_DEVICE, device_id)
  700. set_tag(
  701. SynapseTags.TO_DEVICE_MSGID,
  702. msg.get(EventContentFields.TO_DEVICE_MSGID),
  703. )
  704. async with self._to_device_msg_id_gen.get_next() as stream_id:
  705. now_ms = self._clock.time_msec()
  706. await self.db_pool.runInteraction(
  707. "add_messages_to_device_inbox", add_messages_txn, now_ms, stream_id
  708. )
  709. for user_id in local_messages_by_user_then_device.keys():
  710. self._device_inbox_stream_cache.entity_has_changed(user_id, stream_id)
  711. for destination in remote_messages_by_destination.keys():
  712. self._device_federation_outbox_stream_cache.entity_has_changed(
  713. destination, stream_id
  714. )
  715. return self._to_device_msg_id_gen.get_current_token()
  716. async def add_messages_from_remote_to_device_inbox(
  717. self,
  718. origin: str,
  719. message_id: str,
  720. local_messages_by_user_then_device: Dict[str, Dict[str, JsonDict]],
  721. ) -> int:
  722. assert self._can_write_to_device
  723. def add_messages_txn(
  724. txn: LoggingTransaction, now_ms: int, stream_id: int
  725. ) -> None:
  726. # Check if we've already inserted a matching message_id for that
  727. # origin. This can happen if the origin doesn't receive our
  728. # acknowledgement from the first time we received the message.
  729. already_inserted = self.db_pool.simple_select_one_txn(
  730. txn,
  731. table="device_federation_inbox",
  732. keyvalues={"origin": origin, "message_id": message_id},
  733. retcols=("message_id",),
  734. allow_none=True,
  735. )
  736. if already_inserted is not None:
  737. return
  738. # Add an entry for this message_id so that we know we've processed
  739. # it.
  740. self.db_pool.simple_insert_txn(
  741. txn,
  742. table="device_federation_inbox",
  743. values={
  744. "origin": origin,
  745. "message_id": message_id,
  746. "received_ts": now_ms,
  747. },
  748. )
  749. # Add the messages to the appropriate local device inboxes so that
  750. # they'll be sent to the devices when they next sync.
  751. self._add_messages_to_local_device_inbox_txn(
  752. txn, stream_id, local_messages_by_user_then_device
  753. )
  754. async with self._to_device_msg_id_gen.get_next() as stream_id:
  755. now_ms = self._clock.time_msec()
  756. await self.db_pool.runInteraction(
  757. "add_messages_from_remote_to_device_inbox",
  758. add_messages_txn,
  759. now_ms,
  760. stream_id,
  761. )
  762. for user_id in local_messages_by_user_then_device.keys():
  763. self._device_inbox_stream_cache.entity_has_changed(user_id, stream_id)
  764. return stream_id
  765. def _add_messages_to_local_device_inbox_txn(
  766. self,
  767. txn: LoggingTransaction,
  768. stream_id: int,
  769. messages_by_user_then_device: Dict[str, Dict[str, JsonDict]],
  770. ) -> None:
  771. assert self._can_write_to_device
  772. local_by_user_then_device = {}
  773. for user_id, messages_by_device in messages_by_user_then_device.items():
  774. messages_json_for_user = {}
  775. devices = list(messages_by_device.keys())
  776. if len(devices) == 1 and devices[0] == "*":
  777. # Handle wildcard device_ids.
  778. # We exclude hidden devices (such as cross-signing keys) here as they are
  779. # not expected to receive to-device messages.
  780. devices = self.db_pool.simple_select_onecol_txn(
  781. txn,
  782. table="devices",
  783. keyvalues={"user_id": user_id, "hidden": False},
  784. retcol="device_id",
  785. )
  786. message_json = json_encoder.encode(messages_by_device["*"])
  787. for device_id in devices:
  788. # Add the message for all devices for this user on this
  789. # server.
  790. messages_json_for_user[device_id] = message_json
  791. else:
  792. if not devices:
  793. continue
  794. # We exclude hidden devices (such as cross-signing keys) here as they are
  795. # not expected to receive to-device messages.
  796. rows = cast(
  797. List[Tuple[str]],
  798. self.db_pool.simple_select_many_txn(
  799. txn,
  800. table="devices",
  801. keyvalues={"user_id": user_id, "hidden": False},
  802. column="device_id",
  803. iterable=devices,
  804. retcols=("device_id",),
  805. ),
  806. )
  807. for (device_id,) in rows:
  808. # Only insert into the local inbox if the device exists on
  809. # this server
  810. with start_active_span("serialise_to_device_message"):
  811. msg = messages_by_device[device_id]
  812. set_tag(SynapseTags.TO_DEVICE_TYPE, msg["type"])
  813. set_tag(SynapseTags.TO_DEVICE_SENDER, msg["sender"])
  814. set_tag(SynapseTags.TO_DEVICE_RECIPIENT, user_id)
  815. set_tag(SynapseTags.TO_DEVICE_RECIPIENT_DEVICE, device_id)
  816. set_tag(
  817. SynapseTags.TO_DEVICE_MSGID,
  818. msg["content"].get(EventContentFields.TO_DEVICE_MSGID),
  819. )
  820. message_json = json_encoder.encode(msg)
  821. messages_json_for_user[device_id] = message_json
  822. if messages_json_for_user:
  823. local_by_user_then_device[user_id] = messages_json_for_user
  824. if not local_by_user_then_device:
  825. return
  826. self.db_pool.simple_insert_many_txn(
  827. txn,
  828. table="device_inbox",
  829. keys=("user_id", "device_id", "stream_id", "message_json", "instance_name"),
  830. values=[
  831. (user_id, device_id, stream_id, message_json, self._instance_name)
  832. for user_id, messages_by_device in local_by_user_then_device.items()
  833. for device_id, message_json in messages_by_device.items()
  834. ],
  835. )
  836. if issue9533_logger.isEnabledFor(logging.DEBUG):
  837. issue9533_logger.debug(
  838. "Stored to-device messages with stream_id %i: %s",
  839. stream_id,
  840. [
  841. f"{user_id}/{device_id} (msgid "
  842. f"{msg['content'].get(EventContentFields.TO_DEVICE_MSGID)})"
  843. for (
  844. user_id,
  845. messages_by_device,
  846. ) in messages_by_user_then_device.items()
  847. for (device_id, msg) in messages_by_device.items()
  848. ],
  849. )
  850. class DeviceInboxBackgroundUpdateStore(SQLBaseStore):
  851. DEVICE_INBOX_STREAM_ID = "device_inbox_stream_drop"
  852. REMOVE_DEAD_DEVICES_FROM_INBOX = "remove_dead_devices_from_device_inbox"
  853. def __init__(
  854. self,
  855. database: DatabasePool,
  856. db_conn: LoggingDatabaseConnection,
  857. hs: "HomeServer",
  858. ):
  859. super().__init__(database, db_conn, hs)
  860. self.db_pool.updates.register_background_index_update(
  861. "device_inbox_stream_index",
  862. index_name="device_inbox_stream_id_user_id",
  863. table="device_inbox",
  864. columns=["stream_id", "user_id"],
  865. )
  866. self.db_pool.updates.register_background_update_handler(
  867. self.DEVICE_INBOX_STREAM_ID, self._background_drop_index_device_inbox
  868. )
  869. self.db_pool.updates.register_background_update_handler(
  870. self.REMOVE_DEAD_DEVICES_FROM_INBOX,
  871. self._remove_dead_devices_from_device_inbox,
  872. )
  873. async def _background_drop_index_device_inbox(
  874. self, progress: JsonDict, batch_size: int
  875. ) -> int:
  876. def reindex_txn(conn: LoggingDatabaseConnection) -> None:
  877. txn = conn.cursor()
  878. txn.execute("DROP INDEX IF EXISTS device_inbox_stream_id")
  879. txn.close()
  880. await self.db_pool.runWithConnection(reindex_txn)
  881. await self.db_pool.updates._end_background_update(self.DEVICE_INBOX_STREAM_ID)
  882. return 1
  883. async def _remove_dead_devices_from_device_inbox(
  884. self,
  885. progress: JsonDict,
  886. batch_size: int,
  887. ) -> int:
  888. """A background update to remove devices that were either deleted or hidden from
  889. the device_inbox table.
  890. Args:
  891. progress: The update's progress dict.
  892. batch_size: The batch size for this update.
  893. Returns:
  894. The number of rows deleted.
  895. """
  896. def _remove_dead_devices_from_device_inbox_txn(
  897. txn: LoggingTransaction,
  898. ) -> Tuple[int, bool]:
  899. if "max_stream_id" in progress:
  900. max_stream_id = progress["max_stream_id"]
  901. else:
  902. txn.execute("SELECT max(stream_id) FROM device_inbox")
  903. # There's a type mismatch here between how we want to type the row and
  904. # what fetchone says it returns, but we silence it because we know that
  905. # res can't be None.
  906. res = cast(Tuple[Optional[int]], txn.fetchone())
  907. if res[0] is None:
  908. # this can only happen if the `device_inbox` table is empty, in which
  909. # case we have no work to do.
  910. return 0, True
  911. else:
  912. max_stream_id = res[0]
  913. start = progress.get("stream_id", 0)
  914. stop = start + batch_size
  915. # delete rows in `device_inbox` which do *not* correspond to a known,
  916. # unhidden device.
  917. sql = """
  918. DELETE FROM device_inbox
  919. WHERE
  920. stream_id >= ? AND stream_id < ?
  921. AND NOT EXISTS (
  922. SELECT * FROM devices d
  923. WHERE
  924. d.device_id=device_inbox.device_id
  925. AND d.user_id=device_inbox.user_id
  926. AND NOT hidden
  927. )
  928. """
  929. txn.execute(sql, (start, stop))
  930. self.db_pool.updates._background_update_progress_txn(
  931. txn,
  932. self.REMOVE_DEAD_DEVICES_FROM_INBOX,
  933. {
  934. "stream_id": stop,
  935. "max_stream_id": max_stream_id,
  936. },
  937. )
  938. return stop > max_stream_id
  939. finished = await self.db_pool.runInteraction(
  940. "_remove_devices_from_device_inbox_txn",
  941. _remove_dead_devices_from_device_inbox_txn,
  942. )
  943. if finished:
  944. await self.db_pool.updates._end_background_update(
  945. self.REMOVE_DEAD_DEVICES_FROM_INBOX,
  946. )
  947. return batch_size
  948. class DeviceInboxStore(DeviceInboxWorkerStore, DeviceInboxBackgroundUpdateStore):
  949. pass