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.
 
 
 
 
 
 

778 lines
29 KiB

  1. # Copyright 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import TYPE_CHECKING, Dict, List, Mapping, Optional, Tuple, Union, cast
  16. from typing_extensions import TypedDict
  17. from synapse.metrics.background_process_metrics import wrap_as_background_process
  18. from synapse.storage._base import SQLBaseStore
  19. from synapse.storage.database import (
  20. DatabasePool,
  21. LoggingDatabaseConnection,
  22. LoggingTransaction,
  23. make_tuple_comparison_clause,
  24. )
  25. from synapse.storage.databases.main.monthly_active_users import (
  26. MonthlyActiveUsersWorkerStore,
  27. )
  28. from synapse.types import JsonDict, UserID
  29. from synapse.util.caches.lrucache import LruCache
  30. if TYPE_CHECKING:
  31. from synapse.server import HomeServer
  32. logger = logging.getLogger(__name__)
  33. # Number of msec of granularity to store the user IP 'last seen' time. Smaller
  34. # times give more inserts into the database even for readonly API hits
  35. # 120 seconds == 2 minutes
  36. LAST_SEEN_GRANULARITY = 120 * 1000
  37. class DeviceLastConnectionInfo(TypedDict):
  38. """Metadata for the last connection seen for a user and device combination"""
  39. # These types must match the columns in the `devices` table
  40. user_id: str
  41. device_id: str
  42. ip: Optional[str]
  43. user_agent: Optional[str]
  44. last_seen: Optional[int]
  45. class LastConnectionInfo(TypedDict):
  46. """Metadata for the last connection seen for an access token and IP combination"""
  47. # These types must match the columns in the `user_ips` table
  48. access_token: str
  49. ip: str
  50. user_agent: str
  51. last_seen: int
  52. class ClientIpBackgroundUpdateStore(SQLBaseStore):
  53. def __init__(
  54. self,
  55. database: DatabasePool,
  56. db_conn: LoggingDatabaseConnection,
  57. hs: "HomeServer",
  58. ):
  59. super().__init__(database, db_conn, hs)
  60. self.db_pool.updates.register_background_index_update(
  61. "user_ips_device_index",
  62. index_name="user_ips_device_id",
  63. table="user_ips",
  64. columns=["user_id", "device_id", "last_seen"],
  65. )
  66. self.db_pool.updates.register_background_index_update(
  67. "user_ips_last_seen_index",
  68. index_name="user_ips_last_seen",
  69. table="user_ips",
  70. columns=["user_id", "last_seen"],
  71. )
  72. self.db_pool.updates.register_background_index_update(
  73. "user_ips_last_seen_only_index",
  74. index_name="user_ips_last_seen_only",
  75. table="user_ips",
  76. columns=["last_seen"],
  77. )
  78. self.db_pool.updates.register_background_update_handler(
  79. "user_ips_analyze", self._analyze_user_ip
  80. )
  81. self.db_pool.updates.register_background_update_handler(
  82. "user_ips_remove_dupes", self._remove_user_ip_dupes
  83. )
  84. # Register a unique index
  85. self.db_pool.updates.register_background_index_update(
  86. "user_ips_device_unique_index",
  87. index_name="user_ips_user_token_ip_unique_index",
  88. table="user_ips",
  89. columns=["user_id", "access_token", "ip"],
  90. unique=True,
  91. )
  92. # Drop the old non-unique index
  93. self.db_pool.updates.register_background_update_handler(
  94. "user_ips_drop_nonunique_index", self._remove_user_ip_nonunique
  95. )
  96. # Update the last seen info in devices.
  97. self.db_pool.updates.register_background_update_handler(
  98. "devices_last_seen", self._devices_last_seen_update
  99. )
  100. async def _remove_user_ip_nonunique(
  101. self, progress: JsonDict, batch_size: int
  102. ) -> int:
  103. def f(conn: LoggingDatabaseConnection) -> None:
  104. txn = conn.cursor()
  105. txn.execute("DROP INDEX IF EXISTS user_ips_user_ip")
  106. txn.close()
  107. await self.db_pool.runWithConnection(f)
  108. await self.db_pool.updates._end_background_update(
  109. "user_ips_drop_nonunique_index"
  110. )
  111. return 1
  112. async def _analyze_user_ip(self, progress: JsonDict, batch_size: int) -> int:
  113. # Background update to analyze user_ips table before we run the
  114. # deduplication background update. The table may not have been analyzed
  115. # for ages due to the table locks.
  116. #
  117. # This will lock out the naive upserts to user_ips while it happens, but
  118. # the analyze should be quick (28GB table takes ~10s)
  119. def user_ips_analyze(txn: LoggingTransaction) -> None:
  120. txn.execute("ANALYZE user_ips")
  121. await self.db_pool.runInteraction("user_ips_analyze", user_ips_analyze)
  122. await self.db_pool.updates._end_background_update("user_ips_analyze")
  123. return 1
  124. async def _remove_user_ip_dupes(self, progress: JsonDict, batch_size: int) -> int:
  125. # This works function works by scanning the user_ips table in batches
  126. # based on `last_seen`. For each row in a batch it searches the rest of
  127. # the table to see if there are any duplicates, if there are then they
  128. # are removed and replaced with a suitable row.
  129. # Fetch the start of the batch
  130. begin_last_seen: int = progress.get("last_seen", 0)
  131. def get_last_seen(txn: LoggingTransaction) -> Optional[int]:
  132. txn.execute(
  133. """
  134. SELECT last_seen FROM user_ips
  135. WHERE last_seen > ?
  136. ORDER BY last_seen
  137. LIMIT 1
  138. OFFSET ?
  139. """,
  140. (begin_last_seen, batch_size),
  141. )
  142. row = cast(Optional[Tuple[int]], txn.fetchone())
  143. if row:
  144. return row[0]
  145. else:
  146. return None
  147. # Get a last seen that has roughly `batch_size` since `begin_last_seen`
  148. end_last_seen = await self.db_pool.runInteraction(
  149. "user_ips_dups_get_last_seen", get_last_seen
  150. )
  151. # If it returns None, then we're processing the last batch
  152. last = end_last_seen is None
  153. logger.info(
  154. "Scanning for duplicate 'user_ips' rows in range: %s <= last_seen < %s",
  155. begin_last_seen,
  156. end_last_seen,
  157. )
  158. def remove(txn: LoggingTransaction) -> None:
  159. # This works by looking at all entries in the given time span, and
  160. # then for each (user_id, access_token, ip) tuple in that range
  161. # checking for any duplicates in the rest of the table (via a join).
  162. # It then only returns entries which have duplicates, and the max
  163. # last_seen across all duplicates, which can the be used to delete
  164. # all other duplicates.
  165. # It is efficient due to the existence of (user_id, access_token,
  166. # ip) and (last_seen) indices.
  167. # Define the search space, which requires handling the last batch in
  168. # a different way
  169. args: Tuple[int, ...]
  170. if last:
  171. clause = "? <= last_seen"
  172. args = (begin_last_seen,)
  173. else:
  174. assert end_last_seen is not None
  175. clause = "? <= last_seen AND last_seen < ?"
  176. args = (begin_last_seen, end_last_seen)
  177. # (Note: The DISTINCT in the inner query is important to ensure that
  178. # the COUNT(*) is accurate, otherwise double counting may happen due
  179. # to the join effectively being a cross product)
  180. txn.execute(
  181. """
  182. SELECT user_id, access_token, ip,
  183. MAX(device_id), MAX(user_agent), MAX(last_seen),
  184. COUNT(*)
  185. FROM (
  186. SELECT DISTINCT user_id, access_token, ip
  187. FROM user_ips
  188. WHERE {}
  189. ) c
  190. INNER JOIN user_ips USING (user_id, access_token, ip)
  191. GROUP BY user_id, access_token, ip
  192. HAVING count(*) > 1
  193. """.format(
  194. clause
  195. ),
  196. args,
  197. )
  198. res = cast(
  199. List[Tuple[str, str, str, Optional[str], str, int, int]], txn.fetchall()
  200. )
  201. # We've got some duplicates
  202. for i in res:
  203. user_id, access_token, ip, device_id, user_agent, last_seen, count = i
  204. # We want to delete the duplicates so we end up with only a
  205. # single row.
  206. #
  207. # The naive way of doing this would be just to delete all rows
  208. # and reinsert a constructed row. However, if there are a lot of
  209. # duplicate rows this can cause the table to grow a lot, which
  210. # can be problematic in two ways:
  211. # 1. If user_ips is already large then this can cause the
  212. # table to rapidly grow, potentially filling the disk.
  213. # 2. Reinserting a lot of rows can confuse the table
  214. # statistics for postgres, causing it to not use the
  215. # correct indices for the query above, resulting in a full
  216. # table scan. This is incredibly slow for large tables and
  217. # can kill database performance. (This seems to mainly
  218. # happen for the last query where the clause is simply `? <
  219. # last_seen`)
  220. #
  221. # So instead we want to delete all but *one* of the duplicate
  222. # rows. That is hard to do reliably, so we cheat and do a two
  223. # step process:
  224. # 1. Delete all rows with a last_seen strictly less than the
  225. # max last_seen. This hopefully results in deleting all but
  226. # one row the majority of the time, but there may be
  227. # duplicate last_seen
  228. # 2. If multiple rows remain, we fall back to the naive method
  229. # and simply delete all rows and reinsert.
  230. #
  231. # Note that this relies on no new duplicate rows being inserted,
  232. # but if that is happening then this entire process is futile
  233. # anyway.
  234. # Do step 1:
  235. txn.execute(
  236. """
  237. DELETE FROM user_ips
  238. WHERE user_id = ? AND access_token = ? AND ip = ? AND last_seen < ?
  239. """,
  240. (user_id, access_token, ip, last_seen),
  241. )
  242. if txn.rowcount == count - 1:
  243. # We deleted all but one of the duplicate rows, i.e. there
  244. # is exactly one remaining and so there is nothing left to
  245. # do.
  246. continue
  247. elif txn.rowcount >= count:
  248. raise Exception(
  249. "We deleted more duplicate rows from 'user_ips' than expected"
  250. )
  251. # The previous step didn't delete enough rows, so we fallback to
  252. # step 2:
  253. # Drop all the duplicates
  254. txn.execute(
  255. """
  256. DELETE FROM user_ips
  257. WHERE user_id = ? AND access_token = ? AND ip = ?
  258. """,
  259. (user_id, access_token, ip),
  260. )
  261. # Add in one to be the last_seen
  262. txn.execute(
  263. """
  264. INSERT INTO user_ips
  265. (user_id, access_token, ip, device_id, user_agent, last_seen)
  266. VALUES (?, ?, ?, ?, ?, ?)
  267. """,
  268. (user_id, access_token, ip, device_id, user_agent, last_seen),
  269. )
  270. self.db_pool.updates._background_update_progress_txn(
  271. txn, "user_ips_remove_dupes", {"last_seen": end_last_seen}
  272. )
  273. await self.db_pool.runInteraction("user_ips_dups_remove", remove)
  274. if last:
  275. await self.db_pool.updates._end_background_update("user_ips_remove_dupes")
  276. return batch_size
  277. async def _devices_last_seen_update(
  278. self, progress: JsonDict, batch_size: int
  279. ) -> int:
  280. """Background update to insert last seen info into devices table"""
  281. last_user_id: str = progress.get("last_user_id", "")
  282. last_device_id: str = progress.get("last_device_id", "")
  283. def _devices_last_seen_update_txn(txn: LoggingTransaction) -> int:
  284. # This consists of two queries:
  285. #
  286. # 1. The sub-query searches for the next N devices and joins
  287. # against user_ips to find the max last_seen associated with
  288. # that device.
  289. # 2. The outer query then joins again against user_ips on
  290. # user/device/last_seen. This *should* hopefully only
  291. # return one row, but if it does return more than one then
  292. # we'll just end up updating the same device row multiple
  293. # times, which is fine.
  294. where_args: List[Union[str, int]]
  295. where_clause, where_args = make_tuple_comparison_clause(
  296. [("user_id", last_user_id), ("device_id", last_device_id)],
  297. )
  298. sql = """
  299. SELECT
  300. last_seen, ip, user_agent, user_id, device_id
  301. FROM (
  302. SELECT
  303. user_id, device_id, MAX(u.last_seen) AS last_seen
  304. FROM devices
  305. INNER JOIN user_ips AS u USING (user_id, device_id)
  306. WHERE %(where_clause)s
  307. GROUP BY user_id, device_id
  308. ORDER BY user_id ASC, device_id ASC
  309. LIMIT ?
  310. ) c
  311. INNER JOIN user_ips AS u USING (user_id, device_id, last_seen)
  312. """ % {
  313. "where_clause": where_clause
  314. }
  315. txn.execute(sql, where_args + [batch_size])
  316. rows = cast(List[Tuple[int, str, str, str, str]], txn.fetchall())
  317. if not rows:
  318. return 0
  319. sql = """
  320. UPDATE devices
  321. SET last_seen = ?, ip = ?, user_agent = ?
  322. WHERE user_id = ? AND device_id = ?
  323. """
  324. txn.execute_batch(sql, rows)
  325. _, _, _, user_id, device_id = rows[-1]
  326. self.db_pool.updates._background_update_progress_txn(
  327. txn,
  328. "devices_last_seen",
  329. {"last_user_id": user_id, "last_device_id": device_id},
  330. )
  331. return len(rows)
  332. updated = await self.db_pool.runInteraction(
  333. "_devices_last_seen_update", _devices_last_seen_update_txn
  334. )
  335. if not updated:
  336. await self.db_pool.updates._end_background_update("devices_last_seen")
  337. return updated
  338. class ClientIpWorkerStore(ClientIpBackgroundUpdateStore, MonthlyActiveUsersWorkerStore):
  339. def __init__(
  340. self,
  341. database: DatabasePool,
  342. db_conn: LoggingDatabaseConnection,
  343. hs: "HomeServer",
  344. ):
  345. super().__init__(database, db_conn, hs)
  346. if hs.config.redis.redis_enabled:
  347. # If we're using Redis, we can shift this update process off to
  348. # the background worker
  349. self._update_on_this_worker = hs.config.worker.run_background_tasks
  350. else:
  351. # If we're NOT using Redis, this must be handled by the master
  352. self._update_on_this_worker = hs.get_instance_name() == "master"
  353. self.user_ips_max_age = hs.config.server.user_ips_max_age
  354. # (user_id, access_token, ip,) -> last_seen
  355. self.client_ip_last_seen = LruCache[Tuple[str, str, str], int](
  356. cache_name="client_ip_last_seen", max_size=50000
  357. )
  358. if hs.config.worker.run_background_tasks and self.user_ips_max_age:
  359. self._clock.looping_call(self._prune_old_user_ips, 5 * 1000)
  360. if self._update_on_this_worker:
  361. # This is the designated worker that can write to the client IP
  362. # tables.
  363. # (user_id, access_token, ip,) -> (user_agent, device_id, last_seen)
  364. self._batch_row_update: Dict[
  365. Tuple[str, str, str], Tuple[str, Optional[str], int]
  366. ] = {}
  367. self._client_ip_looper = self._clock.looping_call(
  368. self._update_client_ips_batch, 5 * 1000
  369. )
  370. self.hs.get_reactor().addSystemEventTrigger(
  371. "before", "shutdown", self._update_client_ips_batch
  372. )
  373. @wrap_as_background_process("prune_old_user_ips")
  374. async def _prune_old_user_ips(self) -> None:
  375. """Removes entries in user IPs older than the configured period."""
  376. if self.user_ips_max_age is None:
  377. # Nothing to do
  378. return
  379. if not await self.db_pool.updates.has_completed_background_update(
  380. "devices_last_seen"
  381. ):
  382. # Only start pruning if we have finished populating the devices
  383. # last seen info.
  384. return
  385. # We do a slightly funky SQL delete to ensure we don't try and delete
  386. # too much at once (as the table may be very large from before we
  387. # started pruning).
  388. #
  389. # This works by finding the max last_seen that is less than the given
  390. # time, but has no more than N rows before it, deleting all rows with
  391. # a lesser last_seen time. (We COALESCE so that the sub-SELECT always
  392. # returns exactly one row).
  393. sql = """
  394. DELETE FROM user_ips
  395. WHERE last_seen <= (
  396. SELECT COALESCE(MAX(last_seen), -1)
  397. FROM (
  398. SELECT last_seen FROM user_ips
  399. WHERE last_seen <= ?
  400. ORDER BY last_seen ASC
  401. LIMIT 5000
  402. ) AS u
  403. )
  404. """
  405. timestamp = self._clock.time_msec() - self.user_ips_max_age
  406. def _prune_old_user_ips_txn(txn: LoggingTransaction) -> None:
  407. txn.execute(sql, (timestamp,))
  408. await self.db_pool.runInteraction(
  409. "_prune_old_user_ips", _prune_old_user_ips_txn
  410. )
  411. async def _get_last_client_ip_by_device_from_database(
  412. self, user_id: str, device_id: Optional[str]
  413. ) -> Dict[Tuple[str, str], DeviceLastConnectionInfo]:
  414. """For each device_id listed, give the user_ip it was last seen on.
  415. The result might be slightly out of date as client IPs are inserted in batches.
  416. Args:
  417. user_id: The user to fetch devices for.
  418. device_id: If None fetches all devices for the user
  419. Returns:
  420. A dictionary mapping a tuple of (user_id, device_id) to dicts, with
  421. keys giving the column names from the devices table.
  422. """
  423. keyvalues = {"user_id": user_id}
  424. if device_id is not None:
  425. keyvalues["device_id"] = device_id
  426. res = cast(
  427. List[DeviceLastConnectionInfo],
  428. await self.db_pool.simple_select_list(
  429. table="devices",
  430. keyvalues=keyvalues,
  431. retcols=("user_id", "ip", "user_agent", "device_id", "last_seen"),
  432. ),
  433. )
  434. return {(d["user_id"], d["device_id"]): d for d in res}
  435. async def _get_user_ip_and_agents_from_database(
  436. self, user: UserID, since_ts: int = 0
  437. ) -> List[LastConnectionInfo]:
  438. """Fetch the IPs and user agents for a user since the given timestamp.
  439. The result might be slightly out of date as client IPs are inserted in batches.
  440. Args:
  441. user: The user for which to fetch IP addresses and user agents.
  442. since_ts: The timestamp after which to fetch IP addresses and user agents,
  443. in milliseconds.
  444. Returns:
  445. A list of dictionaries, each containing:
  446. * `access_token`: The access token used.
  447. * `ip`: The IP address used.
  448. * `user_agent`: The last user agent seen for this access token and IP
  449. address combination.
  450. * `last_seen`: The timestamp at which this access token and IP address
  451. combination was last seen, in milliseconds.
  452. Only the latest user agent for each access token and IP address combination
  453. is available.
  454. """
  455. user_id = user.to_string()
  456. def get_recent(txn: LoggingTransaction) -> List[Tuple[str, str, str, int]]:
  457. txn.execute(
  458. """
  459. SELECT access_token, ip, user_agent, last_seen FROM user_ips
  460. WHERE last_seen >= ? AND user_id = ?
  461. ORDER BY last_seen
  462. DESC
  463. """,
  464. (since_ts, user_id),
  465. )
  466. return cast(List[Tuple[str, str, str, int]], txn.fetchall())
  467. rows = await self.db_pool.runInteraction(
  468. desc="get_user_ip_and_agents", func=get_recent
  469. )
  470. return [
  471. {
  472. "access_token": access_token,
  473. "ip": ip,
  474. "user_agent": user_agent,
  475. "last_seen": last_seen,
  476. }
  477. for access_token, ip, user_agent, last_seen in rows
  478. ]
  479. async def insert_client_ip(
  480. self,
  481. user_id: str,
  482. access_token: str,
  483. ip: str,
  484. user_agent: str,
  485. device_id: Optional[str],
  486. now: Optional[int] = None,
  487. ) -> None:
  488. # The sync proxy continuously triggers /sync even if the user is not
  489. # present so should be excluded from user_ips entries.
  490. if user_agent == "sync-v3-proxy-":
  491. return
  492. if not now:
  493. now = int(self._clock.time_msec())
  494. key = (user_id, access_token, ip)
  495. try:
  496. last_seen = self.client_ip_last_seen.get(key)
  497. except KeyError:
  498. last_seen = None
  499. # Rate-limited inserts
  500. if last_seen is not None and (now - last_seen) < LAST_SEEN_GRANULARITY:
  501. return
  502. self.client_ip_last_seen.set(key, now)
  503. if self._update_on_this_worker:
  504. await self.populate_monthly_active_users(user_id)
  505. self._batch_row_update[key] = (user_agent, device_id, now)
  506. else:
  507. # We are not the designated writer-worker, so stream over replication
  508. self.hs.get_replication_command_handler().send_user_ip(
  509. user_id, access_token, ip, user_agent, device_id, now
  510. )
  511. @wrap_as_background_process("update_client_ips")
  512. async def _update_client_ips_batch(self) -> None:
  513. assert (
  514. self._update_on_this_worker
  515. ), "This worker is not designated to update client IPs"
  516. # If the DB pool has already terminated, don't try updating
  517. if not self.db_pool.is_running():
  518. return
  519. to_update = self._batch_row_update
  520. self._batch_row_update = {}
  521. if to_update:
  522. await self.db_pool.runInteraction(
  523. "_update_client_ips_batch", self._update_client_ips_batch_txn, to_update
  524. )
  525. def _update_client_ips_batch_txn(
  526. self,
  527. txn: LoggingTransaction,
  528. to_update: Mapping[Tuple[str, str, str], Tuple[str, Optional[str], int]],
  529. ) -> None:
  530. assert (
  531. self._update_on_this_worker
  532. ), "This worker is not designated to update client IPs"
  533. # Keys and values for the `user_ips` upsert.
  534. user_ips_keys = []
  535. user_ips_values = []
  536. # Keys and values for the `devices` update.
  537. devices_keys = []
  538. devices_values = []
  539. for entry in to_update.items():
  540. (user_id, access_token, ip), (user_agent, device_id, last_seen) = entry
  541. user_ips_keys.append((user_id, access_token, ip))
  542. user_ips_values.append((user_agent, device_id, last_seen))
  543. # Technically an access token might not be associated with
  544. # a device so we need to check.
  545. if device_id:
  546. devices_keys.append((user_id, device_id))
  547. devices_values.append((user_agent, last_seen, ip))
  548. self.db_pool.simple_upsert_many_txn(
  549. txn,
  550. table="user_ips",
  551. key_names=("user_id", "access_token", "ip"),
  552. key_values=user_ips_keys,
  553. value_names=("user_agent", "device_id", "last_seen"),
  554. value_values=user_ips_values,
  555. )
  556. if devices_values:
  557. self.db_pool.simple_update_many_txn(
  558. txn,
  559. table="devices",
  560. key_names=("user_id", "device_id"),
  561. key_values=devices_keys,
  562. value_names=("user_agent", "last_seen", "ip"),
  563. value_values=devices_values,
  564. )
  565. async def get_last_client_ip_by_device(
  566. self, user_id: str, device_id: Optional[str]
  567. ) -> Dict[Tuple[str, str], DeviceLastConnectionInfo]:
  568. """For each device_id listed, give the user_ip it was last seen on
  569. Args:
  570. user_id: The user to fetch devices for.
  571. device_id: If None fetches all devices for the user
  572. Returns:
  573. A dictionary mapping a tuple of (user_id, device_id) to dicts, with
  574. keys giving the column names from the devices table.
  575. """
  576. ret = await self._get_last_client_ip_by_device_from_database(user_id, device_id)
  577. if not self._update_on_this_worker:
  578. # Only the writing-worker has additional in-memory data to enhance
  579. # the result
  580. return ret
  581. # Update what is retrieved from the database with data which is pending
  582. # insertion, as if it has already been stored in the database.
  583. for key in self._batch_row_update:
  584. uid, _access_token, ip = key
  585. if uid == user_id:
  586. user_agent, did, last_seen = self._batch_row_update[key]
  587. if did is None:
  588. # These updates don't make it to the `devices` table
  589. continue
  590. if not device_id or did == device_id:
  591. ret[(user_id, did)] = {
  592. "user_id": user_id,
  593. "ip": ip,
  594. "user_agent": user_agent,
  595. "device_id": did,
  596. "last_seen": last_seen,
  597. }
  598. return ret
  599. async def get_user_ip_and_agents(
  600. self, user: UserID, since_ts: int = 0
  601. ) -> List[LastConnectionInfo]:
  602. """Fetch the IPs and user agents for a user since the given timestamp.
  603. Args:
  604. user: The user for which to fetch IP addresses and user agents.
  605. since_ts: The timestamp after which to fetch IP addresses and user agents,
  606. in milliseconds.
  607. Returns:
  608. A list of dictionaries, each containing:
  609. * `access_token`: The access token used.
  610. * `ip`: The IP address used.
  611. * `user_agent`: The last user agent seen for this access token and IP
  612. address combination.
  613. * `last_seen`: The timestamp at which this access token and IP address
  614. combination was last seen, in milliseconds.
  615. Only the latest user agent for each access token and IP address combination
  616. is available.
  617. """
  618. rows_from_db = await self._get_user_ip_and_agents_from_database(user, since_ts)
  619. if not self._update_on_this_worker:
  620. # Only the writing-worker has additional in-memory data to enhance
  621. # the result
  622. return rows_from_db
  623. results: Dict[Tuple[str, str], LastConnectionInfo] = {
  624. (connection["access_token"], connection["ip"]): connection
  625. for connection in rows_from_db
  626. }
  627. # Overlay data that is pending insertion on top of the results from the
  628. # database.
  629. user_id = user.to_string()
  630. for key in self._batch_row_update:
  631. uid, access_token, ip = key
  632. if uid == user_id:
  633. user_agent, _, last_seen = self._batch_row_update[key]
  634. if last_seen >= since_ts:
  635. results[(access_token, ip)] = {
  636. "access_token": access_token,
  637. "ip": ip,
  638. "user_agent": user_agent,
  639. "last_seen": last_seen,
  640. }
  641. return list(results.values())
  642. async def get_last_seen_for_user_id(self, user_id: str) -> Optional[int]:
  643. """Get the last seen timestamp for a user, if we have it."""
  644. return await self.db_pool.simple_select_one_onecol(
  645. table="user_ips",
  646. keyvalues={"user_id": user_id},
  647. retcol="MAX(last_seen)",
  648. allow_none=True,
  649. desc="get_last_seen_for_user_id",
  650. )