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.
 
 
 
 
 
 

693 lines
24 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import (
  17. TYPE_CHECKING,
  18. Any,
  19. Dict,
  20. Iterable,
  21. Iterator,
  22. List,
  23. Optional,
  24. Tuple,
  25. cast,
  26. )
  27. from synapse.push import PusherConfig, ThrottleParams
  28. from synapse.replication.tcp.streams import PushersStream
  29. from synapse.storage._base import SQLBaseStore, db_to_json
  30. from synapse.storage.database import (
  31. DatabasePool,
  32. LoggingDatabaseConnection,
  33. LoggingTransaction,
  34. )
  35. from synapse.storage.util.id_generators import (
  36. AbstractStreamIdGenerator,
  37. AbstractStreamIdTracker,
  38. StreamIdGenerator,
  39. )
  40. from synapse.types import JsonDict
  41. from synapse.util import json_encoder
  42. from synapse.util.caches.descriptors import cached
  43. if TYPE_CHECKING:
  44. from synapse.server import HomeServer
  45. logger = logging.getLogger(__name__)
  46. class PusherWorkerStore(SQLBaseStore):
  47. def __init__(
  48. self,
  49. database: DatabasePool,
  50. db_conn: LoggingDatabaseConnection,
  51. hs: "HomeServer",
  52. ):
  53. super().__init__(database, db_conn, hs)
  54. # In the worker store this is an ID tracker which we overwrite in the non-worker
  55. # class below that is used on the main process.
  56. self._pushers_id_gen: AbstractStreamIdTracker = StreamIdGenerator(
  57. db_conn,
  58. hs.get_replication_notifier(),
  59. "pushers",
  60. "id",
  61. extra_tables=[("deleted_pushers", "stream_id")],
  62. is_writer=hs.config.worker.worker_app is None,
  63. )
  64. self.db_pool.updates.register_background_update_handler(
  65. "remove_deactivated_pushers",
  66. self._remove_deactivated_pushers,
  67. )
  68. self.db_pool.updates.register_background_update_handler(
  69. "remove_stale_pushers",
  70. self._remove_stale_pushers,
  71. )
  72. self.db_pool.updates.register_background_update_handler(
  73. "remove_deleted_email_pushers",
  74. self._remove_deleted_email_pushers,
  75. )
  76. def _decode_pushers_rows(self, rows: Iterable[dict]) -> Iterator[PusherConfig]:
  77. """JSON-decode the data in the rows returned from the `pushers` table
  78. Drops any rows whose data cannot be decoded
  79. """
  80. for r in rows:
  81. data_json = r["data"]
  82. try:
  83. r["data"] = db_to_json(data_json)
  84. except Exception as e:
  85. logger.warning(
  86. "Invalid JSON in data for pusher %d: %s, %s",
  87. r["id"],
  88. data_json,
  89. e.args[0],
  90. )
  91. continue
  92. # If we're using SQLite, then boolean values are integers. This is
  93. # troublesome since some code using the return value of this method might
  94. # expect it to be a boolean, or will expose it to clients (in responses).
  95. r["enabled"] = bool(r["enabled"])
  96. yield PusherConfig(**r)
  97. def get_pushers_stream_token(self) -> int:
  98. return self._pushers_id_gen.get_current_token()
  99. def process_replication_position(
  100. self, stream_name: str, instance_name: str, token: int
  101. ) -> None:
  102. if stream_name == PushersStream.NAME:
  103. self._pushers_id_gen.advance(instance_name, token)
  104. super().process_replication_position(stream_name, instance_name, token)
  105. async def get_pushers_by_app_id_and_pushkey(
  106. self, app_id: str, pushkey: str
  107. ) -> Iterator[PusherConfig]:
  108. return await self.get_pushers_by({"app_id": app_id, "pushkey": pushkey})
  109. async def get_pushers_by_user_id(self, user_id: str) -> Iterator[PusherConfig]:
  110. return await self.get_pushers_by({"user_name": user_id})
  111. async def get_pushers_by(self, keyvalues: Dict[str, Any]) -> Iterator[PusherConfig]:
  112. """Retrieve pushers that match the given criteria.
  113. Args:
  114. keyvalues: A {column: value} dictionary.
  115. Returns:
  116. The pushers for which the given columns have the given values.
  117. """
  118. def get_pushers_by_txn(txn: LoggingTransaction) -> List[Dict[str, Any]]:
  119. # We could technically use simple_select_list here, but we need to call
  120. # COALESCE on the 'enabled' column. While it is technically possible to give
  121. # simple_select_list the whole `COALESCE(...) AS ...` as a column name, it
  122. # feels a bit hacky, so it's probably better to just inline the query.
  123. sql = """
  124. SELECT
  125. id, user_name, access_token, profile_tag, kind, app_id,
  126. app_display_name, device_display_name, pushkey, ts, lang, data,
  127. last_stream_ordering, last_success, failing_since,
  128. COALESCE(enabled, TRUE) AS enabled, device_id
  129. FROM pushers
  130. """
  131. sql += "WHERE %s" % (" AND ".join("%s = ?" % (k,) for k in keyvalues),)
  132. txn.execute(sql, list(keyvalues.values()))
  133. return self.db_pool.cursor_to_dict(txn)
  134. ret = await self.db_pool.runInteraction(
  135. desc="get_pushers_by",
  136. func=get_pushers_by_txn,
  137. )
  138. return self._decode_pushers_rows(ret)
  139. async def get_enabled_pushers(self) -> Iterator[PusherConfig]:
  140. def get_enabled_pushers_txn(txn: LoggingTransaction) -> Iterator[PusherConfig]:
  141. txn.execute("SELECT * FROM pushers WHERE COALESCE(enabled, TRUE)")
  142. rows = self.db_pool.cursor_to_dict(txn)
  143. return self._decode_pushers_rows(rows)
  144. return await self.db_pool.runInteraction(
  145. "get_enabled_pushers", get_enabled_pushers_txn
  146. )
  147. async def get_all_updated_pushers_rows(
  148. self, instance_name: str, last_id: int, current_id: int, limit: int
  149. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  150. """Get updates for pushers replication stream.
  151. Args:
  152. instance_name: The writer we want to fetch updates from. Unused
  153. here since there is only ever one writer.
  154. last_id: The token to fetch updates from. Exclusive.
  155. current_id: The token to fetch updates up to. Inclusive.
  156. limit: The requested limit for the number of rows to return. The
  157. function may return more or fewer rows.
  158. Returns:
  159. A tuple consisting of: the updates, a token to use to fetch
  160. subsequent updates, and whether we returned fewer rows than exists
  161. between the requested tokens due to the limit.
  162. The token returned can be used in a subsequent call to this
  163. function to get further updatees.
  164. The updates are a list of 2-tuples of stream ID and the row data
  165. """
  166. if last_id == current_id:
  167. return [], current_id, False
  168. def get_all_updated_pushers_rows_txn(
  169. txn: LoggingTransaction,
  170. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  171. sql = """
  172. SELECT id, user_name, app_id, pushkey
  173. FROM pushers
  174. WHERE ? < id AND id <= ?
  175. ORDER BY id ASC LIMIT ?
  176. """
  177. txn.execute(sql, (last_id, current_id, limit))
  178. updates = cast(
  179. List[Tuple[int, tuple]],
  180. [
  181. (stream_id, (user_name, app_id, pushkey, False))
  182. for stream_id, user_name, app_id, pushkey in txn
  183. ],
  184. )
  185. sql = """
  186. SELECT stream_id, user_id, app_id, pushkey
  187. FROM deleted_pushers
  188. WHERE ? < stream_id AND stream_id <= ?
  189. ORDER BY stream_id ASC LIMIT ?
  190. """
  191. txn.execute(sql, (last_id, current_id, limit))
  192. updates.extend(
  193. (stream_id, (user_name, app_id, pushkey, True))
  194. for stream_id, user_name, app_id, pushkey in txn
  195. )
  196. updates.sort() # Sort so that they're ordered by stream id
  197. limited = False
  198. upper_bound = current_id
  199. if len(updates) >= limit:
  200. limited = True
  201. upper_bound = updates[-1][0]
  202. return updates, upper_bound, limited
  203. return await self.db_pool.runInteraction(
  204. "get_all_updated_pushers_rows", get_all_updated_pushers_rows_txn
  205. )
  206. @cached(num_args=1, max_entries=15000)
  207. async def get_if_user_has_pusher(self, user_id: str) -> None:
  208. # This only exists for the cachedList decorator
  209. raise NotImplementedError()
  210. async def update_pusher_last_stream_ordering(
  211. self, app_id: str, pushkey: str, user_id: str, last_stream_ordering: int
  212. ) -> None:
  213. await self.db_pool.simple_update_one(
  214. "pushers",
  215. {"app_id": app_id, "pushkey": pushkey, "user_name": user_id},
  216. {"last_stream_ordering": last_stream_ordering},
  217. desc="update_pusher_last_stream_ordering",
  218. )
  219. async def update_pusher_last_stream_ordering_and_success(
  220. self,
  221. app_id: str,
  222. pushkey: str,
  223. user_id: str,
  224. last_stream_ordering: int,
  225. last_success: int,
  226. ) -> bool:
  227. """Update the last stream ordering position we've processed up to for
  228. the given pusher.
  229. Args:
  230. app_id
  231. pushkey
  232. user_id
  233. last_stream_ordering
  234. last_success
  235. Returns:
  236. True if the pusher still exists; False if it has been deleted.
  237. """
  238. updated = await self.db_pool.simple_update(
  239. table="pushers",
  240. keyvalues={"app_id": app_id, "pushkey": pushkey, "user_name": user_id},
  241. updatevalues={
  242. "last_stream_ordering": last_stream_ordering,
  243. "last_success": last_success,
  244. },
  245. desc="update_pusher_last_stream_ordering_and_success",
  246. )
  247. return bool(updated)
  248. async def update_pusher_failing_since(
  249. self, app_id: str, pushkey: str, user_id: str, failing_since: Optional[int]
  250. ) -> None:
  251. await self.db_pool.simple_update(
  252. table="pushers",
  253. keyvalues={"app_id": app_id, "pushkey": pushkey, "user_name": user_id},
  254. updatevalues={"failing_since": failing_since},
  255. desc="update_pusher_failing_since",
  256. )
  257. async def get_throttle_params_by_room(
  258. self, pusher_id: str
  259. ) -> Dict[str, ThrottleParams]:
  260. res = await self.db_pool.simple_select_list(
  261. "pusher_throttle",
  262. {"pusher": pusher_id},
  263. ["room_id", "last_sent_ts", "throttle_ms"],
  264. desc="get_throttle_params_by_room",
  265. )
  266. params_by_room = {}
  267. for row in res:
  268. params_by_room[row["room_id"]] = ThrottleParams(
  269. row["last_sent_ts"],
  270. row["throttle_ms"],
  271. )
  272. return params_by_room
  273. async def set_throttle_params(
  274. self, pusher_id: str, room_id: str, params: ThrottleParams
  275. ) -> None:
  276. await self.db_pool.simple_upsert(
  277. "pusher_throttle",
  278. {"pusher": pusher_id, "room_id": room_id},
  279. {"last_sent_ts": params.last_sent_ts, "throttle_ms": params.throttle_ms},
  280. desc="set_throttle_params",
  281. )
  282. async def _remove_deactivated_pushers(self, progress: dict, batch_size: int) -> int:
  283. """A background update that deletes all pushers for deactivated users.
  284. Note that we don't proacively tell the pusherpool that we've deleted
  285. these (just because its a bit off a faff to do from here), but they will
  286. get cleaned up at the next restart
  287. """
  288. last_user = progress.get("last_user", "")
  289. def _delete_pushers(txn: LoggingTransaction) -> int:
  290. sql = """
  291. SELECT name FROM users
  292. WHERE deactivated = ? and name > ?
  293. ORDER BY name ASC
  294. LIMIT ?
  295. """
  296. txn.execute(sql, (1, last_user, batch_size))
  297. users = [row[0] for row in txn]
  298. self.db_pool.simple_delete_many_txn(
  299. txn,
  300. table="pushers",
  301. column="user_name",
  302. values=users,
  303. keyvalues={},
  304. )
  305. if users:
  306. self.db_pool.updates._background_update_progress_txn(
  307. txn, "remove_deactivated_pushers", {"last_user": users[-1]}
  308. )
  309. return len(users)
  310. number_deleted = await self.db_pool.runInteraction(
  311. "_remove_deactivated_pushers", _delete_pushers
  312. )
  313. if number_deleted < batch_size:
  314. await self.db_pool.updates._end_background_update(
  315. "remove_deactivated_pushers"
  316. )
  317. return number_deleted
  318. async def _remove_stale_pushers(self, progress: dict, batch_size: int) -> int:
  319. """A background update that deletes all pushers for logged out devices.
  320. Note that we don't proacively tell the pusherpool that we've deleted
  321. these (just because its a bit off a faff to do from here), but they will
  322. get cleaned up at the next restart
  323. """
  324. last_pusher = progress.get("last_pusher", 0)
  325. def _delete_pushers(txn: LoggingTransaction) -> int:
  326. sql = """
  327. SELECT p.id, access_token FROM pushers AS p
  328. LEFT JOIN access_tokens AS a ON (p.access_token = a.id)
  329. WHERE p.id > ?
  330. ORDER BY p.id ASC
  331. LIMIT ?
  332. """
  333. txn.execute(sql, (last_pusher, batch_size))
  334. pushers = [(row[0], row[1]) for row in txn]
  335. self.db_pool.simple_delete_many_txn(
  336. txn,
  337. table="pushers",
  338. column="id",
  339. values=[pusher_id for pusher_id, token in pushers if token is None],
  340. keyvalues={},
  341. )
  342. if pushers:
  343. self.db_pool.updates._background_update_progress_txn(
  344. txn, "remove_stale_pushers", {"last_pusher": pushers[-1][0]}
  345. )
  346. return len(pushers)
  347. number_deleted = await self.db_pool.runInteraction(
  348. "_remove_stale_pushers", _delete_pushers
  349. )
  350. if number_deleted < batch_size:
  351. await self.db_pool.updates._end_background_update("remove_stale_pushers")
  352. return number_deleted
  353. async def _remove_deleted_email_pushers(
  354. self, progress: dict, batch_size: int
  355. ) -> int:
  356. """A background update that deletes all pushers for deleted email addresses.
  357. In previous versions of synapse, when users deleted their email address, it didn't
  358. also delete all the pushers for that email address. This background update removes
  359. those to prevent unwanted emails. This should only need to be run once (when users
  360. upgrade to v1.42.0
  361. Args:
  362. progress: dict used to store progress of this background update
  363. batch_size: the maximum number of rows to retrieve in a single select query
  364. Returns:
  365. The number of deleted rows
  366. """
  367. last_pusher = progress.get("last_pusher", 0)
  368. def _delete_pushers(txn: LoggingTransaction) -> int:
  369. sql = """
  370. SELECT p.id, p.user_name, p.app_id, p.pushkey
  371. FROM pushers AS p
  372. LEFT JOIN user_threepids AS t
  373. ON t.user_id = p.user_name
  374. AND t.medium = 'email'
  375. AND t.address = p.pushkey
  376. WHERE t.user_id is NULL
  377. AND p.app_id = 'm.email'
  378. AND p.id > ?
  379. ORDER BY p.id ASC
  380. LIMIT ?
  381. """
  382. txn.execute(sql, (last_pusher, batch_size))
  383. rows = txn.fetchall()
  384. last = None
  385. num_deleted = 0
  386. for row in rows:
  387. last = row[0]
  388. num_deleted += 1
  389. self.db_pool.simple_delete_txn(
  390. txn,
  391. "pushers",
  392. {"user_name": row[1], "app_id": row[2], "pushkey": row[3]},
  393. )
  394. if last is not None:
  395. self.db_pool.updates._background_update_progress_txn(
  396. txn, "remove_deleted_email_pushers", {"last_pusher": last}
  397. )
  398. return num_deleted
  399. number_deleted = await self.db_pool.runInteraction(
  400. "_remove_deleted_email_pushers", _delete_pushers
  401. )
  402. if number_deleted < batch_size:
  403. await self.db_pool.updates._end_background_update(
  404. "remove_deleted_email_pushers"
  405. )
  406. return number_deleted
  407. class PusherBackgroundUpdatesStore(SQLBaseStore):
  408. def __init__(
  409. self,
  410. database: DatabasePool,
  411. db_conn: LoggingDatabaseConnection,
  412. hs: "HomeServer",
  413. ):
  414. super().__init__(database, db_conn, hs)
  415. self.db_pool.updates.register_background_update_handler(
  416. "set_device_id_for_pushers", self._set_device_id_for_pushers
  417. )
  418. async def _set_device_id_for_pushers(
  419. self, progress: JsonDict, batch_size: int
  420. ) -> int:
  421. """Background update to populate the device_id column of the pushers table."""
  422. last_pusher_id = progress.get("pusher_id", 0)
  423. def set_device_id_for_pushers_txn(txn: LoggingTransaction) -> int:
  424. txn.execute(
  425. """
  426. SELECT p.id, at.device_id
  427. FROM pushers AS p
  428. INNER JOIN access_tokens AS at
  429. ON p.access_token = at.id
  430. WHERE
  431. p.access_token IS NOT NULL
  432. AND at.device_id IS NOT NULL
  433. AND p.id > ?
  434. ORDER BY p.id
  435. LIMIT ?
  436. """,
  437. (last_pusher_id, batch_size),
  438. )
  439. rows = self.db_pool.cursor_to_dict(txn)
  440. if len(rows) == 0:
  441. return 0
  442. self.db_pool.simple_update_many_txn(
  443. txn=txn,
  444. table="pushers",
  445. key_names=("id",),
  446. key_values=[(row["id"],) for row in rows],
  447. value_names=("device_id",),
  448. value_values=[(row["device_id"],) for row in rows],
  449. )
  450. self.db_pool.updates._background_update_progress_txn(
  451. txn, "set_device_id_for_pushers", {"pusher_id": rows[-1]["id"]}
  452. )
  453. return len(rows)
  454. nb_processed = await self.db_pool.runInteraction(
  455. "set_device_id_for_pushers", set_device_id_for_pushers_txn
  456. )
  457. if nb_processed < batch_size:
  458. await self.db_pool.updates._end_background_update(
  459. "set_device_id_for_pushers"
  460. )
  461. return nb_processed
  462. class PusherStore(PusherWorkerStore, PusherBackgroundUpdatesStore):
  463. # Because we have write access, this will be a StreamIdGenerator
  464. # (see PusherWorkerStore.__init__)
  465. _pushers_id_gen: AbstractStreamIdGenerator
  466. async def add_pusher(
  467. self,
  468. user_id: str,
  469. access_token: Optional[int],
  470. kind: str,
  471. app_id: str,
  472. app_display_name: str,
  473. device_display_name: str,
  474. pushkey: str,
  475. pushkey_ts: int,
  476. lang: Optional[str],
  477. data: Optional[JsonDict],
  478. last_stream_ordering: int,
  479. profile_tag: str = "",
  480. enabled: bool = True,
  481. device_id: Optional[str] = None,
  482. ) -> None:
  483. async with self._pushers_id_gen.get_next() as stream_id:
  484. await self.db_pool.simple_upsert(
  485. table="pushers",
  486. keyvalues={"app_id": app_id, "pushkey": pushkey, "user_name": user_id},
  487. values={
  488. "access_token": access_token,
  489. "kind": kind,
  490. "app_display_name": app_display_name,
  491. "device_display_name": device_display_name,
  492. "ts": pushkey_ts,
  493. "lang": lang,
  494. "data": json_encoder.encode(data),
  495. "last_stream_ordering": last_stream_ordering,
  496. "profile_tag": profile_tag,
  497. "id": stream_id,
  498. "enabled": enabled,
  499. "device_id": device_id,
  500. },
  501. desc="add_pusher",
  502. )
  503. user_has_pusher = self.get_if_user_has_pusher.cache.get_immediate(
  504. (user_id,), None, update_metrics=False
  505. )
  506. if user_has_pusher is not True:
  507. # invalidate, since we the user might not have had a pusher before
  508. await self.db_pool.runInteraction(
  509. "add_pusher",
  510. self._invalidate_cache_and_stream, # type: ignore[attr-defined]
  511. self.get_if_user_has_pusher,
  512. (user_id,),
  513. )
  514. async def delete_pusher_by_app_id_pushkey_user_id(
  515. self, app_id: str, pushkey: str, user_id: str
  516. ) -> None:
  517. def delete_pusher_txn(txn: LoggingTransaction, stream_id: int) -> None:
  518. self._invalidate_cache_and_stream( # type: ignore[attr-defined]
  519. txn, self.get_if_user_has_pusher, (user_id,)
  520. )
  521. # It is expected that there is exactly one pusher to delete, but
  522. # if it isn't there (or there are multiple) delete them all.
  523. self.db_pool.simple_delete_txn(
  524. txn,
  525. "pushers",
  526. {"app_id": app_id, "pushkey": pushkey, "user_name": user_id},
  527. )
  528. # it's possible for us to end up with duplicate rows for
  529. # (app_id, pushkey, user_id) at different stream_ids, but that
  530. # doesn't really matter.
  531. self.db_pool.simple_insert_txn(
  532. txn,
  533. table="deleted_pushers",
  534. values={
  535. "stream_id": stream_id,
  536. "app_id": app_id,
  537. "pushkey": pushkey,
  538. "user_id": user_id,
  539. },
  540. )
  541. async with self._pushers_id_gen.get_next() as stream_id:
  542. await self.db_pool.runInteraction(
  543. "delete_pusher", delete_pusher_txn, stream_id
  544. )
  545. async def delete_all_pushers_for_user(self, user_id: str) -> None:
  546. """Delete all pushers associated with an account."""
  547. # We want to generate a row in `deleted_pushers` for each pusher we're
  548. # deleting, so we fetch the list now so we can generate the appropriate
  549. # number of stream IDs.
  550. #
  551. # Note: technically there could be a race here between adding/deleting
  552. # pushers, but a) the worst case if we don't stop a pusher until the
  553. # next restart and b) this is only called when we're deactivating an
  554. # account.
  555. pushers = list(await self.get_pushers_by_user_id(user_id))
  556. def delete_pushers_txn(txn: LoggingTransaction, stream_ids: List[int]) -> None:
  557. self._invalidate_cache_and_stream( # type: ignore[attr-defined]
  558. txn, self.get_if_user_has_pusher, (user_id,)
  559. )
  560. self.db_pool.simple_delete_txn(
  561. txn,
  562. table="pushers",
  563. keyvalues={"user_name": user_id},
  564. )
  565. self.db_pool.simple_insert_many_txn(
  566. txn,
  567. table="deleted_pushers",
  568. keys=("stream_id", "app_id", "pushkey", "user_id"),
  569. values=[
  570. (stream_id, pusher.app_id, pusher.pushkey, user_id)
  571. for stream_id, pusher in zip(stream_ids, pushers)
  572. ],
  573. )
  574. async with self._pushers_id_gen.get_next_mult(len(pushers)) as stream_ids:
  575. await self.db_pool.runInteraction(
  576. "delete_all_pushers_for_user", delete_pushers_txn, stream_ids
  577. )