25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

2248 satır
81 KiB

  1. # Copyright 2016 OpenMarket Ltd
  2. # Copyright 2019 New Vector Ltd
  3. # Copyright 2019,2020 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 (
  18. TYPE_CHECKING,
  19. Any,
  20. Collection,
  21. Dict,
  22. Iterable,
  23. List,
  24. Optional,
  25. Set,
  26. Tuple,
  27. cast,
  28. )
  29. from typing_extensions import Literal
  30. from synapse.api.constants import EduTypes
  31. from synapse.api.errors import Codes, StoreError
  32. from synapse.logging.opentracing import (
  33. get_active_span_text_map,
  34. set_tag,
  35. trace,
  36. whitelisted_homeserver,
  37. )
  38. from synapse.metrics.background_process_metrics import wrap_as_background_process
  39. from synapse.replication.tcp.streams._base import DeviceListsStream
  40. from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause
  41. from synapse.storage.database import (
  42. DatabasePool,
  43. LoggingDatabaseConnection,
  44. LoggingTransaction,
  45. make_tuple_comparison_clause,
  46. )
  47. from synapse.storage.databases.main.end_to_end_keys import EndToEndKeyWorkerStore
  48. from synapse.storage.databases.main.roommember import RoomMemberWorkerStore
  49. from synapse.storage.types import Cursor
  50. from synapse.storage.util.id_generators import (
  51. AbstractStreamIdGenerator,
  52. AbstractStreamIdTracker,
  53. StreamIdGenerator,
  54. )
  55. from synapse.types import JsonDict, StrCollection, get_verify_key_from_cross_signing_key
  56. from synapse.util import json_decoder, json_encoder
  57. from synapse.util.caches.descriptors import cached, cachedList
  58. from synapse.util.caches.lrucache import LruCache
  59. from synapse.util.caches.stream_change_cache import (
  60. AllEntitiesChangedResult,
  61. StreamChangeCache,
  62. )
  63. from synapse.util.cancellation import cancellable
  64. from synapse.util.iterutils import batch_iter
  65. from synapse.util.stringutils import shortstr
  66. if TYPE_CHECKING:
  67. from synapse.server import HomeServer
  68. logger = logging.getLogger(__name__)
  69. issue_8631_logger = logging.getLogger("synapse.8631_debug")
  70. DROP_DEVICE_LIST_STREAMS_NON_UNIQUE_INDEXES = (
  71. "drop_device_list_streams_non_unique_indexes"
  72. )
  73. BG_UPDATE_REMOVE_DUP_OUTBOUND_POKES = "remove_dup_outbound_pokes"
  74. class DeviceWorkerStore(RoomMemberWorkerStore, EndToEndKeyWorkerStore):
  75. def __init__(
  76. self,
  77. database: DatabasePool,
  78. db_conn: LoggingDatabaseConnection,
  79. hs: "HomeServer",
  80. ):
  81. super().__init__(database, db_conn, hs)
  82. # In the worker store this is an ID tracker which we overwrite in the non-worker
  83. # class below that is used on the main process.
  84. self._device_list_id_gen: AbstractStreamIdTracker = StreamIdGenerator(
  85. db_conn,
  86. hs.get_replication_notifier(),
  87. "device_lists_stream",
  88. "stream_id",
  89. extra_tables=[
  90. ("user_signature_stream", "stream_id"),
  91. ("device_lists_outbound_pokes", "stream_id"),
  92. ("device_lists_changes_in_room", "stream_id"),
  93. ("device_lists_remote_pending", "stream_id"),
  94. ],
  95. is_writer=hs.config.worker.worker_app is None,
  96. )
  97. # Type-ignore: _device_list_id_gen is mixed in from either DataStore (as a
  98. # StreamIdGenerator) or SlavedDataStore (as a SlavedIdTracker).
  99. device_list_max = self._device_list_id_gen.get_current_token()
  100. device_list_prefill, min_device_list_id = self.db_pool.get_cache_dict(
  101. db_conn,
  102. "device_lists_stream",
  103. entity_column="user_id",
  104. stream_column="stream_id",
  105. max_value=device_list_max,
  106. limit=10000,
  107. )
  108. self._device_list_stream_cache = StreamChangeCache(
  109. "DeviceListStreamChangeCache",
  110. min_device_list_id,
  111. prefilled_cache=device_list_prefill,
  112. )
  113. (
  114. user_signature_stream_prefill,
  115. user_signature_stream_list_id,
  116. ) = self.db_pool.get_cache_dict(
  117. db_conn,
  118. "user_signature_stream",
  119. entity_column="from_user_id",
  120. stream_column="stream_id",
  121. max_value=device_list_max,
  122. limit=1000,
  123. )
  124. self._user_signature_stream_cache = StreamChangeCache(
  125. "UserSignatureStreamChangeCache",
  126. user_signature_stream_list_id,
  127. prefilled_cache=user_signature_stream_prefill,
  128. )
  129. (
  130. device_list_federation_prefill,
  131. device_list_federation_list_id,
  132. ) = self.db_pool.get_cache_dict(
  133. db_conn,
  134. "device_lists_outbound_pokes",
  135. entity_column="destination",
  136. stream_column="stream_id",
  137. max_value=device_list_max,
  138. limit=10000,
  139. )
  140. self._device_list_federation_stream_cache = StreamChangeCache(
  141. "DeviceListFederationStreamChangeCache",
  142. device_list_federation_list_id,
  143. prefilled_cache=device_list_federation_prefill,
  144. )
  145. if hs.config.worker.run_background_tasks:
  146. self._clock.looping_call(
  147. self._prune_old_outbound_device_pokes, 60 * 60 * 1000
  148. )
  149. def process_replication_rows(
  150. self, stream_name: str, instance_name: str, token: int, rows: Iterable[Any]
  151. ) -> None:
  152. if stream_name == DeviceListsStream.NAME:
  153. self._invalidate_caches_for_devices(token, rows)
  154. return super().process_replication_rows(stream_name, instance_name, token, rows)
  155. def process_replication_position(
  156. self, stream_name: str, instance_name: str, token: int
  157. ) -> None:
  158. if stream_name == DeviceListsStream.NAME:
  159. self._device_list_id_gen.advance(instance_name, token)
  160. super().process_replication_position(stream_name, instance_name, token)
  161. def _invalidate_caches_for_devices(
  162. self, token: int, rows: Iterable[DeviceListsStream.DeviceListsStreamRow]
  163. ) -> None:
  164. for row in rows:
  165. if row.is_signature:
  166. self._user_signature_stream_cache.entity_has_changed(row.entity, token)
  167. continue
  168. # The entities are either user IDs (starting with '@') whose devices
  169. # have changed, or remote servers that we need to tell about
  170. # changes.
  171. if row.entity.startswith("@"):
  172. self._device_list_stream_cache.entity_has_changed(row.entity, token)
  173. self.get_cached_devices_for_user.invalidate((row.entity,))
  174. self._get_cached_user_device.invalidate((row.entity,))
  175. self.get_device_list_last_stream_id_for_remote.invalidate((row.entity,))
  176. else:
  177. self._device_list_federation_stream_cache.entity_has_changed(
  178. row.entity, token
  179. )
  180. def get_device_stream_token(self) -> int:
  181. return self._device_list_id_gen.get_current_token()
  182. async def count_devices_by_users(self, user_ids: Optional[List[str]] = None) -> int:
  183. """Retrieve number of all devices of given users.
  184. Only returns number of devices that are not marked as hidden.
  185. Args:
  186. user_ids: The IDs of the users which owns devices
  187. Returns:
  188. Number of devices of this users.
  189. """
  190. def count_devices_by_users_txn(
  191. txn: LoggingTransaction, user_ids: List[str]
  192. ) -> int:
  193. sql = """
  194. SELECT count(*)
  195. FROM devices
  196. WHERE
  197. hidden = '0' AND
  198. """
  199. clause, args = make_in_list_sql_clause(
  200. txn.database_engine, "user_id", user_ids
  201. )
  202. txn.execute(sql + clause, args)
  203. return cast(Tuple[int], txn.fetchone())[0]
  204. if not user_ids:
  205. return 0
  206. return await self.db_pool.runInteraction(
  207. "count_devices_by_users", count_devices_by_users_txn, user_ids
  208. )
  209. async def get_device(
  210. self, user_id: str, device_id: str
  211. ) -> Optional[Dict[str, Any]]:
  212. """Retrieve a device. Only returns devices that are not marked as
  213. hidden.
  214. Args:
  215. user_id: The ID of the user which owns the device
  216. device_id: The ID of the device to retrieve
  217. Returns:
  218. A dict containing the device information, or `None` if the device does not
  219. exist.
  220. """
  221. return await self.db_pool.simple_select_one(
  222. table="devices",
  223. keyvalues={"user_id": user_id, "device_id": device_id, "hidden": False},
  224. retcols=("user_id", "device_id", "display_name"),
  225. desc="get_device",
  226. allow_none=True,
  227. )
  228. async def get_device_opt(
  229. self, user_id: str, device_id: str
  230. ) -> Optional[Dict[str, Any]]:
  231. """Retrieve a device. Only returns devices that are not marked as
  232. hidden.
  233. Args:
  234. user_id: The ID of the user which owns the device
  235. device_id: The ID of the device to retrieve
  236. Returns:
  237. A dict containing the device information, or None if the device does not exist.
  238. """
  239. return await self.db_pool.simple_select_one(
  240. table="devices",
  241. keyvalues={"user_id": user_id, "device_id": device_id, "hidden": False},
  242. retcols=("user_id", "device_id", "display_name"),
  243. desc="get_device",
  244. allow_none=True,
  245. )
  246. async def get_devices_by_user(self, user_id: str) -> Dict[str, Dict[str, str]]:
  247. """Retrieve all of a user's registered devices. Only returns devices
  248. that are not marked as hidden.
  249. Args:
  250. user_id:
  251. Returns:
  252. A mapping from device_id to a dict containing "device_id", "user_id"
  253. and "display_name" for each device.
  254. """
  255. devices = await self.db_pool.simple_select_list(
  256. table="devices",
  257. keyvalues={"user_id": user_id, "hidden": False},
  258. retcols=("user_id", "device_id", "display_name"),
  259. desc="get_devices_by_user",
  260. )
  261. return {d["device_id"]: d for d in devices}
  262. async def get_devices_by_auth_provider_session_id(
  263. self, auth_provider_id: str, auth_provider_session_id: str
  264. ) -> List[Dict[str, Any]]:
  265. """Retrieve the list of devices associated with a SSO IdP session ID.
  266. Args:
  267. auth_provider_id: The SSO IdP ID as defined in the server config
  268. auth_provider_session_id: The session ID within the IdP
  269. Returns:
  270. A list of dicts containing the device_id and the user_id of each device
  271. """
  272. return await self.db_pool.simple_select_list(
  273. table="device_auth_providers",
  274. keyvalues={
  275. "auth_provider_id": auth_provider_id,
  276. "auth_provider_session_id": auth_provider_session_id,
  277. },
  278. retcols=("user_id", "device_id"),
  279. desc="get_devices_by_auth_provider_session_id",
  280. )
  281. @trace
  282. async def get_device_updates_by_remote(
  283. self, destination: str, from_stream_id: int, limit: int
  284. ) -> Tuple[int, List[Tuple[str, JsonDict]]]:
  285. """Get a stream of device updates to send to the given remote server.
  286. Args:
  287. destination: The host the device updates are intended for
  288. from_stream_id: The minimum stream_id to filter updates by, exclusive
  289. limit: Maximum number of device updates to return
  290. Returns:
  291. - The current stream id (i.e. the stream id of the last update included
  292. in the response); and
  293. - The list of updates, where each update is a pair of EDU type and
  294. EDU contents.
  295. """
  296. now_stream_id = self.get_device_stream_token()
  297. has_changed = self._device_list_federation_stream_cache.has_entity_changed(
  298. destination, int(from_stream_id)
  299. )
  300. if not has_changed:
  301. # debugging for https://github.com/matrix-org/synapse/issues/14251
  302. issue_8631_logger.debug(
  303. "%s: no change between %i and %i",
  304. destination,
  305. from_stream_id,
  306. now_stream_id,
  307. )
  308. return now_stream_id, []
  309. updates = await self.db_pool.runInteraction(
  310. "get_device_updates_by_remote",
  311. self._get_device_updates_by_remote_txn,
  312. destination,
  313. from_stream_id,
  314. now_stream_id,
  315. limit,
  316. )
  317. # We need to ensure `updates` doesn't grow too big.
  318. # Currently: `len(updates) <= limit`.
  319. # Return an empty list if there are no updates
  320. if not updates:
  321. return now_stream_id, []
  322. if issue_8631_logger.isEnabledFor(logging.DEBUG):
  323. data = {(user, device): stream_id for user, device, stream_id, _ in updates}
  324. issue_8631_logger.debug(
  325. "device updates need to be sent to %s: %s", destination, data
  326. )
  327. # get the cross-signing keys of the users in the list, so that we can
  328. # determine which of the device changes were cross-signing keys
  329. users = {r[0] for r in updates}
  330. master_key_by_user = {}
  331. self_signing_key_by_user = {}
  332. for user in users:
  333. cross_signing_key = await self.get_e2e_cross_signing_key(user, "master")
  334. if cross_signing_key:
  335. key_id, verify_key = get_verify_key_from_cross_signing_key(
  336. cross_signing_key
  337. )
  338. # verify_key is a VerifyKey from signedjson, which uses
  339. # .version to denote the portion of the key ID after the
  340. # algorithm and colon, which is the device ID
  341. master_key_by_user[user] = {
  342. "key_info": cross_signing_key,
  343. "device_id": verify_key.version,
  344. }
  345. cross_signing_key = await self.get_e2e_cross_signing_key(
  346. user, "self_signing"
  347. )
  348. if cross_signing_key:
  349. key_id, verify_key = get_verify_key_from_cross_signing_key(
  350. cross_signing_key
  351. )
  352. self_signing_key_by_user[user] = {
  353. "key_info": cross_signing_key,
  354. "device_id": verify_key.version,
  355. }
  356. # Perform the equivalent of a GROUP BY
  357. #
  358. # Iterate through the updates list and copy non-duplicate
  359. # (user_id, device_id) entries into a map, with the value being
  360. # the max stream_id across each set of duplicate entries
  361. #
  362. # maps (user_id, device_id) -> (stream_id, opentracing_context)
  363. #
  364. # opentracing_context contains the opentracing metadata for the request
  365. # that created the poke
  366. #
  367. # The most recent request's opentracing_context is used as the
  368. # context which created the Edu.
  369. # This is the stream ID that we will return for the consumer to resume
  370. # following this stream later.
  371. last_processed_stream_id = from_stream_id
  372. # A map of (user ID, device ID) to (stream ID, context).
  373. query_map: Dict[Tuple[str, str], Tuple[int, Optional[str]]] = {}
  374. cross_signing_keys_by_user: Dict[str, Dict[str, object]] = {}
  375. for user_id, device_id, update_stream_id, update_context in updates:
  376. # Calculate the remaining length budget.
  377. # Note that, for now, each entry in `cross_signing_keys_by_user`
  378. # gives rise to two device updates in the result, so those cost twice
  379. # as much (and are the whole reason we need to separately calculate
  380. # the budget; we know len(updates) <= limit otherwise!)
  381. # N.B. len() on dicts is cheap since they store their size.
  382. remaining_length_budget = limit - (
  383. len(query_map) + 2 * len(cross_signing_keys_by_user)
  384. )
  385. assert remaining_length_budget >= 0
  386. is_master_key_update = (
  387. user_id in master_key_by_user
  388. and device_id == master_key_by_user[user_id]["device_id"]
  389. )
  390. is_self_signing_key_update = (
  391. user_id in self_signing_key_by_user
  392. and device_id == self_signing_key_by_user[user_id]["device_id"]
  393. )
  394. is_cross_signing_key_update = (
  395. is_master_key_update or is_self_signing_key_update
  396. )
  397. if (
  398. is_cross_signing_key_update
  399. and user_id not in cross_signing_keys_by_user
  400. ):
  401. # This will give rise to 2 device updates.
  402. # If we don't have the budget, stop here!
  403. if remaining_length_budget < 2:
  404. break
  405. if is_master_key_update:
  406. result = cross_signing_keys_by_user.setdefault(user_id, {})
  407. result["master_key"] = master_key_by_user[user_id]["key_info"]
  408. elif is_self_signing_key_update:
  409. result = cross_signing_keys_by_user.setdefault(user_id, {})
  410. result["self_signing_key"] = self_signing_key_by_user[user_id][
  411. "key_info"
  412. ]
  413. else:
  414. key = (user_id, device_id)
  415. if key not in query_map and remaining_length_budget < 1:
  416. # We don't have space for a new entry
  417. break
  418. previous_update_stream_id, _ = query_map.get(key, (0, None))
  419. if update_stream_id > previous_update_stream_id:
  420. # FIXME If this overwrites an older update, this discards the
  421. # previous OpenTracing context.
  422. # It might make it harder to track down issues using OpenTracing.
  423. # If there's a good reason why it doesn't matter, a comment here
  424. # about that would not hurt.
  425. query_map[key] = (update_stream_id, update_context)
  426. # As this update has been added to the response, advance the stream
  427. # position.
  428. last_processed_stream_id = update_stream_id
  429. # In the worst case scenario, each update is for a distinct user and is
  430. # added either to the query_map or to cross_signing_keys_by_user,
  431. # but not both:
  432. # len(query_map) + len(cross_signing_keys_by_user) <= len(updates) here,
  433. # so len(query_map) + len(cross_signing_keys_by_user) <= limit.
  434. results = await self._get_device_update_edus_by_remote(
  435. destination, from_stream_id, query_map
  436. )
  437. # len(results) <= len(query_map) here,
  438. # so len(results) + len(cross_signing_keys_by_user) <= limit.
  439. # Add the updated cross-signing keys to the results list
  440. for user_id, result in cross_signing_keys_by_user.items():
  441. result["user_id"] = user_id
  442. results.append((EduTypes.SIGNING_KEY_UPDATE, result))
  443. # also send the unstable version
  444. # FIXME: remove this when enough servers have upgraded
  445. # and remove the length budgeting above.
  446. results.append(("org.matrix.signing_key_update", result))
  447. if issue_8631_logger.isEnabledFor(logging.DEBUG):
  448. for (user_id, edu) in results:
  449. issue_8631_logger.debug(
  450. "device update to %s for %s from %s to %s: %s",
  451. destination,
  452. user_id,
  453. from_stream_id,
  454. last_processed_stream_id,
  455. edu,
  456. )
  457. return last_processed_stream_id, results
  458. def _get_device_updates_by_remote_txn(
  459. self,
  460. txn: LoggingTransaction,
  461. destination: str,
  462. from_stream_id: int,
  463. now_stream_id: int,
  464. limit: int,
  465. ) -> List[Tuple[str, str, int, Optional[str]]]:
  466. """Return device update information for a given remote destination
  467. Args:
  468. txn: The transaction to execute
  469. destination: The host the device updates are intended for
  470. from_stream_id: The minimum stream_id to filter updates by, exclusive
  471. now_stream_id: The maximum stream_id to filter updates by, inclusive
  472. limit: Maximum number of device updates to return
  473. Returns:
  474. List of device update tuples:
  475. - user_id
  476. - device_id
  477. - stream_id
  478. - opentracing_context
  479. """
  480. # get the list of device updates that need to be sent
  481. sql = """
  482. SELECT user_id, device_id, stream_id, opentracing_context FROM device_lists_outbound_pokes
  483. WHERE destination = ? AND ? < stream_id AND stream_id <= ?
  484. ORDER BY stream_id
  485. LIMIT ?
  486. """
  487. txn.execute(sql, (destination, from_stream_id, now_stream_id, limit))
  488. return cast(List[Tuple[str, str, int, Optional[str]]], txn.fetchall())
  489. async def _get_device_update_edus_by_remote(
  490. self,
  491. destination: str,
  492. from_stream_id: int,
  493. query_map: Dict[Tuple[str, str], Tuple[int, Optional[str]]],
  494. ) -> List[Tuple[str, dict]]:
  495. """Returns a list of device update EDUs as well as E2EE keys
  496. Args:
  497. destination: The host the device updates are intended for
  498. from_stream_id: The minimum stream_id to filter updates by, exclusive
  499. query_map: Dictionary mapping (user_id, device_id) to
  500. (update stream_id, the relevant json-encoded opentracing context)
  501. Returns:
  502. List of objects representing a device update EDU.
  503. Postconditions:
  504. The returned list has a length not exceeding that of the query_map:
  505. len(result) <= len(query_map)
  506. """
  507. devices = (
  508. await self.get_e2e_device_keys_and_signatures(
  509. # Because these are (user_id, device_id) tuples with all
  510. # device_ids not being None, the returned list's length will not
  511. # exceed that of query_map.
  512. query_map.keys(),
  513. include_all_devices=True,
  514. include_deleted_devices=True,
  515. )
  516. if query_map
  517. else {}
  518. )
  519. results = []
  520. for user_id, user_devices in devices.items():
  521. # The prev_id for the first row is always the last row before
  522. # `from_stream_id`
  523. prev_id = await self._get_last_device_update_for_remote_user(
  524. destination, user_id, from_stream_id
  525. )
  526. # make sure we go through the devices in stream order
  527. device_ids = sorted(
  528. user_devices.keys(),
  529. key=lambda i: query_map[(user_id, i)][0],
  530. )
  531. for device_id in device_ids:
  532. device = user_devices[device_id]
  533. stream_id, opentracing_context = query_map[(user_id, device_id)]
  534. result = {
  535. "user_id": user_id,
  536. "device_id": device_id,
  537. "prev_id": [prev_id] if prev_id else [],
  538. "stream_id": stream_id,
  539. }
  540. if opentracing_context != "{}":
  541. result["org.matrix.opentracing_context"] = opentracing_context
  542. prev_id = stream_id
  543. if device is not None:
  544. keys = device.keys
  545. if keys:
  546. result["keys"] = keys
  547. device_display_name = None
  548. if (
  549. self.hs.config.federation.allow_device_name_lookup_over_federation
  550. ):
  551. device_display_name = device.display_name
  552. if device_display_name:
  553. result["device_display_name"] = device_display_name
  554. else:
  555. result["deleted"] = True
  556. results.append((EduTypes.DEVICE_LIST_UPDATE, result))
  557. return results
  558. async def _get_last_device_update_for_remote_user(
  559. self, destination: str, user_id: str, from_stream_id: int
  560. ) -> int:
  561. def f(txn: LoggingTransaction) -> int:
  562. prev_sent_id_sql = """
  563. SELECT coalesce(max(stream_id), 0) as stream_id
  564. FROM device_lists_outbound_last_success
  565. WHERE destination = ? AND user_id = ? AND stream_id <= ?
  566. """
  567. txn.execute(prev_sent_id_sql, (destination, user_id, from_stream_id))
  568. rows = txn.fetchall()
  569. return rows[0][0]
  570. return await self.db_pool.runInteraction(
  571. "get_last_device_update_for_remote_user", f
  572. )
  573. async def mark_as_sent_devices_by_remote(
  574. self, destination: str, stream_id: int
  575. ) -> None:
  576. """Mark that updates have successfully been sent to the destination."""
  577. await self.db_pool.runInteraction(
  578. "mark_as_sent_devices_by_remote",
  579. self._mark_as_sent_devices_by_remote_txn,
  580. destination,
  581. stream_id,
  582. )
  583. def _mark_as_sent_devices_by_remote_txn(
  584. self, txn: LoggingTransaction, destination: str, stream_id: int
  585. ) -> None:
  586. # We update the device_lists_outbound_last_success with the successfully
  587. # poked users.
  588. sql = """
  589. SELECT user_id, coalesce(max(o.stream_id), 0)
  590. FROM device_lists_outbound_pokes as o
  591. WHERE destination = ? AND o.stream_id <= ?
  592. GROUP BY user_id
  593. """
  594. txn.execute(sql, (destination, stream_id))
  595. rows = txn.fetchall()
  596. self.db_pool.simple_upsert_many_txn(
  597. txn=txn,
  598. table="device_lists_outbound_last_success",
  599. key_names=("destination", "user_id"),
  600. key_values=[(destination, user_id) for user_id, _ in rows],
  601. value_names=("stream_id",),
  602. value_values=((stream_id,) for _, stream_id in rows),
  603. )
  604. # Delete all sent outbound pokes
  605. sql = """
  606. DELETE FROM device_lists_outbound_pokes
  607. WHERE destination = ? AND stream_id <= ?
  608. """
  609. txn.execute(sql, (destination, stream_id))
  610. async def add_user_signature_change_to_streams(
  611. self, from_user_id: str, user_ids: List[str]
  612. ) -> int:
  613. """Persist that a user has made new signatures
  614. Args:
  615. from_user_id: the user who made the signatures
  616. user_ids: the users who were signed
  617. Returns:
  618. The new stream ID.
  619. """
  620. # TODO: this looks like it's _writing_. Should this be on DeviceStore rather
  621. # than DeviceWorkerStore?
  622. async with self._device_list_id_gen.get_next() as stream_id: # type: ignore[attr-defined]
  623. await self.db_pool.runInteraction(
  624. "add_user_sig_change_to_streams",
  625. self._add_user_signature_change_txn,
  626. from_user_id,
  627. user_ids,
  628. stream_id,
  629. )
  630. return stream_id
  631. def _add_user_signature_change_txn(
  632. self,
  633. txn: LoggingTransaction,
  634. from_user_id: str,
  635. user_ids: List[str],
  636. stream_id: int,
  637. ) -> None:
  638. txn.call_after(
  639. self._user_signature_stream_cache.entity_has_changed,
  640. from_user_id,
  641. stream_id,
  642. )
  643. self.db_pool.simple_insert_txn(
  644. txn,
  645. "user_signature_stream",
  646. values={
  647. "stream_id": stream_id,
  648. "from_user_id": from_user_id,
  649. "user_ids": json_encoder.encode(user_ids),
  650. },
  651. )
  652. @trace
  653. @cancellable
  654. async def get_user_devices_from_cache(
  655. self, query_list: List[Tuple[str, Optional[str]]]
  656. ) -> Tuple[Set[str], Dict[str, Dict[str, JsonDict]]]:
  657. """Get the devices (and keys if any) for remote users from the cache.
  658. Args:
  659. query_list: List of (user_id, device_ids), if device_ids is
  660. falsey then return all device ids for that user.
  661. Returns:
  662. A tuple of (user_ids_not_in_cache, results_map), where
  663. user_ids_not_in_cache is a set of user_ids and results_map is a
  664. mapping of user_id -> device_id -> device_info.
  665. """
  666. user_ids = {user_id for user_id, _ in query_list}
  667. user_map = await self.get_device_list_last_stream_id_for_remotes(list(user_ids))
  668. # We go and check if any of the users need to have their device lists
  669. # resynced. If they do then we remove them from the cached list.
  670. users_needing_resync = await self.get_user_ids_requiring_device_list_resync(
  671. user_ids
  672. )
  673. user_ids_in_cache = {
  674. user_id for user_id, stream_id in user_map.items() if stream_id
  675. } - users_needing_resync
  676. user_ids_not_in_cache = user_ids - user_ids_in_cache
  677. results: Dict[str, Dict[str, JsonDict]] = {}
  678. for user_id, device_id in query_list:
  679. if user_id not in user_ids_in_cache:
  680. continue
  681. if device_id:
  682. device = await self._get_cached_user_device(user_id, device_id)
  683. results.setdefault(user_id, {})[device_id] = device
  684. else:
  685. results[user_id] = await self.get_cached_devices_for_user(user_id)
  686. set_tag("in_cache", str(results))
  687. set_tag("not_in_cache", str(user_ids_not_in_cache))
  688. return user_ids_not_in_cache, results
  689. @cached(num_args=2, tree=True)
  690. async def _get_cached_user_device(self, user_id: str, device_id: str) -> JsonDict:
  691. content = await self.db_pool.simple_select_one_onecol(
  692. table="device_lists_remote_cache",
  693. keyvalues={"user_id": user_id, "device_id": device_id},
  694. retcol="content",
  695. desc="_get_cached_user_device",
  696. )
  697. return db_to_json(content)
  698. @cached()
  699. async def get_cached_devices_for_user(self, user_id: str) -> Dict[str, JsonDict]:
  700. devices = await self.db_pool.simple_select_list(
  701. table="device_lists_remote_cache",
  702. keyvalues={"user_id": user_id},
  703. retcols=("device_id", "content"),
  704. desc="get_cached_devices_for_user",
  705. )
  706. return {
  707. device["device_id"]: db_to_json(device["content"]) for device in devices
  708. }
  709. def get_cached_device_list_changes(
  710. self,
  711. from_key: int,
  712. ) -> AllEntitiesChangedResult:
  713. """Get set of users whose devices have changed since `from_key`, or None
  714. if that information is not in our cache.
  715. """
  716. return self._device_list_stream_cache.get_all_entities_changed(from_key)
  717. @cancellable
  718. async def get_all_devices_changed(
  719. self,
  720. from_key: int,
  721. to_key: int,
  722. ) -> Set[str]:
  723. """Get all users whose devices have changed in the given range.
  724. Args:
  725. from_key: The minimum device lists stream token to query device list
  726. changes for, exclusive.
  727. to_key: The maximum device lists stream token to query device list
  728. changes for, inclusive.
  729. Returns:
  730. The set of user_ids whose devices have changed since `from_key`
  731. (exclusive) until `to_key` (inclusive).
  732. """
  733. result = self._device_list_stream_cache.get_all_entities_changed(from_key)
  734. if result.hit:
  735. # We know which users might have changed devices.
  736. if not result.entities:
  737. # If no users then we can return early.
  738. return set()
  739. # Otherwise we need to filter down the list
  740. return await self.get_users_whose_devices_changed(
  741. from_key, result.entities, to_key
  742. )
  743. # If the cache didn't tell us anything, we just need to query the full
  744. # range.
  745. sql = """
  746. SELECT DISTINCT user_id FROM device_lists_stream
  747. WHERE ? < stream_id AND stream_id <= ?
  748. """
  749. rows = await self.db_pool.execute(
  750. "get_all_devices_changed",
  751. None,
  752. sql,
  753. from_key,
  754. to_key,
  755. )
  756. return {u for u, in rows}
  757. @cancellable
  758. async def get_users_whose_devices_changed(
  759. self,
  760. from_key: int,
  761. user_ids: Collection[str],
  762. to_key: Optional[int] = None,
  763. ) -> Set[str]:
  764. """Get set of users whose devices have changed since `from_key` that
  765. are in the given list of user_ids.
  766. Args:
  767. from_key: The minimum device lists stream token to query device list changes for,
  768. exclusive.
  769. user_ids: If provided, only check if these users have changed their device lists.
  770. Otherwise changes from all users are returned.
  771. to_key: The maximum device lists stream token to query device list changes for,
  772. inclusive.
  773. Returns:
  774. The set of user_ids whose devices have changed since `from_key` (exclusive)
  775. until `to_key` (inclusive).
  776. """
  777. # Get set of users who *may* have changed. Users not in the returned
  778. # list have definitely not changed.
  779. user_ids_to_check = self._device_list_stream_cache.get_entities_changed(
  780. user_ids, from_key
  781. )
  782. # If an empty set was returned, there's nothing to do.
  783. if not user_ids_to_check:
  784. return set()
  785. if to_key is None:
  786. to_key = self._device_list_id_gen.get_current_token()
  787. def _get_users_whose_devices_changed_txn(txn: LoggingTransaction) -> Set[str]:
  788. sql = """
  789. SELECT DISTINCT user_id FROM device_lists_stream
  790. WHERE ? < stream_id AND stream_id <= ? AND %s
  791. """
  792. changes: Set[str] = set()
  793. # Query device changes with a batch of users at a time
  794. for chunk in batch_iter(user_ids_to_check, 100):
  795. clause, args = make_in_list_sql_clause(
  796. txn.database_engine, "user_id", chunk
  797. )
  798. txn.execute(sql % (clause,), [from_key, to_key] + args)
  799. changes.update(user_id for user_id, in txn)
  800. return changes
  801. return await self.db_pool.runInteraction(
  802. "get_users_whose_devices_changed", _get_users_whose_devices_changed_txn
  803. )
  804. async def get_users_whose_signatures_changed(
  805. self, user_id: str, from_key: int
  806. ) -> Set[str]:
  807. """Get the users who have new cross-signing signatures made by `user_id` since
  808. `from_key`.
  809. Args:
  810. user_id: the user who made the signatures
  811. from_key: The device lists stream token
  812. Returns:
  813. A set of user IDs with updated signatures.
  814. """
  815. if self._user_signature_stream_cache.has_entity_changed(user_id, from_key):
  816. sql = """
  817. SELECT DISTINCT user_ids FROM user_signature_stream
  818. WHERE from_user_id = ? AND stream_id > ?
  819. """
  820. rows = await self.db_pool.execute(
  821. "get_users_whose_signatures_changed", None, sql, user_id, from_key
  822. )
  823. return {user for row in rows for user in db_to_json(row[0])}
  824. else:
  825. return set()
  826. async def get_all_device_list_changes_for_remotes(
  827. self, instance_name: str, last_id: int, current_id: int, limit: int
  828. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  829. """Get updates for device lists replication stream.
  830. Args:
  831. instance_name: The writer we want to fetch updates from. Unused
  832. here since there is only ever one writer.
  833. last_id: The token to fetch updates from. Exclusive.
  834. current_id: The token to fetch updates up to. Inclusive.
  835. limit: The requested limit for the number of rows to return. The
  836. function may return more or fewer rows.
  837. Returns:
  838. A tuple consisting of: the updates, a token to use to fetch
  839. subsequent updates, and whether we returned fewer rows than exists
  840. between the requested tokens due to the limit.
  841. The token returned can be used in a subsequent call to this
  842. function to get further updates.
  843. The updates are a list of 2-tuples of stream ID and the row data
  844. """
  845. if last_id == current_id:
  846. return [], current_id, False
  847. def _get_all_device_list_changes_for_remotes(
  848. txn: Cursor,
  849. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  850. # This query Does The Right Thing where it'll correctly apply the
  851. # bounds to the inner queries.
  852. sql = """
  853. SELECT stream_id, entity FROM (
  854. SELECT stream_id, user_id AS entity FROM device_lists_stream
  855. UNION ALL
  856. SELECT stream_id, destination AS entity FROM device_lists_outbound_pokes
  857. ) AS e
  858. WHERE ? < stream_id AND stream_id <= ?
  859. ORDER BY stream_id ASC
  860. LIMIT ?
  861. """
  862. txn.execute(sql, (last_id, current_id, limit))
  863. updates = [(row[0], row[1:]) for row in txn]
  864. limited = False
  865. upto_token = current_id
  866. if len(updates) >= limit:
  867. upto_token = updates[-1][0]
  868. limited = True
  869. return updates, upto_token, limited
  870. return await self.db_pool.runInteraction(
  871. "get_all_device_list_changes_for_remotes",
  872. _get_all_device_list_changes_for_remotes,
  873. )
  874. @cached(max_entries=10000)
  875. async def get_device_list_last_stream_id_for_remote(
  876. self, user_id: str
  877. ) -> Optional[str]:
  878. """Get the last stream_id we got for a user. May be None if we haven't
  879. got any information for them.
  880. """
  881. return await self.db_pool.simple_select_one_onecol(
  882. table="device_lists_remote_extremeties",
  883. keyvalues={"user_id": user_id},
  884. retcol="stream_id",
  885. desc="get_device_list_last_stream_id_for_remote",
  886. allow_none=True,
  887. )
  888. @cachedList(
  889. cached_method_name="get_device_list_last_stream_id_for_remote",
  890. list_name="user_ids",
  891. )
  892. async def get_device_list_last_stream_id_for_remotes(
  893. self, user_ids: Iterable[str]
  894. ) -> Dict[str, Optional[str]]:
  895. rows = await self.db_pool.simple_select_many_batch(
  896. table="device_lists_remote_extremeties",
  897. column="user_id",
  898. iterable=user_ids,
  899. retcols=("user_id", "stream_id"),
  900. desc="get_device_list_last_stream_id_for_remotes",
  901. )
  902. results: Dict[str, Optional[str]] = {user_id: None for user_id in user_ids}
  903. results.update({row["user_id"]: row["stream_id"] for row in rows})
  904. return results
  905. async def get_user_ids_requiring_device_list_resync(
  906. self,
  907. user_ids: Optional[Collection[str]] = None,
  908. ) -> Set[str]:
  909. """Given a list of remote users return the list of users that we
  910. should resync the device lists for. If None is given instead of a list,
  911. return every user that we should resync the device lists for.
  912. Returns:
  913. The IDs of users whose device lists need resync.
  914. """
  915. if user_ids:
  916. rows = await self.db_pool.simple_select_many_batch(
  917. table="device_lists_remote_resync",
  918. column="user_id",
  919. iterable=user_ids,
  920. retcols=("user_id",),
  921. desc="get_user_ids_requiring_device_list_resync_with_iterable",
  922. )
  923. else:
  924. rows = await self.db_pool.simple_select_list(
  925. table="device_lists_remote_resync",
  926. keyvalues=None,
  927. retcols=("user_id",),
  928. desc="get_user_ids_requiring_device_list_resync",
  929. )
  930. return {row["user_id"] for row in rows}
  931. async def mark_remote_users_device_caches_as_stale(
  932. self, user_ids: StrCollection
  933. ) -> None:
  934. """Records that the server has reason to believe the cache of the devices
  935. for the remote users is out of date.
  936. """
  937. def _mark_remote_users_device_caches_as_stale_txn(
  938. txn: LoggingTransaction,
  939. ) -> None:
  940. # TODO add insertion_values support to simple_upsert_many and use
  941. # that!
  942. for user_id in user_ids:
  943. self.db_pool.simple_upsert_txn(
  944. txn,
  945. table="device_lists_remote_resync",
  946. keyvalues={"user_id": user_id},
  947. values={},
  948. insertion_values={"added_ts": self._clock.time_msec()},
  949. )
  950. await self.db_pool.runInteraction(
  951. "mark_remote_users_device_caches_as_stale",
  952. _mark_remote_users_device_caches_as_stale_txn,
  953. )
  954. async def mark_remote_user_device_cache_as_valid(self, user_id: str) -> None:
  955. # Remove the database entry that says we need to resync devices, after a resync
  956. await self.db_pool.simple_delete(
  957. table="device_lists_remote_resync",
  958. keyvalues={"user_id": user_id},
  959. desc="mark_remote_user_device_cache_as_valid",
  960. )
  961. async def handle_potentially_left_users(self, user_ids: Set[str]) -> None:
  962. """Given a set of remote users check if the server still shares a room with
  963. them. If not then mark those users' device cache as stale.
  964. """
  965. if not user_ids:
  966. return
  967. await self.db_pool.runInteraction(
  968. "_handle_potentially_left_users",
  969. self.handle_potentially_left_users_txn,
  970. user_ids,
  971. )
  972. def handle_potentially_left_users_txn(
  973. self,
  974. txn: LoggingTransaction,
  975. user_ids: Set[str],
  976. ) -> None:
  977. """Given a set of remote users check if the server still shares a room with
  978. them. If not then mark those users' device cache as stale.
  979. """
  980. if not user_ids:
  981. return
  982. joined_users = self.get_users_server_still_shares_room_with_txn(txn, user_ids)
  983. left_users = user_ids - joined_users
  984. for user_id in left_users:
  985. self.mark_remote_user_device_list_as_unsubscribed_txn(txn, user_id)
  986. async def mark_remote_user_device_list_as_unsubscribed(self, user_id: str) -> None:
  987. """Mark that we no longer track device lists for remote user."""
  988. await self.db_pool.runInteraction(
  989. "mark_remote_user_device_list_as_unsubscribed",
  990. self.mark_remote_user_device_list_as_unsubscribed_txn,
  991. user_id,
  992. )
  993. def mark_remote_user_device_list_as_unsubscribed_txn(
  994. self,
  995. txn: LoggingTransaction,
  996. user_id: str,
  997. ) -> None:
  998. self.db_pool.simple_delete_txn(
  999. txn,
  1000. table="device_lists_remote_extremeties",
  1001. keyvalues={"user_id": user_id},
  1002. )
  1003. self._invalidate_cache_and_stream(
  1004. txn, self.get_device_list_last_stream_id_for_remote, (user_id,)
  1005. )
  1006. async def get_dehydrated_device(
  1007. self, user_id: str
  1008. ) -> Optional[Tuple[str, JsonDict]]:
  1009. """Retrieve the information for a dehydrated device.
  1010. Args:
  1011. user_id: the user whose dehydrated device we are looking for
  1012. Returns:
  1013. a tuple whose first item is the device ID, and the second item is
  1014. the dehydrated device information
  1015. """
  1016. # FIXME: make sure device ID still exists in devices table
  1017. row = await self.db_pool.simple_select_one(
  1018. table="dehydrated_devices",
  1019. keyvalues={"user_id": user_id},
  1020. retcols=["device_id", "device_data"],
  1021. allow_none=True,
  1022. )
  1023. return (
  1024. (row["device_id"], json_decoder.decode(row["device_data"])) if row else None
  1025. )
  1026. def _store_dehydrated_device_txn(
  1027. self, txn: LoggingTransaction, user_id: str, device_id: str, device_data: str
  1028. ) -> Optional[str]:
  1029. old_device_id = self.db_pool.simple_select_one_onecol_txn(
  1030. txn,
  1031. table="dehydrated_devices",
  1032. keyvalues={"user_id": user_id},
  1033. retcol="device_id",
  1034. allow_none=True,
  1035. )
  1036. self.db_pool.simple_upsert_txn(
  1037. txn,
  1038. table="dehydrated_devices",
  1039. keyvalues={"user_id": user_id},
  1040. values={"device_id": device_id, "device_data": device_data},
  1041. )
  1042. return old_device_id
  1043. async def store_dehydrated_device(
  1044. self, user_id: str, device_id: str, device_data: JsonDict
  1045. ) -> Optional[str]:
  1046. """Store a dehydrated device for a user.
  1047. Args:
  1048. user_id: the user that we are storing the device for
  1049. device_id: the ID of the dehydrated device
  1050. device_data: the dehydrated device information
  1051. Returns:
  1052. device id of the user's previous dehydrated device, if any
  1053. """
  1054. return await self.db_pool.runInteraction(
  1055. "store_dehydrated_device_txn",
  1056. self._store_dehydrated_device_txn,
  1057. user_id,
  1058. device_id,
  1059. json_encoder.encode(device_data),
  1060. )
  1061. async def remove_dehydrated_device(self, user_id: str, device_id: str) -> bool:
  1062. """Remove a dehydrated device.
  1063. Args:
  1064. user_id: the user that the dehydrated device belongs to
  1065. device_id: the ID of the dehydrated device
  1066. """
  1067. count = await self.db_pool.simple_delete(
  1068. "dehydrated_devices",
  1069. {"user_id": user_id, "device_id": device_id},
  1070. desc="remove_dehydrated_device",
  1071. )
  1072. return count >= 1
  1073. @wrap_as_background_process("prune_old_outbound_device_pokes")
  1074. async def _prune_old_outbound_device_pokes(
  1075. self, prune_age: int = 24 * 60 * 60 * 1000
  1076. ) -> None:
  1077. """Delete old entries out of the device_lists_outbound_pokes to ensure
  1078. that we don't fill up due to dead servers.
  1079. Normally, we try to send device updates as a delta since a previous known point:
  1080. this is done by setting the prev_id in the m.device_list_update EDU. However,
  1081. for that to work, we have to have a complete record of each change to
  1082. each device, which can add up to quite a lot of data.
  1083. An alternative mechanism is that, if the remote server sees that it has missed
  1084. an entry in the stream_id sequence for a given user, it will request a full
  1085. list of that user's devices. Hence, we can reduce the amount of data we have to
  1086. store (and transmit in some future transaction), by clearing almost everything
  1087. for a given destination out of the database, and having the remote server
  1088. resync.
  1089. All we need to do is make sure we keep at least one row for each
  1090. (user, destination) pair, to remind us to send a m.device_list_update EDU for
  1091. that user when the destination comes back. It doesn't matter which device
  1092. we keep.
  1093. """
  1094. yesterday = self._clock.time_msec() - prune_age
  1095. def _prune_txn(txn: LoggingTransaction) -> None:
  1096. # look for (user, destination) pairs which have an update older than
  1097. # the cutoff.
  1098. #
  1099. # For each pair, we also need to know the most recent stream_id, and
  1100. # an arbitrary device_id at that stream_id.
  1101. select_sql = """
  1102. SELECT
  1103. dlop1.destination,
  1104. dlop1.user_id,
  1105. MAX(dlop1.stream_id) AS stream_id,
  1106. (SELECT MIN(dlop2.device_id) AS device_id FROM
  1107. device_lists_outbound_pokes dlop2
  1108. WHERE dlop2.destination = dlop1.destination AND
  1109. dlop2.user_id=dlop1.user_id AND
  1110. dlop2.stream_id=MAX(dlop1.stream_id)
  1111. )
  1112. FROM device_lists_outbound_pokes dlop1
  1113. GROUP BY destination, user_id
  1114. HAVING min(ts) < ? AND count(*) > 1
  1115. """
  1116. txn.execute(select_sql, (yesterday,))
  1117. rows = txn.fetchall()
  1118. if not rows:
  1119. return
  1120. logger.info(
  1121. "Pruning old outbound device list updates for %i users/destinations: %s",
  1122. len(rows),
  1123. shortstr((row[0], row[1]) for row in rows),
  1124. )
  1125. # we want to keep the update with the highest stream_id for each user.
  1126. #
  1127. # there might be more than one update (with different device_ids) with the
  1128. # same stream_id, so we also delete all but one rows with the max stream id.
  1129. delete_sql = """
  1130. DELETE FROM device_lists_outbound_pokes
  1131. WHERE destination = ? AND user_id = ? AND (
  1132. stream_id < ? OR
  1133. (stream_id = ? AND device_id != ?)
  1134. )
  1135. """
  1136. count = 0
  1137. for (destination, user_id, stream_id, device_id) in rows:
  1138. txn.execute(
  1139. delete_sql, (destination, user_id, stream_id, stream_id, device_id)
  1140. )
  1141. count += txn.rowcount
  1142. # Since we've deleted unsent deltas, we need to remove the entry
  1143. # of last successful sent so that the prev_ids are correctly set.
  1144. sql = """
  1145. DELETE FROM device_lists_outbound_last_success
  1146. WHERE destination = ? AND user_id = ?
  1147. """
  1148. txn.execute_batch(sql, ((row[0], row[1]) for row in rows))
  1149. logger.info("Pruned %d device list outbound pokes", count)
  1150. await self.db_pool.runInteraction(
  1151. "_prune_old_outbound_device_pokes",
  1152. _prune_txn,
  1153. )
  1154. async def get_local_devices_not_accessed_since(
  1155. self, since_ms: int
  1156. ) -> Dict[str, List[str]]:
  1157. """Retrieves local devices that haven't been accessed since a given date.
  1158. Args:
  1159. since_ms: the timestamp to select on, every device with a last access date
  1160. from before that time is returned.
  1161. Returns:
  1162. A dictionary with an entry for each user with at least one device matching
  1163. the request, which value is a list of the device ID(s) for the corresponding
  1164. device(s).
  1165. """
  1166. def get_devices_not_accessed_since_txn(
  1167. txn: LoggingTransaction,
  1168. ) -> List[Dict[str, str]]:
  1169. sql = """
  1170. SELECT user_id, device_id
  1171. FROM devices WHERE last_seen < ? AND hidden = FALSE
  1172. """
  1173. txn.execute(sql, (since_ms,))
  1174. return self.db_pool.cursor_to_dict(txn)
  1175. rows = await self.db_pool.runInteraction(
  1176. "get_devices_not_accessed_since",
  1177. get_devices_not_accessed_since_txn,
  1178. )
  1179. devices: Dict[str, List[str]] = {}
  1180. for row in rows:
  1181. # Remote devices are never stale from our point of view.
  1182. if self.hs.is_mine_id(row["user_id"]):
  1183. user_devices = devices.setdefault(row["user_id"], [])
  1184. user_devices.append(row["device_id"])
  1185. return devices
  1186. @cached()
  1187. async def _get_min_device_lists_changes_in_room(self) -> int:
  1188. """Returns the minimum stream ID that we have entries for
  1189. `device_lists_changes_in_room`
  1190. """
  1191. return await self.db_pool.simple_select_one_onecol(
  1192. table="device_lists_changes_in_room",
  1193. keyvalues={},
  1194. retcol="COALESCE(MIN(stream_id), 0)",
  1195. desc="get_min_device_lists_changes_in_room",
  1196. )
  1197. @cancellable
  1198. async def get_device_list_changes_in_rooms(
  1199. self, room_ids: Collection[str], from_id: int
  1200. ) -> Optional[Set[str]]:
  1201. """Return the set of users whose devices have changed in the given rooms
  1202. since the given stream ID.
  1203. Returns None if the given stream ID is too old.
  1204. """
  1205. if not room_ids:
  1206. return set()
  1207. min_stream_id = await self._get_min_device_lists_changes_in_room()
  1208. if min_stream_id > from_id:
  1209. return None
  1210. sql = """
  1211. SELECT DISTINCT user_id FROM device_lists_changes_in_room
  1212. WHERE {clause} AND stream_id >= ?
  1213. """
  1214. def _get_device_list_changes_in_rooms_txn(
  1215. txn: LoggingTransaction,
  1216. clause: str,
  1217. args: List[Any],
  1218. ) -> Set[str]:
  1219. txn.execute(sql.format(clause=clause), args)
  1220. return {user_id for user_id, in txn}
  1221. changes = set()
  1222. for chunk in batch_iter(room_ids, 1000):
  1223. clause, args = make_in_list_sql_clause(
  1224. self.database_engine, "room_id", chunk
  1225. )
  1226. args.append(from_id)
  1227. changes |= await self.db_pool.runInteraction(
  1228. "get_device_list_changes_in_rooms",
  1229. _get_device_list_changes_in_rooms_txn,
  1230. clause,
  1231. args,
  1232. )
  1233. return changes
  1234. async def get_device_list_changes_in_room(
  1235. self, room_id: str, min_stream_id: int
  1236. ) -> Collection[Tuple[str, str]]:
  1237. """Get all device list changes that happened in the room since the given
  1238. stream ID.
  1239. Returns:
  1240. Collection of user ID/device ID tuples of all devices that have
  1241. changed
  1242. """
  1243. sql = """
  1244. SELECT DISTINCT user_id, device_id FROM device_lists_changes_in_room
  1245. WHERE room_id = ? AND stream_id > ?
  1246. """
  1247. def get_device_list_changes_in_room_txn(
  1248. txn: LoggingTransaction,
  1249. ) -> Collection[Tuple[str, str]]:
  1250. txn.execute(sql, (room_id, min_stream_id))
  1251. return cast(Collection[Tuple[str, str]], txn.fetchall())
  1252. return await self.db_pool.runInteraction(
  1253. "get_device_list_changes_in_room",
  1254. get_device_list_changes_in_room_txn,
  1255. )
  1256. class DeviceBackgroundUpdateStore(SQLBaseStore):
  1257. def __init__(
  1258. self,
  1259. database: DatabasePool,
  1260. db_conn: LoggingDatabaseConnection,
  1261. hs: "HomeServer",
  1262. ):
  1263. super().__init__(database, db_conn, hs)
  1264. self.db_pool.updates.register_background_index_update(
  1265. "device_lists_stream_idx",
  1266. index_name="device_lists_stream_user_id",
  1267. table="device_lists_stream",
  1268. columns=["user_id", "device_id"],
  1269. )
  1270. # create a unique index on device_lists_remote_cache
  1271. self.db_pool.updates.register_background_index_update(
  1272. "device_lists_remote_cache_unique_idx",
  1273. index_name="device_lists_remote_cache_unique_id",
  1274. table="device_lists_remote_cache",
  1275. columns=["user_id", "device_id"],
  1276. unique=True,
  1277. )
  1278. # And one on device_lists_remote_extremeties
  1279. self.db_pool.updates.register_background_index_update(
  1280. "device_lists_remote_extremeties_unique_idx",
  1281. index_name="device_lists_remote_extremeties_unique_idx",
  1282. table="device_lists_remote_extremeties",
  1283. columns=["user_id"],
  1284. unique=True,
  1285. )
  1286. # once they complete, we can remove the old non-unique indexes.
  1287. self.db_pool.updates.register_background_update_handler(
  1288. DROP_DEVICE_LIST_STREAMS_NON_UNIQUE_INDEXES,
  1289. self._drop_device_list_streams_non_unique_indexes,
  1290. )
  1291. # clear out duplicate device list outbound pokes
  1292. self.db_pool.updates.register_background_update_handler(
  1293. BG_UPDATE_REMOVE_DUP_OUTBOUND_POKES,
  1294. self._remove_duplicate_outbound_pokes,
  1295. )
  1296. self.db_pool.updates.register_background_index_update(
  1297. "device_lists_changes_in_room_by_room_index",
  1298. index_name="device_lists_changes_in_room_by_room_idx",
  1299. table="device_lists_changes_in_room",
  1300. columns=["room_id", "stream_id"],
  1301. )
  1302. async def _drop_device_list_streams_non_unique_indexes(
  1303. self, progress: JsonDict, batch_size: int
  1304. ) -> int:
  1305. def f(conn: LoggingDatabaseConnection) -> None:
  1306. txn = conn.cursor()
  1307. txn.execute("DROP INDEX IF EXISTS device_lists_remote_cache_id")
  1308. txn.execute("DROP INDEX IF EXISTS device_lists_remote_extremeties_id")
  1309. txn.close()
  1310. await self.db_pool.runWithConnection(f)
  1311. await self.db_pool.updates._end_background_update(
  1312. DROP_DEVICE_LIST_STREAMS_NON_UNIQUE_INDEXES
  1313. )
  1314. return 1
  1315. async def _remove_duplicate_outbound_pokes(
  1316. self, progress: JsonDict, batch_size: int
  1317. ) -> int:
  1318. # for some reason, we have accumulated duplicate entries in
  1319. # device_lists_outbound_pokes, which makes prune_outbound_device_list_pokes less
  1320. # efficient.
  1321. #
  1322. # For each duplicate, we delete all the existing rows and put one back.
  1323. KEY_COLS = ["stream_id", "destination", "user_id", "device_id"]
  1324. last_row = progress.get(
  1325. "last_row",
  1326. {"stream_id": 0, "destination": "", "user_id": "", "device_id": ""},
  1327. )
  1328. def _txn(txn: LoggingTransaction) -> int:
  1329. clause, args = make_tuple_comparison_clause(
  1330. [(x, last_row[x]) for x in KEY_COLS]
  1331. )
  1332. sql = """
  1333. SELECT stream_id, destination, user_id, device_id, MAX(ts) AS ts
  1334. FROM device_lists_outbound_pokes
  1335. WHERE %s
  1336. GROUP BY %s
  1337. HAVING count(*) > 1
  1338. ORDER BY %s
  1339. LIMIT ?
  1340. """ % (
  1341. clause, # WHERE
  1342. ",".join(KEY_COLS), # GROUP BY
  1343. ",".join(KEY_COLS), # ORDER BY
  1344. )
  1345. txn.execute(sql, args + [batch_size])
  1346. rows = self.db_pool.cursor_to_dict(txn)
  1347. row = None
  1348. for row in rows:
  1349. self.db_pool.simple_delete_txn(
  1350. txn,
  1351. "device_lists_outbound_pokes",
  1352. {x: row[x] for x in KEY_COLS},
  1353. )
  1354. row["sent"] = False
  1355. self.db_pool.simple_insert_txn(
  1356. txn,
  1357. "device_lists_outbound_pokes",
  1358. row,
  1359. )
  1360. if row:
  1361. self.db_pool.updates._background_update_progress_txn(
  1362. txn,
  1363. BG_UPDATE_REMOVE_DUP_OUTBOUND_POKES,
  1364. {"last_row": row},
  1365. )
  1366. return len(rows)
  1367. rows = await self.db_pool.runInteraction(
  1368. BG_UPDATE_REMOVE_DUP_OUTBOUND_POKES, _txn
  1369. )
  1370. if not rows:
  1371. await self.db_pool.updates._end_background_update(
  1372. BG_UPDATE_REMOVE_DUP_OUTBOUND_POKES
  1373. )
  1374. return rows
  1375. class DeviceStore(DeviceWorkerStore, DeviceBackgroundUpdateStore):
  1376. # Because we have write access, this will be a StreamIdGenerator
  1377. # (see DeviceWorkerStore.__init__)
  1378. _device_list_id_gen: AbstractStreamIdGenerator
  1379. def __init__(
  1380. self,
  1381. database: DatabasePool,
  1382. db_conn: LoggingDatabaseConnection,
  1383. hs: "HomeServer",
  1384. ):
  1385. super().__init__(database, db_conn, hs)
  1386. # Map of (user_id, device_id) -> bool. If there is an entry that implies
  1387. # the device exists.
  1388. self.device_id_exists_cache: LruCache[
  1389. Tuple[str, str], Literal[True]
  1390. ] = LruCache(cache_name="device_id_exists", max_size=10000)
  1391. async def store_device(
  1392. self,
  1393. user_id: str,
  1394. device_id: str,
  1395. initial_device_display_name: Optional[str],
  1396. auth_provider_id: Optional[str] = None,
  1397. auth_provider_session_id: Optional[str] = None,
  1398. ) -> bool:
  1399. """Ensure the given device is known; add it to the store if not
  1400. Args:
  1401. user_id: id of user associated with the device
  1402. device_id: id of device
  1403. initial_device_display_name: initial displayname of the device.
  1404. Ignored if device exists.
  1405. auth_provider_id: The SSO IdP the user used, if any.
  1406. auth_provider_session_id: The session ID (sid) got from a OIDC login.
  1407. Returns:
  1408. Whether the device was inserted or an existing device existed with that ID.
  1409. Raises:
  1410. StoreError: if the device is already in use
  1411. """
  1412. key = (user_id, device_id)
  1413. if self.device_id_exists_cache.get(key, None):
  1414. return False
  1415. try:
  1416. inserted = await self.db_pool.simple_upsert(
  1417. "devices",
  1418. keyvalues={
  1419. "user_id": user_id,
  1420. "device_id": device_id,
  1421. },
  1422. values={},
  1423. insertion_values={
  1424. "display_name": initial_device_display_name,
  1425. "hidden": False,
  1426. },
  1427. desc="store_device",
  1428. )
  1429. if not inserted:
  1430. # if the device already exists, check if it's a real device, or
  1431. # if the device ID is reserved by something else
  1432. hidden = await self.db_pool.simple_select_one_onecol(
  1433. "devices",
  1434. keyvalues={"user_id": user_id, "device_id": device_id},
  1435. retcol="hidden",
  1436. )
  1437. if hidden:
  1438. raise StoreError(400, "The device ID is in use", Codes.FORBIDDEN)
  1439. if auth_provider_id and auth_provider_session_id:
  1440. await self.db_pool.simple_insert(
  1441. "device_auth_providers",
  1442. values={
  1443. "user_id": user_id,
  1444. "device_id": device_id,
  1445. "auth_provider_id": auth_provider_id,
  1446. "auth_provider_session_id": auth_provider_session_id,
  1447. },
  1448. desc="store_device_auth_provider",
  1449. )
  1450. self.device_id_exists_cache.set(key, True)
  1451. return inserted
  1452. except StoreError:
  1453. raise
  1454. except Exception as e:
  1455. logger.error(
  1456. "store_device with device_id=%s(%r) user_id=%s(%r)"
  1457. " display_name=%s(%r) failed: %s",
  1458. type(device_id).__name__,
  1459. device_id,
  1460. type(user_id).__name__,
  1461. user_id,
  1462. type(initial_device_display_name).__name__,
  1463. initial_device_display_name,
  1464. e,
  1465. )
  1466. raise StoreError(500, "Problem storing device.")
  1467. async def delete_devices(self, user_id: str, device_ids: List[str]) -> None:
  1468. """Deletes several devices.
  1469. Args:
  1470. user_id: The ID of the user which owns the devices
  1471. device_ids: The IDs of the devices to delete
  1472. """
  1473. def _delete_devices_txn(txn: LoggingTransaction) -> None:
  1474. self.db_pool.simple_delete_many_txn(
  1475. txn,
  1476. table="devices",
  1477. column="device_id",
  1478. values=device_ids,
  1479. keyvalues={"user_id": user_id, "hidden": False},
  1480. )
  1481. self.db_pool.simple_delete_many_txn(
  1482. txn,
  1483. table="device_inbox",
  1484. column="device_id",
  1485. values=device_ids,
  1486. keyvalues={"user_id": user_id},
  1487. )
  1488. self.db_pool.simple_delete_many_txn(
  1489. txn,
  1490. table="device_auth_providers",
  1491. column="device_id",
  1492. values=device_ids,
  1493. keyvalues={"user_id": user_id},
  1494. )
  1495. await self.db_pool.runInteraction("delete_devices", _delete_devices_txn)
  1496. for device_id in device_ids:
  1497. self.device_id_exists_cache.invalidate((user_id, device_id))
  1498. async def update_device(
  1499. self, user_id: str, device_id: str, new_display_name: Optional[str] = None
  1500. ) -> None:
  1501. """Update a device. Only updates the device if it is not marked as
  1502. hidden.
  1503. Args:
  1504. user_id: The ID of the user which owns the device
  1505. device_id: The ID of the device to update
  1506. new_display_name: new displayname for device; None to leave unchanged
  1507. Raises:
  1508. StoreError: if the device is not found
  1509. """
  1510. updates = {}
  1511. if new_display_name is not None:
  1512. updates["display_name"] = new_display_name
  1513. if not updates:
  1514. return None
  1515. await self.db_pool.simple_update_one(
  1516. table="devices",
  1517. keyvalues={"user_id": user_id, "device_id": device_id, "hidden": False},
  1518. updatevalues=updates,
  1519. desc="update_device",
  1520. )
  1521. async def update_remote_device_list_cache_entry(
  1522. self, user_id: str, device_id: str, content: JsonDict, stream_id: str
  1523. ) -> None:
  1524. """Updates a single device in the cache of a remote user's devicelist.
  1525. Note: assumes that we are the only thread that can be updating this user's
  1526. device list.
  1527. Args:
  1528. user_id: User to update device list for
  1529. device_id: ID of decivice being updated
  1530. content: new data on this device
  1531. stream_id: the version of the device list
  1532. """
  1533. await self.db_pool.runInteraction(
  1534. "update_remote_device_list_cache_entry",
  1535. self._update_remote_device_list_cache_entry_txn,
  1536. user_id,
  1537. device_id,
  1538. content,
  1539. stream_id,
  1540. )
  1541. def _update_remote_device_list_cache_entry_txn(
  1542. self,
  1543. txn: LoggingTransaction,
  1544. user_id: str,
  1545. device_id: str,
  1546. content: JsonDict,
  1547. stream_id: str,
  1548. ) -> None:
  1549. """Delete, update or insert a cache entry for this (user, device) pair."""
  1550. if content.get("deleted"):
  1551. self.db_pool.simple_delete_txn(
  1552. txn,
  1553. table="device_lists_remote_cache",
  1554. keyvalues={"user_id": user_id, "device_id": device_id},
  1555. )
  1556. txn.call_after(self.device_id_exists_cache.invalidate, (user_id, device_id))
  1557. else:
  1558. self.db_pool.simple_upsert_txn(
  1559. txn,
  1560. table="device_lists_remote_cache",
  1561. keyvalues={"user_id": user_id, "device_id": device_id},
  1562. values={"content": json_encoder.encode(content)},
  1563. )
  1564. txn.call_after(self._get_cached_user_device.invalidate, (user_id, device_id))
  1565. txn.call_after(self.get_cached_devices_for_user.invalidate, (user_id,))
  1566. txn.call_after(
  1567. self.get_device_list_last_stream_id_for_remote.invalidate, (user_id,)
  1568. )
  1569. self.db_pool.simple_upsert_txn(
  1570. txn,
  1571. table="device_lists_remote_extremeties",
  1572. keyvalues={"user_id": user_id},
  1573. values={"stream_id": stream_id},
  1574. )
  1575. async def update_remote_device_list_cache(
  1576. self, user_id: str, devices: List[dict], stream_id: int
  1577. ) -> None:
  1578. """Replace the entire cache of the remote user's devices.
  1579. Note: assumes that we are the only thread that can be updating this user's
  1580. device list.
  1581. Args:
  1582. user_id: User to update device list for
  1583. devices: list of device objects supplied over federation
  1584. stream_id: the version of the device list
  1585. """
  1586. await self.db_pool.runInteraction(
  1587. "update_remote_device_list_cache",
  1588. self._update_remote_device_list_cache_txn,
  1589. user_id,
  1590. devices,
  1591. stream_id,
  1592. )
  1593. def _update_remote_device_list_cache_txn(
  1594. self, txn: LoggingTransaction, user_id: str, devices: List[dict], stream_id: int
  1595. ) -> None:
  1596. """Replace the list of cached devices for this user with the given list."""
  1597. self.db_pool.simple_delete_txn(
  1598. txn, table="device_lists_remote_cache", keyvalues={"user_id": user_id}
  1599. )
  1600. self.db_pool.simple_insert_many_txn(
  1601. txn,
  1602. table="device_lists_remote_cache",
  1603. keys=("user_id", "device_id", "content"),
  1604. values=[
  1605. (user_id, content["device_id"], json_encoder.encode(content))
  1606. for content in devices
  1607. ],
  1608. )
  1609. txn.call_after(self.get_cached_devices_for_user.invalidate, (user_id,))
  1610. txn.call_after(self._get_cached_user_device.invalidate, (user_id,))
  1611. txn.call_after(
  1612. self.get_device_list_last_stream_id_for_remote.invalidate, (user_id,)
  1613. )
  1614. self.db_pool.simple_upsert_txn(
  1615. txn,
  1616. table="device_lists_remote_extremeties",
  1617. keyvalues={"user_id": user_id},
  1618. values={"stream_id": stream_id},
  1619. )
  1620. async def add_device_change_to_streams(
  1621. self,
  1622. user_id: str,
  1623. device_ids: Collection[str],
  1624. room_ids: Collection[str],
  1625. ) -> Optional[int]:
  1626. """Persist that a user's devices have been updated, and which hosts
  1627. (if any) should be poked.
  1628. Args:
  1629. user_id: The ID of the user whose device changed.
  1630. device_ids: The IDs of any changed devices. If empty, this function will
  1631. return None.
  1632. room_ids: The rooms that the user is in
  1633. Returns:
  1634. The maximum stream ID of device list updates that were added to the database, or
  1635. None if no updates were added.
  1636. """
  1637. if not device_ids:
  1638. return None
  1639. context = get_active_span_text_map()
  1640. def add_device_changes_txn(
  1641. txn: LoggingTransaction, stream_ids: List[int]
  1642. ) -> None:
  1643. self._add_device_change_to_stream_txn(
  1644. txn,
  1645. user_id,
  1646. device_ids,
  1647. stream_ids,
  1648. )
  1649. self._add_device_outbound_room_poke_txn(
  1650. txn,
  1651. user_id,
  1652. device_ids,
  1653. room_ids,
  1654. stream_ids,
  1655. context,
  1656. )
  1657. async with self._device_list_id_gen.get_next_mult(
  1658. len(device_ids)
  1659. ) as stream_ids:
  1660. await self.db_pool.runInteraction(
  1661. "add_device_change_to_stream",
  1662. add_device_changes_txn,
  1663. stream_ids,
  1664. )
  1665. return stream_ids[-1]
  1666. def _add_device_change_to_stream_txn(
  1667. self,
  1668. txn: LoggingTransaction,
  1669. user_id: str,
  1670. device_ids: Collection[str],
  1671. stream_ids: List[int],
  1672. ) -> None:
  1673. txn.call_after(
  1674. self._device_list_stream_cache.entity_has_changed,
  1675. user_id,
  1676. stream_ids[-1],
  1677. )
  1678. min_stream_id = stream_ids[0]
  1679. # Delete older entries in the table, as we really only care about
  1680. # when the latest change happened.
  1681. txn.execute_batch(
  1682. """
  1683. DELETE FROM device_lists_stream
  1684. WHERE user_id = ? AND device_id = ? AND stream_id < ?
  1685. """,
  1686. [(user_id, device_id, min_stream_id) for device_id in device_ids],
  1687. )
  1688. self.db_pool.simple_insert_many_txn(
  1689. txn,
  1690. table="device_lists_stream",
  1691. keys=("stream_id", "user_id", "device_id"),
  1692. values=[
  1693. (stream_id, user_id, device_id)
  1694. for stream_id, device_id in zip(stream_ids, device_ids)
  1695. ],
  1696. )
  1697. def _add_device_outbound_poke_to_stream_txn(
  1698. self,
  1699. txn: LoggingTransaction,
  1700. user_id: str,
  1701. device_id: str,
  1702. hosts: Collection[str],
  1703. stream_ids: List[int],
  1704. context: Optional[Dict[str, str]],
  1705. ) -> None:
  1706. for host in hosts:
  1707. txn.call_after(
  1708. self._device_list_federation_stream_cache.entity_has_changed,
  1709. host,
  1710. stream_ids[-1],
  1711. )
  1712. now = self._clock.time_msec()
  1713. stream_id_iterator = iter(stream_ids)
  1714. encoded_context = json_encoder.encode(context)
  1715. mark_sent = not self.hs.is_mine_id(user_id)
  1716. values = [
  1717. (
  1718. destination,
  1719. next(stream_id_iterator),
  1720. user_id,
  1721. device_id,
  1722. mark_sent,
  1723. now,
  1724. encoded_context if whitelisted_homeserver(destination) else "{}",
  1725. )
  1726. for destination in hosts
  1727. ]
  1728. self.db_pool.simple_insert_many_txn(
  1729. txn,
  1730. table="device_lists_outbound_pokes",
  1731. keys=(
  1732. "destination",
  1733. "stream_id",
  1734. "user_id",
  1735. "device_id",
  1736. "sent",
  1737. "ts",
  1738. "opentracing_context",
  1739. ),
  1740. values=values,
  1741. )
  1742. # debugging for https://github.com/matrix-org/synapse/issues/14251
  1743. if issue_8631_logger.isEnabledFor(logging.DEBUG):
  1744. issue_8631_logger.debug(
  1745. "Recorded outbound pokes for %s:%s with device stream ids %s",
  1746. user_id,
  1747. device_id,
  1748. {
  1749. stream_id: destination
  1750. for (destination, stream_id, _, _, _, _, _) in values
  1751. },
  1752. )
  1753. def _add_device_outbound_room_poke_txn(
  1754. self,
  1755. txn: LoggingTransaction,
  1756. user_id: str,
  1757. device_ids: Iterable[str],
  1758. room_ids: Collection[str],
  1759. stream_ids: List[int],
  1760. context: Dict[str, str],
  1761. ) -> None:
  1762. """Record the user in the room has updated their device."""
  1763. encoded_context = json_encoder.encode(context)
  1764. # The `device_lists_changes_in_room.stream_id` column matches the
  1765. # corresponding `stream_id` of the update in the `device_lists_stream`
  1766. # table, i.e. all rows persisted for the same device update will have
  1767. # the same `stream_id` (but different room IDs).
  1768. self.db_pool.simple_insert_many_txn(
  1769. txn,
  1770. table="device_lists_changes_in_room",
  1771. keys=(
  1772. "user_id",
  1773. "device_id",
  1774. "room_id",
  1775. "stream_id",
  1776. "converted_to_destinations",
  1777. "opentracing_context",
  1778. ),
  1779. values=[
  1780. (
  1781. user_id,
  1782. device_id,
  1783. room_id,
  1784. stream_id,
  1785. # We only need to calculate outbound pokes for local users
  1786. not self.hs.is_mine_id(user_id),
  1787. encoded_context,
  1788. )
  1789. for room_id in room_ids
  1790. for device_id, stream_id in zip(device_ids, stream_ids)
  1791. ],
  1792. )
  1793. async def get_uncoverted_outbound_room_pokes(
  1794. self, start_stream_id: int, start_room_id: str, limit: int = 10
  1795. ) -> List[Tuple[str, str, str, int, Optional[Dict[str, str]]]]:
  1796. """Get device list changes by room that have not yet been handled and
  1797. written to `device_lists_outbound_pokes`.
  1798. Args:
  1799. start_stream_id: Together with `start_room_id`, indicates the position after
  1800. which to return device list changes.
  1801. start_room_id: Together with `start_stream_id`, indicates the position after
  1802. which to return device list changes.
  1803. limit: The maximum number of device list changes to return.
  1804. Returns:
  1805. A list of user ID, device ID, room ID, stream ID and optional opentracing
  1806. context, in order of ascending (stream ID, room ID).
  1807. """
  1808. sql = """
  1809. SELECT user_id, device_id, room_id, stream_id, opentracing_context
  1810. FROM device_lists_changes_in_room
  1811. WHERE
  1812. (stream_id, room_id) > (?, ?) AND
  1813. stream_id <= ? AND
  1814. NOT converted_to_destinations
  1815. ORDER BY stream_id ASC, room_id ASC
  1816. LIMIT ?
  1817. """
  1818. def get_uncoverted_outbound_room_pokes_txn(
  1819. txn: LoggingTransaction,
  1820. ) -> List[Tuple[str, str, str, int, Optional[Dict[str, str]]]]:
  1821. txn.execute(
  1822. sql,
  1823. (
  1824. start_stream_id,
  1825. start_room_id,
  1826. # Avoid returning rows if there may be uncommitted device list
  1827. # changes with smaller stream IDs.
  1828. self._device_list_id_gen.get_current_token(),
  1829. limit,
  1830. ),
  1831. )
  1832. return [
  1833. (
  1834. user_id,
  1835. device_id,
  1836. room_id,
  1837. stream_id,
  1838. db_to_json(opentracing_context),
  1839. )
  1840. for user_id, device_id, room_id, stream_id, opentracing_context in txn
  1841. ]
  1842. return await self.db_pool.runInteraction(
  1843. "get_uncoverted_outbound_room_pokes", get_uncoverted_outbound_room_pokes_txn
  1844. )
  1845. async def add_device_list_outbound_pokes(
  1846. self,
  1847. user_id: str,
  1848. device_id: str,
  1849. room_id: str,
  1850. hosts: Collection[str],
  1851. context: Optional[Dict[str, str]],
  1852. ) -> None:
  1853. """Queue the device update to be sent to the given set of hosts,
  1854. calculated from the room ID.
  1855. """
  1856. if not hosts:
  1857. return
  1858. def add_device_list_outbound_pokes_txn(
  1859. txn: LoggingTransaction, stream_ids: List[int]
  1860. ) -> None:
  1861. self._add_device_outbound_poke_to_stream_txn(
  1862. txn,
  1863. user_id=user_id,
  1864. device_id=device_id,
  1865. hosts=hosts,
  1866. stream_ids=stream_ids,
  1867. context=context,
  1868. )
  1869. async with self._device_list_id_gen.get_next_mult(len(hosts)) as stream_ids:
  1870. return await self.db_pool.runInteraction(
  1871. "add_device_list_outbound_pokes",
  1872. add_device_list_outbound_pokes_txn,
  1873. stream_ids,
  1874. )
  1875. async def add_remote_device_list_to_pending(
  1876. self, user_id: str, device_id: str
  1877. ) -> None:
  1878. """Add a device list update to the table tracking remote device list
  1879. updates during partial joins.
  1880. """
  1881. async with self._device_list_id_gen.get_next() as stream_id:
  1882. await self.db_pool.simple_upsert(
  1883. table="device_lists_remote_pending",
  1884. keyvalues={
  1885. "user_id": user_id,
  1886. "device_id": device_id,
  1887. },
  1888. values={"stream_id": stream_id},
  1889. desc="add_remote_device_list_to_pending",
  1890. )
  1891. async def get_pending_remote_device_list_updates_for_room(
  1892. self, room_id: str
  1893. ) -> Collection[Tuple[str, str]]:
  1894. """Get the set of remote device list updates from the pending table for
  1895. the room.
  1896. """
  1897. min_device_stream_id = await self.db_pool.simple_select_one_onecol(
  1898. table="partial_state_rooms",
  1899. keyvalues={
  1900. "room_id": room_id,
  1901. },
  1902. retcol="device_lists_stream_id",
  1903. desc="get_pending_remote_device_list_updates_for_room_device",
  1904. )
  1905. sql = """
  1906. SELECT user_id, device_id FROM device_lists_remote_pending AS d
  1907. INNER JOIN current_state_events AS c ON
  1908. type = 'm.room.member'
  1909. AND state_key = user_id
  1910. AND membership = 'join'
  1911. WHERE
  1912. room_id = ? AND stream_id > ?
  1913. """
  1914. def get_pending_remote_device_list_updates_for_room_txn(
  1915. txn: LoggingTransaction,
  1916. ) -> Collection[Tuple[str, str]]:
  1917. txn.execute(sql, (room_id, min_device_stream_id))
  1918. return cast(Collection[Tuple[str, str]], txn.fetchall())
  1919. return await self.db_pool.runInteraction(
  1920. "get_pending_remote_device_list_updates_for_room",
  1921. get_pending_remote_device_list_updates_for_room_txn,
  1922. )
  1923. async def get_device_change_last_converted_pos(self) -> Tuple[int, str]:
  1924. """
  1925. Get the position of the last row in `device_list_changes_in_room` that has been
  1926. converted to `device_lists_outbound_pokes`.
  1927. Rows with a strictly greater position where `converted_to_destinations` is
  1928. `FALSE` have not been converted.
  1929. """
  1930. row = await self.db_pool.simple_select_one(
  1931. table="device_lists_changes_converted_stream_position",
  1932. keyvalues={},
  1933. retcols=["stream_id", "room_id"],
  1934. desc="get_device_change_last_converted_pos",
  1935. )
  1936. return row["stream_id"], row["room_id"]
  1937. async def set_device_change_last_converted_pos(
  1938. self,
  1939. stream_id: int,
  1940. room_id: str,
  1941. ) -> None:
  1942. """
  1943. Set the position of the last row in `device_list_changes_in_room` that has been
  1944. converted to `device_lists_outbound_pokes`.
  1945. """
  1946. await self.db_pool.simple_update_one(
  1947. table="device_lists_changes_converted_stream_position",
  1948. keyvalues={},
  1949. updatevalues={"stream_id": stream_id, "room_id": room_id},
  1950. desc="set_device_change_last_converted_pos",
  1951. )