You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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