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.
 
 
 
 
 
 

1855 lines
70 KiB

  1. # Copyright 2015 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. """Responsible for storing and fetching push actions / notifications.
  16. There are two main uses for push actions:
  17. 1. Sending out push to a user's device; and
  18. 2. Tracking per-room per-user notification counts (used in sync requests).
  19. For the former we simply use the `event_push_actions` table, which contains all
  20. the calculated actions for a given user (which were calculated by the
  21. `BulkPushRuleEvaluator`).
  22. For the latter we could simply count the number of rows in `event_push_actions`
  23. table for a given room/user, but in practice this is *very* heavyweight when
  24. there were a large number of notifications (due to e.g. the user never reading a
  25. room). Plus, keeping all push actions indefinitely uses a lot of disk space.
  26. To fix these issues, we add a new table `event_push_summary` that tracks
  27. per-user per-room counts of all notifications that happened before a stream
  28. ordering S. Thus, to get the notification count for a user / room we can simply
  29. query a single row in `event_push_summary` and count the number of rows in
  30. `event_push_actions` with a stream ordering larger than S (and as long as S is
  31. "recent", the number of rows needing to be scanned will be small).
  32. The `event_push_summary` table is updated via a background job that periodically
  33. chooses a new stream ordering S' (usually the latest stream ordering), counts
  34. all notifications in `event_push_actions` between the existing S and S', and
  35. adds them to the existing counts in `event_push_summary`.
  36. This allows us to delete old rows from `event_push_actions` once those rows have
  37. been counted and added to `event_push_summary` (we call this process
  38. "rotation").
  39. We need to handle when a user sends a read receipt to the room. Again this is
  40. done as a background process. For each receipt we clear the row in
  41. `event_push_summary` and count the number of notifications in
  42. `event_push_actions` that happened after the receipt but before S, and insert
  43. that count into `event_push_summary` (If the receipt happened *after* S then we
  44. simply clear the `event_push_summary`.)
  45. Note that its possible that if the read receipt is for an old event the relevant
  46. `event_push_actions` rows will have been rotated and we get the wrong count
  47. (it'll be too low). We accept this as a rare edge case that is unlikely to
  48. impact the user much (since the vast majority of read receipts will be for the
  49. latest event).
  50. The last complication is to handle the race where we request the notifications
  51. counts after a user sends a read receipt into the room, but *before* the
  52. background update handles the receipt (without any special handling the counts
  53. would be outdated). We fix this by including in `event_push_summary` the read
  54. receipt we used when updating `event_push_summary`, and every time we query the
  55. table we check if that matches the most recent read receipt in the room. If yes,
  56. continue as above, if not we simply query the `event_push_actions` table
  57. directly.
  58. Since read receipts are almost always for recent events, scanning the
  59. `event_push_actions` table in this case is unlikely to be a problem. Even if it
  60. is a problem, it is temporary until the background job handles the new read
  61. receipt.
  62. """
  63. import logging
  64. from collections import defaultdict
  65. from typing import (
  66. TYPE_CHECKING,
  67. Collection,
  68. Dict,
  69. List,
  70. Mapping,
  71. Optional,
  72. Tuple,
  73. Union,
  74. cast,
  75. )
  76. import attr
  77. from synapse.api.constants import MAIN_TIMELINE, ReceiptTypes
  78. from synapse.metrics.background_process_metrics import wrap_as_background_process
  79. from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause
  80. from synapse.storage.database import (
  81. DatabasePool,
  82. LoggingDatabaseConnection,
  83. LoggingTransaction,
  84. PostgresEngine,
  85. )
  86. from synapse.storage.databases.main.receipts import ReceiptsWorkerStore
  87. from synapse.storage.databases.main.stream import StreamWorkerStore
  88. from synapse.types import JsonDict
  89. from synapse.util import json_encoder
  90. from synapse.util.caches.descriptors import cached
  91. if TYPE_CHECKING:
  92. from synapse.server import HomeServer
  93. logger = logging.getLogger(__name__)
  94. DEFAULT_NOTIF_ACTION: List[Union[dict, str]] = [
  95. "notify",
  96. {"set_tweak": "highlight", "value": False},
  97. ]
  98. DEFAULT_HIGHLIGHT_ACTION: List[Union[dict, str]] = [
  99. "notify",
  100. {"set_tweak": "sound", "value": "default"},
  101. {"set_tweak": "highlight"},
  102. ]
  103. @attr.s(slots=True, auto_attribs=True)
  104. class _RoomReceipt:
  105. """
  106. HttpPushAction instances include the information used to generate HTTP
  107. requests to a push gateway.
  108. """
  109. unthreaded_stream_ordering: int = 0
  110. # threaded_stream_ordering includes the main pseudo-thread.
  111. threaded_stream_ordering: Dict[str, int] = attr.Factory(dict)
  112. def is_unread(self, thread_id: str, stream_ordering: int) -> bool:
  113. """Returns True if the stream ordering is unread according to the receipt information."""
  114. # Only include push actions with a stream ordering after both the unthreaded
  115. # and threaded receipt. Properly handles a user without any receipts present.
  116. return (
  117. self.unthreaded_stream_ordering < stream_ordering
  118. and self.threaded_stream_ordering.get(thread_id, 0) < stream_ordering
  119. )
  120. # A _RoomReceipt with no receipts in it.
  121. MISSING_ROOM_RECEIPT = _RoomReceipt()
  122. @attr.s(slots=True, frozen=True, auto_attribs=True)
  123. class HttpPushAction:
  124. """
  125. HttpPushAction instances include the information used to generate HTTP
  126. requests to a push gateway.
  127. """
  128. event_id: str
  129. room_id: str
  130. stream_ordering: int
  131. actions: List[Union[dict, str]]
  132. @attr.s(slots=True, frozen=True, auto_attribs=True)
  133. class EmailPushAction(HttpPushAction):
  134. """
  135. EmailPushAction instances include the information used to render an email
  136. push notification.
  137. """
  138. received_ts: Optional[int]
  139. @attr.s(slots=True, frozen=True, auto_attribs=True)
  140. class UserPushAction(EmailPushAction):
  141. """
  142. UserPushAction instances include the necessary information to respond to
  143. /notifications requests.
  144. """
  145. topological_ordering: int
  146. highlight: bool
  147. profile_tag: str
  148. # TODO This is used as a cached value and is mutable.
  149. @attr.s(slots=True, auto_attribs=True)
  150. class NotifCounts:
  151. """
  152. The per-user, per-room, per-thread count of notifications. Used by sync and push.
  153. """
  154. notify_count: int = 0
  155. unread_count: int = 0
  156. highlight_count: int = 0
  157. @attr.s(slots=True, frozen=True, auto_attribs=True)
  158. class RoomNotifCounts:
  159. """
  160. The per-user, per-room count of notifications. Used by sync and push.
  161. """
  162. main_timeline: NotifCounts
  163. # Map of thread ID to the notification counts.
  164. threads: Mapping[str, NotifCounts]
  165. @staticmethod
  166. def empty() -> "RoomNotifCounts":
  167. return _EMPTY_ROOM_NOTIF_COUNTS
  168. def __len__(self) -> int:
  169. # To properly account for the amount of space in any caches.
  170. return len(self.threads) + 1
  171. _EMPTY_ROOM_NOTIF_COUNTS = RoomNotifCounts(NotifCounts(), {})
  172. def _serialize_action(
  173. actions: Collection[Union[Mapping, str]], is_highlight: bool
  174. ) -> str:
  175. """Custom serializer for actions. This allows us to "compress" common actions.
  176. We use the fact that most users have the same actions for notifs (and for
  177. highlights).
  178. We store these default actions as the empty string rather than the full JSON.
  179. Since the empty string isn't valid JSON there is no risk of this clashing with
  180. any real JSON actions
  181. """
  182. if is_highlight:
  183. if actions == DEFAULT_HIGHLIGHT_ACTION:
  184. return "" # We use empty string as the column is non-NULL
  185. else:
  186. if actions == DEFAULT_NOTIF_ACTION:
  187. return ""
  188. return json_encoder.encode(actions)
  189. def _deserialize_action(actions: str, is_highlight: bool) -> List[Union[dict, str]]:
  190. """Custom deserializer for actions. This allows us to "compress" common actions"""
  191. if actions:
  192. return db_to_json(actions)
  193. if is_highlight:
  194. return DEFAULT_HIGHLIGHT_ACTION
  195. else:
  196. return DEFAULT_NOTIF_ACTION
  197. class EventPushActionsWorkerStore(ReceiptsWorkerStore, StreamWorkerStore, SQLBaseStore):
  198. def __init__(
  199. self,
  200. database: DatabasePool,
  201. db_conn: LoggingDatabaseConnection,
  202. hs: "HomeServer",
  203. ):
  204. super().__init__(database, db_conn, hs)
  205. # Track when the process started.
  206. self._started_ts = self._clock.time_msec()
  207. # These get correctly set by _find_stream_orderings_for_times_txn
  208. self.stream_ordering_month_ago: Optional[int] = None
  209. self.stream_ordering_day_ago: Optional[int] = None
  210. cur = db_conn.cursor(txn_name="_find_stream_orderings_for_times_txn")
  211. self._find_stream_orderings_for_times_txn(cur)
  212. cur.close()
  213. self.find_stream_orderings_looping_call = self._clock.looping_call(
  214. self._find_stream_orderings_for_times, 10 * 60 * 1000
  215. )
  216. self._rotate_count = 10000
  217. self._doing_notif_rotation = False
  218. if hs.config.worker.run_background_tasks:
  219. self._rotate_notif_loop = self._clock.looping_call(
  220. self._rotate_notifs, 30 * 1000
  221. )
  222. self._clear_old_staging_loop = self._clock.looping_call(
  223. self._clear_old_push_actions_staging, 30 * 60 * 1000
  224. )
  225. self.db_pool.updates.register_background_index_update(
  226. "event_push_summary_unique_index2",
  227. index_name="event_push_summary_unique_index2",
  228. table="event_push_summary",
  229. columns=["user_id", "room_id", "thread_id"],
  230. unique=True,
  231. )
  232. self.db_pool.updates.register_background_validate_constraint(
  233. "event_push_actions_staging_thread_id",
  234. constraint_name="event_push_actions_staging_thread_id",
  235. table="event_push_actions_staging",
  236. )
  237. self.db_pool.updates.register_background_validate_constraint(
  238. "event_push_actions_thread_id",
  239. constraint_name="event_push_actions_thread_id",
  240. table="event_push_actions",
  241. )
  242. self.db_pool.updates.register_background_validate_constraint(
  243. "event_push_summary_thread_id",
  244. constraint_name="event_push_summary_thread_id",
  245. table="event_push_summary",
  246. )
  247. self.db_pool.updates.register_background_update_handler(
  248. "event_push_drop_null_thread_id_indexes",
  249. self._background_drop_null_thread_id_indexes,
  250. )
  251. async def _background_drop_null_thread_id_indexes(
  252. self, progress: JsonDict, batch_size: int
  253. ) -> int:
  254. """
  255. Drop the indexes used to find null thread_ids for event_push_actions and
  256. event_push_summary.
  257. """
  258. def drop_null_thread_id_indexes_txn(txn: LoggingTransaction) -> None:
  259. sql = "DROP INDEX IF EXISTS event_push_actions_thread_id_null"
  260. logger.debug("[SQL] %s", sql)
  261. txn.execute(sql)
  262. sql = "DROP INDEX IF EXISTS event_push_summary_thread_id_null"
  263. logger.debug("[SQL] %s", sql)
  264. txn.execute(sql)
  265. await self.db_pool.runInteraction(
  266. "drop_null_thread_id_indexes_txn",
  267. drop_null_thread_id_indexes_txn,
  268. )
  269. await self.db_pool.updates._end_background_update(
  270. "event_push_drop_null_thread_id_indexes"
  271. )
  272. return 0
  273. async def get_unread_counts_by_room_for_user(self, user_id: str) -> Dict[str, int]:
  274. """Get the notification count by room for a user. Only considers notifications,
  275. not highlight or unread counts, and threads are currently aggregated under their room.
  276. This function is intentionally not cached because it is called to calculate the
  277. unread badge for push notifications and thus the result is expected to change.
  278. Note that this function assumes the user is a member of the room. Because
  279. summary rows are not removed when a user leaves a room, the caller must
  280. filter out those results from the result.
  281. Returns:
  282. A map of room ID to notification counts for the given user.
  283. """
  284. return await self.db_pool.runInteraction(
  285. "get_unread_counts_by_room_for_user",
  286. self._get_unread_counts_by_room_for_user_txn,
  287. user_id,
  288. )
  289. def _get_unread_counts_by_room_for_user_txn(
  290. self, txn: LoggingTransaction, user_id: str
  291. ) -> Dict[str, int]:
  292. receipt_types_clause, args = make_in_list_sql_clause(
  293. self.database_engine,
  294. "receipt_type",
  295. (ReceiptTypes.READ, ReceiptTypes.READ_PRIVATE),
  296. )
  297. args.extend([user_id, user_id])
  298. receipts_cte = f"""
  299. WITH all_receipts AS (
  300. SELECT room_id, thread_id, MAX(event_stream_ordering) AS max_receipt_stream_ordering
  301. FROM receipts_linearized
  302. LEFT JOIN events USING (room_id, event_id)
  303. WHERE
  304. {receipt_types_clause}
  305. AND user_id = ?
  306. GROUP BY room_id, thread_id
  307. )
  308. """
  309. receipts_joins = """
  310. LEFT JOIN (
  311. SELECT room_id, thread_id,
  312. max_receipt_stream_ordering AS threaded_receipt_stream_ordering
  313. FROM all_receipts
  314. WHERE thread_id IS NOT NULL
  315. ) AS threaded_receipts USING (room_id, thread_id)
  316. LEFT JOIN (
  317. SELECT room_id, thread_id,
  318. max_receipt_stream_ordering AS unthreaded_receipt_stream_ordering
  319. FROM all_receipts
  320. WHERE thread_id IS NULL
  321. ) AS unthreaded_receipts USING (room_id)
  322. """
  323. # First get summary counts by room / thread for the user. We use the max receipt
  324. # stream ordering of both threaded & unthreaded receipts to compare against the
  325. # summary table.
  326. #
  327. # PostgreSQL and SQLite differ in comparing scalar numerics.
  328. if isinstance(self.database_engine, PostgresEngine):
  329. # GREATEST ignores NULLs.
  330. max_clause = """GREATEST(
  331. threaded_receipt_stream_ordering,
  332. unthreaded_receipt_stream_ordering
  333. )"""
  334. else:
  335. # MAX returns NULL if any are NULL, so COALESCE to 0 first.
  336. max_clause = """MAX(
  337. COALESCE(threaded_receipt_stream_ordering, 0),
  338. COALESCE(unthreaded_receipt_stream_ordering, 0)
  339. )"""
  340. sql = f"""
  341. {receipts_cte}
  342. SELECT eps.room_id, eps.thread_id, notif_count
  343. FROM event_push_summary AS eps
  344. {receipts_joins}
  345. WHERE user_id = ?
  346. AND notif_count != 0
  347. AND (
  348. (last_receipt_stream_ordering IS NULL AND stream_ordering > {max_clause})
  349. OR last_receipt_stream_ordering = {max_clause}
  350. )
  351. """
  352. txn.execute(sql, args)
  353. seen_thread_ids = set()
  354. room_to_count: Dict[str, int] = defaultdict(int)
  355. for room_id, thread_id, notif_count in txn:
  356. room_to_count[room_id] += notif_count
  357. seen_thread_ids.add(thread_id)
  358. # Now get any event push actions that haven't been rotated using the same OR
  359. # join and filter by receipt and event push summary rotated up to stream ordering.
  360. sql = f"""
  361. {receipts_cte}
  362. SELECT epa.room_id, epa.thread_id, COUNT(CASE WHEN epa.notif = 1 THEN 1 END) AS notif_count
  363. FROM event_push_actions AS epa
  364. {receipts_joins}
  365. WHERE user_id = ?
  366. AND epa.notif = 1
  367. AND stream_ordering > (SELECT stream_ordering FROM event_push_summary_stream_ordering)
  368. AND (threaded_receipt_stream_ordering IS NULL OR stream_ordering > threaded_receipt_stream_ordering)
  369. AND (unthreaded_receipt_stream_ordering IS NULL OR stream_ordering > unthreaded_receipt_stream_ordering)
  370. GROUP BY epa.room_id, epa.thread_id
  371. """
  372. txn.execute(sql, args)
  373. for room_id, thread_id, notif_count in txn:
  374. # Note: only count push actions we have valid summaries for with up to date receipt.
  375. if thread_id not in seen_thread_ids:
  376. continue
  377. room_to_count[room_id] += notif_count
  378. thread_id_clause, thread_ids_args = make_in_list_sql_clause(
  379. self.database_engine, "epa.thread_id", seen_thread_ids
  380. )
  381. # Finally re-check event_push_actions for any rooms not in the summary, ignoring
  382. # the rotated up-to position. This handles the case where a read receipt has arrived
  383. # but not been rotated meaning the summary table is out of date, so we go back to
  384. # the push actions table.
  385. sql = f"""
  386. {receipts_cte}
  387. SELECT epa.room_id, COUNT(CASE WHEN epa.notif = 1 THEN 1 END) AS notif_count
  388. FROM event_push_actions AS epa
  389. {receipts_joins}
  390. WHERE user_id = ?
  391. AND NOT {thread_id_clause}
  392. AND epa.notif = 1
  393. AND (threaded_receipt_stream_ordering IS NULL OR stream_ordering > threaded_receipt_stream_ordering)
  394. AND (unthreaded_receipt_stream_ordering IS NULL OR stream_ordering > unthreaded_receipt_stream_ordering)
  395. GROUP BY epa.room_id
  396. """
  397. args.extend(thread_ids_args)
  398. txn.execute(sql, args)
  399. for room_id, notif_count in txn:
  400. room_to_count[room_id] += notif_count
  401. return room_to_count
  402. @cached(tree=True, max_entries=5000, iterable=True) # type: ignore[synapse-@cached-mutable]
  403. async def get_unread_event_push_actions_by_room_for_user(
  404. self,
  405. room_id: str,
  406. user_id: str,
  407. ) -> RoomNotifCounts:
  408. """Get the notification count, the highlight count and the unread message count
  409. for a given user in a given room after their latest read receipt.
  410. Note that this function assumes the user to be a current member of the room,
  411. since it's either called by the sync handler to handle joined room entries, or by
  412. the HTTP pusher to calculate the badge of unread joined rooms.
  413. Args:
  414. room_id: The room to retrieve the counts in.
  415. user_id: The user to retrieve the counts for.
  416. Returns
  417. A RoomNotifCounts object containing the notification count, the
  418. highlight count and the unread message count for both the main timeline
  419. and threads.
  420. """
  421. return await self.db_pool.runInteraction(
  422. "get_unread_event_push_actions_by_room",
  423. self._get_unread_counts_by_receipt_txn,
  424. room_id,
  425. user_id,
  426. )
  427. def _get_unread_counts_by_receipt_txn(
  428. self,
  429. txn: LoggingTransaction,
  430. room_id: str,
  431. user_id: str,
  432. ) -> RoomNotifCounts:
  433. # Get the stream ordering of the user's latest receipt in the room.
  434. result = self.get_last_unthreaded_receipt_for_user_txn(
  435. txn,
  436. user_id,
  437. room_id,
  438. receipt_types=(ReceiptTypes.READ, ReceiptTypes.READ_PRIVATE),
  439. )
  440. if result:
  441. _, stream_ordering = result
  442. else:
  443. # If the user has no receipts in the room, retrieve the stream ordering for
  444. # the latest membership event from this user in this room (which we assume is
  445. # a join).
  446. event_id = self.db_pool.simple_select_one_onecol_txn(
  447. txn=txn,
  448. table="local_current_membership",
  449. keyvalues={"room_id": room_id, "user_id": user_id},
  450. retcol="event_id",
  451. )
  452. stream_ordering = self.get_stream_id_for_event_txn(txn, event_id)
  453. return self._get_unread_counts_by_pos_txn(
  454. txn, room_id, user_id, stream_ordering
  455. )
  456. def _get_unread_counts_by_pos_txn(
  457. self,
  458. txn: LoggingTransaction,
  459. room_id: str,
  460. user_id: str,
  461. unthreaded_receipt_stream_ordering: int,
  462. ) -> RoomNotifCounts:
  463. """Get the number of unread messages for a user/room that have happened
  464. since the given stream ordering.
  465. Args:
  466. txn: The database transaction.
  467. room_id: The room ID to get unread counts for.
  468. user_id: The user ID to get unread counts for.
  469. unthreaded_receipt_stream_ordering: The stream ordering of the user's latest
  470. unthreaded receipt in the room. If there are no unthreaded receipts,
  471. the stream ordering of the user's join event.
  472. Returns:
  473. A RoomNotifCounts object containing the notification count, the
  474. highlight count and the unread message count for both the main timeline
  475. and threads.
  476. """
  477. main_counts = NotifCounts()
  478. thread_counts: Dict[str, NotifCounts] = {}
  479. def _get_thread(thread_id: str) -> NotifCounts:
  480. if thread_id == MAIN_TIMELINE:
  481. return main_counts
  482. return thread_counts.setdefault(thread_id, NotifCounts())
  483. receipt_types_clause, receipts_args = make_in_list_sql_clause(
  484. self.database_engine,
  485. "receipt_type",
  486. (ReceiptTypes.READ, ReceiptTypes.READ_PRIVATE),
  487. )
  488. # First we pull the counts from the summary table.
  489. #
  490. # We check that `last_receipt_stream_ordering` matches the stream ordering of the
  491. # latest receipt for the thread (which may be either the unthreaded read receipt
  492. # or the threaded read receipt).
  493. #
  494. # If it doesn't match then a new read receipt has arrived and we haven't yet
  495. # updated the counts in `event_push_summary` to reflect that; in that case we
  496. # simply ignore `event_push_summary` counts.
  497. #
  498. # We then do a manual count of all the rows in the `event_push_actions` table
  499. # for any user/room/thread which did not have a valid summary found.
  500. #
  501. # If `last_receipt_stream_ordering` is null then that means it's up-to-date
  502. # (as the row was written by an older version of Synapse that
  503. # updated `event_push_summary` synchronously when persisting a new read
  504. # receipt).
  505. txn.execute(
  506. f"""
  507. SELECT notif_count, COALESCE(unread_count, 0), thread_id
  508. FROM event_push_summary
  509. LEFT JOIN (
  510. SELECT thread_id, MAX(stream_ordering) AS threaded_receipt_stream_ordering
  511. FROM receipts_linearized
  512. LEFT JOIN events USING (room_id, event_id)
  513. WHERE
  514. user_id = ?
  515. AND room_id = ?
  516. AND stream_ordering > ?
  517. AND {receipt_types_clause}
  518. GROUP BY thread_id
  519. ) AS receipts USING (thread_id)
  520. WHERE room_id = ? AND user_id = ?
  521. AND (
  522. (last_receipt_stream_ordering IS NULL AND stream_ordering > COALESCE(threaded_receipt_stream_ordering, ?))
  523. OR last_receipt_stream_ordering = COALESCE(threaded_receipt_stream_ordering, ?)
  524. ) AND (notif_count != 0 OR COALESCE(unread_count, 0) != 0)
  525. """,
  526. (
  527. user_id,
  528. room_id,
  529. unthreaded_receipt_stream_ordering,
  530. *receipts_args,
  531. room_id,
  532. user_id,
  533. unthreaded_receipt_stream_ordering,
  534. unthreaded_receipt_stream_ordering,
  535. ),
  536. )
  537. summarised_threads = set()
  538. for notif_count, unread_count, thread_id in txn:
  539. summarised_threads.add(thread_id)
  540. counts = _get_thread(thread_id)
  541. counts.notify_count += notif_count
  542. counts.unread_count += unread_count
  543. # Next we need to count highlights, which aren't summarised
  544. sql = f"""
  545. SELECT COUNT(*), thread_id FROM event_push_actions
  546. LEFT JOIN (
  547. SELECT thread_id, MAX(stream_ordering) AS threaded_receipt_stream_ordering
  548. FROM receipts_linearized
  549. LEFT JOIN events USING (room_id, event_id)
  550. WHERE
  551. user_id = ?
  552. AND room_id = ?
  553. AND stream_ordering > ?
  554. AND {receipt_types_clause}
  555. GROUP BY thread_id
  556. ) AS receipts USING (thread_id)
  557. WHERE user_id = ?
  558. AND room_id = ?
  559. AND stream_ordering > COALESCE(threaded_receipt_stream_ordering, ?)
  560. AND highlight = 1
  561. GROUP BY thread_id
  562. """
  563. txn.execute(
  564. sql,
  565. (
  566. user_id,
  567. room_id,
  568. unthreaded_receipt_stream_ordering,
  569. *receipts_args,
  570. user_id,
  571. room_id,
  572. unthreaded_receipt_stream_ordering,
  573. ),
  574. )
  575. for highlight_count, thread_id in txn:
  576. _get_thread(thread_id).highlight_count += highlight_count
  577. # For threads which were summarised we need to count actions since the last
  578. # rotation.
  579. thread_id_clause, thread_id_args = make_in_list_sql_clause(
  580. self.database_engine, "thread_id", summarised_threads
  581. )
  582. # The (inclusive) event stream ordering that was previously summarised.
  583. rotated_upto_stream_ordering = self.db_pool.simple_select_one_onecol_txn(
  584. txn,
  585. table="event_push_summary_stream_ordering",
  586. keyvalues={},
  587. retcol="stream_ordering",
  588. )
  589. unread_counts = self._get_notif_unread_count_for_user_room(
  590. txn, room_id, user_id, rotated_upto_stream_ordering
  591. )
  592. for notif_count, unread_count, thread_id in unread_counts:
  593. if thread_id not in summarised_threads:
  594. continue
  595. if thread_id == MAIN_TIMELINE:
  596. counts.notify_count += notif_count
  597. counts.unread_count += unread_count
  598. elif thread_id in thread_counts:
  599. thread_counts[thread_id].notify_count += notif_count
  600. thread_counts[thread_id].unread_count += unread_count
  601. else:
  602. # Previous thread summaries of 0 are discarded above.
  603. #
  604. # TODO If empty summaries are deleted this can be removed.
  605. thread_counts[thread_id] = NotifCounts(
  606. notify_count=notif_count,
  607. unread_count=unread_count,
  608. highlight_count=0,
  609. )
  610. # Finally we need to count push actions that aren't included in the
  611. # summary returned above. This might be due to recent events that haven't
  612. # been summarised yet or the summary is out of date due to a recent read
  613. # receipt.
  614. sql = f"""
  615. SELECT
  616. COUNT(CASE WHEN notif = 1 THEN 1 END),
  617. COUNT(CASE WHEN unread = 1 THEN 1 END),
  618. thread_id
  619. FROM event_push_actions
  620. LEFT JOIN (
  621. SELECT thread_id, MAX(stream_ordering) AS threaded_receipt_stream_ordering
  622. FROM receipts_linearized
  623. LEFT JOIN events USING (room_id, event_id)
  624. WHERE
  625. user_id = ?
  626. AND room_id = ?
  627. AND stream_ordering > ?
  628. AND {receipt_types_clause}
  629. GROUP BY thread_id
  630. ) AS receipts USING (thread_id)
  631. WHERE user_id = ?
  632. AND room_id = ?
  633. AND stream_ordering > COALESCE(threaded_receipt_stream_ordering, ?)
  634. AND NOT {thread_id_clause}
  635. GROUP BY thread_id
  636. """
  637. txn.execute(
  638. sql,
  639. (
  640. user_id,
  641. room_id,
  642. unthreaded_receipt_stream_ordering,
  643. *receipts_args,
  644. user_id,
  645. room_id,
  646. unthreaded_receipt_stream_ordering,
  647. *thread_id_args,
  648. ),
  649. )
  650. for notif_count, unread_count, thread_id in txn:
  651. counts = _get_thread(thread_id)
  652. counts.notify_count += notif_count
  653. counts.unread_count += unread_count
  654. return RoomNotifCounts(main_counts, thread_counts)
  655. def _get_notif_unread_count_for_user_room(
  656. self,
  657. txn: LoggingTransaction,
  658. room_id: str,
  659. user_id: str,
  660. stream_ordering: int,
  661. max_stream_ordering: Optional[int] = None,
  662. thread_id: Optional[str] = None,
  663. ) -> List[Tuple[int, int, str]]:
  664. """Returns the notify and unread counts from `event_push_actions` for
  665. the given user/room in the given range.
  666. Does not consult `event_push_summary` table, which may include push
  667. actions that have been deleted from `event_push_actions` table.
  668. Args:
  669. txn: The database transaction.
  670. room_id: The room ID to get unread counts for.
  671. user_id: The user ID to get unread counts for.
  672. stream_ordering: The (exclusive) minimum stream ordering to consider.
  673. max_stream_ordering: The (inclusive) maximum stream ordering to consider.
  674. If this is not given, then no maximum is applied.
  675. thread_id: The thread ID to fetch unread counts for. If this is not provided
  676. then the results for *all* threads is returned.
  677. Note that if this is provided the resulting list will only have 0 or
  678. 1 tuples in it.
  679. Return:
  680. A tuple of the notif count and unread count in the given range for
  681. each thread.
  682. """
  683. # If there have been no events in the room since the stream ordering,
  684. # there can't be any push actions either.
  685. if not self._events_stream_cache.has_entity_changed(room_id, stream_ordering):
  686. return []
  687. stream_ordering_clause = ""
  688. args = [user_id, room_id, stream_ordering]
  689. if max_stream_ordering is not None:
  690. stream_ordering_clause = "AND ea.stream_ordering <= ?"
  691. args.append(max_stream_ordering)
  692. # If the max stream ordering is less than the min stream ordering,
  693. # then obviously there are zero push actions in that range.
  694. if max_stream_ordering <= stream_ordering:
  695. return []
  696. # Either limit the results to a specific thread or fetch all threads.
  697. thread_id_clause = ""
  698. if thread_id is not None:
  699. thread_id_clause = "AND thread_id = ?"
  700. args.append(thread_id)
  701. sql = f"""
  702. SELECT
  703. COUNT(CASE WHEN notif = 1 THEN 1 END),
  704. COUNT(CASE WHEN unread = 1 THEN 1 END),
  705. thread_id
  706. FROM event_push_actions ea
  707. WHERE user_id = ?
  708. AND room_id = ?
  709. AND ea.stream_ordering > ?
  710. {stream_ordering_clause}
  711. {thread_id_clause}
  712. GROUP BY thread_id
  713. """
  714. txn.execute(sql, args)
  715. return cast(List[Tuple[int, int, str]], txn.fetchall())
  716. async def get_push_action_users_in_range(
  717. self, min_stream_ordering: int, max_stream_ordering: int
  718. ) -> List[str]:
  719. def f(txn: LoggingTransaction) -> List[str]:
  720. sql = (
  721. "SELECT DISTINCT(user_id) FROM event_push_actions WHERE"
  722. " stream_ordering >= ? AND stream_ordering <= ? AND notif = 1"
  723. )
  724. txn.execute(sql, (min_stream_ordering, max_stream_ordering))
  725. return [r[0] for r in txn]
  726. return await self.db_pool.runInteraction("get_push_action_users_in_range", f)
  727. def _get_receipts_by_room_txn(
  728. self, txn: LoggingTransaction, user_id: str
  729. ) -> Dict[str, _RoomReceipt]:
  730. """
  731. Generate a map of room ID to the latest stream ordering that has been
  732. read by the given user.
  733. Args:
  734. txn:
  735. user_id: The user to fetch receipts for.
  736. Returns:
  737. A map including all rooms the user is in with a receipt. It maps
  738. room IDs to _RoomReceipt instances
  739. """
  740. receipt_types_clause, args = make_in_list_sql_clause(
  741. self.database_engine,
  742. "receipt_type",
  743. (ReceiptTypes.READ, ReceiptTypes.READ_PRIVATE),
  744. )
  745. sql = f"""
  746. SELECT room_id, thread_id, MAX(stream_ordering)
  747. FROM receipts_linearized
  748. INNER JOIN events USING (room_id, event_id)
  749. WHERE {receipt_types_clause}
  750. AND user_id = ?
  751. GROUP BY room_id, thread_id
  752. """
  753. args.extend((user_id,))
  754. txn.execute(sql, args)
  755. result: Dict[str, _RoomReceipt] = {}
  756. for room_id, thread_id, stream_ordering in txn:
  757. room_receipt = result.setdefault(room_id, _RoomReceipt())
  758. if thread_id is None:
  759. room_receipt.unthreaded_stream_ordering = stream_ordering
  760. else:
  761. room_receipt.threaded_stream_ordering[thread_id] = stream_ordering
  762. return result
  763. async def get_unread_push_actions_for_user_in_range_for_http(
  764. self,
  765. user_id: str,
  766. min_stream_ordering: int,
  767. max_stream_ordering: int,
  768. limit: int = 20,
  769. ) -> List[HttpPushAction]:
  770. """Get a list of the most recent unread push actions for a given user,
  771. within the given stream ordering range. Called by the httppusher.
  772. Args:
  773. user_id: The user to fetch push actions for.
  774. min_stream_ordering: The exclusive lower bound on the
  775. stream ordering of event push actions to fetch.
  776. max_stream_ordering: The inclusive upper bound on the
  777. stream ordering of event push actions to fetch.
  778. limit: The maximum number of rows to return.
  779. Returns:
  780. A list of dicts with the keys "event_id", "room_id", "stream_ordering", "actions".
  781. The list will be ordered by ascending stream_ordering.
  782. The list will have between 0~limit entries.
  783. """
  784. receipts_by_room = await self.db_pool.runInteraction(
  785. "get_unread_push_actions_for_user_in_range_http_receipts",
  786. self._get_receipts_by_room_txn,
  787. user_id=user_id,
  788. )
  789. def get_push_actions_txn(
  790. txn: LoggingTransaction,
  791. ) -> List[Tuple[str, str, str, int, str, bool]]:
  792. sql = """
  793. SELECT ep.event_id, ep.room_id, ep.thread_id, ep.stream_ordering,
  794. ep.actions, ep.highlight
  795. FROM event_push_actions AS ep
  796. WHERE
  797. ep.user_id = ?
  798. AND ep.stream_ordering > ?
  799. AND ep.stream_ordering <= ?
  800. AND ep.notif = 1
  801. ORDER BY ep.stream_ordering ASC LIMIT ?
  802. """
  803. txn.execute(sql, (user_id, min_stream_ordering, max_stream_ordering, limit))
  804. return cast(List[Tuple[str, str, str, int, str, bool]], txn.fetchall())
  805. push_actions = await self.db_pool.runInteraction(
  806. "get_unread_push_actions_for_user_in_range_http", get_push_actions_txn
  807. )
  808. notifs = [
  809. HttpPushAction(
  810. event_id=event_id,
  811. room_id=room_id,
  812. stream_ordering=stream_ordering,
  813. actions=_deserialize_action(actions, highlight),
  814. )
  815. for event_id, room_id, thread_id, stream_ordering, actions, highlight in push_actions
  816. if receipts_by_room.get(room_id, MISSING_ROOM_RECEIPT).is_unread(
  817. thread_id, stream_ordering
  818. )
  819. ]
  820. # Now sort it so it's ordered correctly, since currently it will
  821. # contain results from the first query, correctly ordered, followed
  822. # by results from the second query, but we want them all ordered
  823. # by stream_ordering, oldest first.
  824. notifs.sort(key=lambda r: r.stream_ordering)
  825. # Take only up to the limit. We have to stop at the limit because
  826. # one of the subqueries may have hit the limit.
  827. return notifs[:limit]
  828. async def get_unread_push_actions_for_user_in_range_for_email(
  829. self,
  830. user_id: str,
  831. min_stream_ordering: int,
  832. max_stream_ordering: int,
  833. limit: int = 20,
  834. ) -> List[EmailPushAction]:
  835. """Get a list of the most recent unread push actions for a given user,
  836. within the given stream ordering range. Called by the emailpusher
  837. Args:
  838. user_id: The user to fetch push actions for.
  839. min_stream_ordering: The exclusive lower bound on the
  840. stream ordering of event push actions to fetch.
  841. max_stream_ordering: The inclusive upper bound on the
  842. stream ordering of event push actions to fetch.
  843. limit: The maximum number of rows to return.
  844. Returns:
  845. A list of dicts with the keys "event_id", "room_id", "stream_ordering", "actions", "received_ts".
  846. The list will be ordered by descending received_ts.
  847. The list will have between 0~limit entries.
  848. """
  849. receipts_by_room = await self.db_pool.runInteraction(
  850. "get_unread_push_actions_for_user_in_range_email_receipts",
  851. self._get_receipts_by_room_txn,
  852. user_id=user_id,
  853. )
  854. def get_push_actions_txn(
  855. txn: LoggingTransaction,
  856. ) -> List[Tuple[str, str, str, int, str, bool, int]]:
  857. sql = """
  858. SELECT ep.event_id, ep.room_id, ep.thread_id, ep.stream_ordering,
  859. ep.actions, ep.highlight, e.received_ts
  860. FROM event_push_actions AS ep
  861. INNER JOIN events AS e USING (room_id, event_id)
  862. WHERE
  863. ep.user_id = ?
  864. AND ep.stream_ordering > ?
  865. AND ep.stream_ordering <= ?
  866. AND ep.notif = 1
  867. ORDER BY ep.stream_ordering DESC LIMIT ?
  868. """
  869. txn.execute(sql, (user_id, min_stream_ordering, max_stream_ordering, limit))
  870. return cast(List[Tuple[str, str, str, int, str, bool, int]], txn.fetchall())
  871. push_actions = await self.db_pool.runInteraction(
  872. "get_unread_push_actions_for_user_in_range_email", get_push_actions_txn
  873. )
  874. # Make a list of dicts from the two sets of results.
  875. notifs = [
  876. EmailPushAction(
  877. event_id=event_id,
  878. room_id=room_id,
  879. stream_ordering=stream_ordering,
  880. actions=_deserialize_action(actions, highlight),
  881. received_ts=received_ts,
  882. )
  883. for event_id, room_id, thread_id, stream_ordering, actions, highlight, received_ts in push_actions
  884. if receipts_by_room.get(room_id, MISSING_ROOM_RECEIPT).is_unread(
  885. thread_id, stream_ordering
  886. )
  887. ]
  888. # Now sort it so it's ordered correctly, since currently it will
  889. # contain results from the first query, correctly ordered, followed
  890. # by results from the second query, but we want them all ordered
  891. # by received_ts (most recent first)
  892. notifs.sort(key=lambda r: -(r.received_ts or 0))
  893. # Now return the first `limit`
  894. return notifs[:limit]
  895. async def get_if_maybe_push_in_range_for_user(
  896. self, user_id: str, min_stream_ordering: int
  897. ) -> bool:
  898. """A fast check to see if there might be something to push for the
  899. user since the given stream ordering. May return false positives.
  900. Useful to know whether to bother starting a pusher on start up or not.
  901. Args:
  902. user_id
  903. min_stream_ordering
  904. Returns:
  905. True if there may be push to process, False if there definitely isn't.
  906. """
  907. def _get_if_maybe_push_in_range_for_user_txn(txn: LoggingTransaction) -> bool:
  908. sql = """
  909. SELECT 1 FROM event_push_actions
  910. WHERE user_id = ? AND stream_ordering > ? AND notif = 1
  911. LIMIT 1
  912. """
  913. txn.execute(sql, (user_id, min_stream_ordering))
  914. return bool(txn.fetchone())
  915. return await self.db_pool.runInteraction(
  916. "get_if_maybe_push_in_range_for_user",
  917. _get_if_maybe_push_in_range_for_user_txn,
  918. )
  919. async def add_push_actions_to_staging(
  920. self,
  921. event_id: str,
  922. user_id_actions: Dict[str, Collection[Union[Mapping, str]]],
  923. count_as_unread: bool,
  924. thread_id: str,
  925. ) -> None:
  926. """Add the push actions for the event to the push action staging area.
  927. Args:
  928. event_id
  929. user_id_actions: A mapping of user_id to list of push actions, where
  930. an action can either be a string or dict.
  931. count_as_unread: Whether this event should increment unread counts.
  932. thread_id: The thread this event is parent of, if applicable.
  933. """
  934. if not user_id_actions:
  935. return
  936. # This is a helper function for generating the necessary tuple that
  937. # can be used to insert into the `event_push_actions_staging` table.
  938. def _gen_entry(
  939. user_id: str, actions: Collection[Union[Mapping, str]]
  940. ) -> Tuple[str, str, str, int, int, int, str, int]:
  941. is_highlight = 1 if _action_has_highlight(actions) else 0
  942. notif = 1 if "notify" in actions else 0
  943. return (
  944. event_id, # event_id column
  945. user_id, # user_id column
  946. _serialize_action(actions, bool(is_highlight)), # actions column
  947. notif, # notif column
  948. is_highlight, # highlight column
  949. int(count_as_unread), # unread column
  950. thread_id, # thread_id column
  951. self._clock.time_msec(), # inserted_ts column
  952. )
  953. await self.db_pool.simple_insert_many(
  954. "event_push_actions_staging",
  955. keys=(
  956. "event_id",
  957. "user_id",
  958. "actions",
  959. "notif",
  960. "highlight",
  961. "unread",
  962. "thread_id",
  963. "inserted_ts",
  964. ),
  965. values=[
  966. _gen_entry(user_id, actions)
  967. for user_id, actions in user_id_actions.items()
  968. ],
  969. desc="add_push_actions_to_staging",
  970. )
  971. async def remove_push_actions_from_staging(self, event_id: str) -> None:
  972. """Called if we failed to persist the event to ensure that stale push
  973. actions don't build up in the DB
  974. """
  975. try:
  976. await self.db_pool.simple_delete(
  977. table="event_push_actions_staging",
  978. keyvalues={"event_id": event_id},
  979. desc="remove_push_actions_from_staging",
  980. )
  981. except Exception:
  982. # this method is called from an exception handler, so propagating
  983. # another exception here really isn't helpful - there's nothing
  984. # the caller can do about it. Just log the exception and move on.
  985. logger.exception(
  986. "Error removing push actions after event persistence failure"
  987. )
  988. @wrap_as_background_process("event_push_action_stream_orderings")
  989. async def _find_stream_orderings_for_times(self) -> None:
  990. await self.db_pool.runInteraction(
  991. "_find_stream_orderings_for_times",
  992. self._find_stream_orderings_for_times_txn,
  993. )
  994. def _find_stream_orderings_for_times_txn(self, txn: LoggingTransaction) -> None:
  995. logger.info("Searching for stream ordering 1 month ago")
  996. self.stream_ordering_month_ago = self._find_first_stream_ordering_after_ts_txn(
  997. txn, self._clock.time_msec() - 30 * 24 * 60 * 60 * 1000
  998. )
  999. logger.info(
  1000. "Found stream ordering 1 month ago: it's %d", self.stream_ordering_month_ago
  1001. )
  1002. logger.info("Searching for stream ordering 1 day ago")
  1003. self.stream_ordering_day_ago = self._find_first_stream_ordering_after_ts_txn(
  1004. txn, self._clock.time_msec() - 24 * 60 * 60 * 1000
  1005. )
  1006. logger.info(
  1007. "Found stream ordering 1 day ago: it's %d", self.stream_ordering_day_ago
  1008. )
  1009. async def find_first_stream_ordering_after_ts(self, ts: int) -> int:
  1010. """Gets the stream ordering corresponding to a given timestamp.
  1011. Specifically, finds the stream_ordering of the first event that was
  1012. received on or after the timestamp. This is done by a binary search on
  1013. the events table, since there is no index on received_ts, so is
  1014. relatively slow.
  1015. Args:
  1016. ts: timestamp in millis
  1017. Returns:
  1018. stream ordering of the first event received on/after the timestamp
  1019. """
  1020. return await self.db_pool.runInteraction(
  1021. "_find_first_stream_ordering_after_ts_txn",
  1022. self._find_first_stream_ordering_after_ts_txn,
  1023. ts,
  1024. )
  1025. @staticmethod
  1026. def _find_first_stream_ordering_after_ts_txn(
  1027. txn: LoggingTransaction, ts: int
  1028. ) -> int:
  1029. """
  1030. Find the stream_ordering of the first event that was received on or
  1031. after a given timestamp. This is relatively slow as there is no index
  1032. on received_ts but we can then use this to delete push actions before
  1033. this.
  1034. received_ts must necessarily be in the same order as stream_ordering
  1035. and stream_ordering is indexed, so we manually binary search using
  1036. stream_ordering
  1037. Args:
  1038. txn:
  1039. ts: timestamp to search for
  1040. Returns:
  1041. The stream ordering
  1042. """
  1043. txn.execute("SELECT MAX(stream_ordering) FROM events")
  1044. max_stream_ordering = cast(Tuple[Optional[int]], txn.fetchone())[0]
  1045. if max_stream_ordering is None:
  1046. return 0
  1047. # We want the first stream_ordering in which received_ts is greater
  1048. # than or equal to ts. Call this point X.
  1049. #
  1050. # We maintain the invariants:
  1051. #
  1052. # range_start <= X <= range_end
  1053. #
  1054. range_start = 0
  1055. range_end = max_stream_ordering + 1
  1056. # Given a stream_ordering, look up the timestamp at that
  1057. # stream_ordering.
  1058. #
  1059. # The array may be sparse (we may be missing some stream_orderings).
  1060. # We treat the gaps as the same as having the same value as the
  1061. # preceding entry, because we will pick the lowest stream_ordering
  1062. # which satisfies our requirement of received_ts >= ts.
  1063. #
  1064. # For example, if our array of events indexed by stream_ordering is
  1065. # [10, <none>, 20], we should treat this as being equivalent to
  1066. # [10, 10, 20].
  1067. #
  1068. sql = """
  1069. SELECT received_ts FROM events
  1070. WHERE stream_ordering <= ?
  1071. ORDER BY stream_ordering DESC
  1072. LIMIT 1
  1073. """
  1074. while range_end - range_start > 0:
  1075. middle = (range_end + range_start) // 2
  1076. txn.execute(sql, (middle,))
  1077. row = txn.fetchone()
  1078. if row is None:
  1079. # no rows with stream_ordering<=middle
  1080. range_start = middle + 1
  1081. continue
  1082. middle_ts = row[0]
  1083. if ts > middle_ts:
  1084. # we got a timestamp lower than the one we were looking for.
  1085. # definitely need to look higher: X > middle.
  1086. range_start = middle + 1
  1087. else:
  1088. # we got a timestamp higher than (or the same as) the one we
  1089. # were looking for. We aren't yet sure about the point we
  1090. # looked up, but we can be sure that X <= middle.
  1091. range_end = middle
  1092. return range_end
  1093. async def get_time_of_last_push_action_before(
  1094. self, stream_ordering: int
  1095. ) -> Optional[int]:
  1096. def f(txn: LoggingTransaction) -> Optional[Tuple[int]]:
  1097. sql = """
  1098. SELECT e.received_ts
  1099. FROM event_push_actions AS ep
  1100. JOIN events e ON ep.room_id = e.room_id AND ep.event_id = e.event_id
  1101. WHERE ep.stream_ordering > ? AND notif = 1
  1102. ORDER BY ep.stream_ordering ASC
  1103. LIMIT 1
  1104. """
  1105. txn.execute(sql, (stream_ordering,))
  1106. return cast(Optional[Tuple[int]], txn.fetchone())
  1107. result = await self.db_pool.runInteraction(
  1108. "get_time_of_last_push_action_before", f
  1109. )
  1110. return result[0] if result else None
  1111. @wrap_as_background_process("rotate_notifs")
  1112. async def _rotate_notifs(self) -> None:
  1113. if self._doing_notif_rotation or self.stream_ordering_day_ago is None:
  1114. return
  1115. self._doing_notif_rotation = True
  1116. try:
  1117. # First we recalculate push summaries and delete stale push actions
  1118. # for rooms/users with new receipts.
  1119. while True:
  1120. logger.debug("Handling new receipts")
  1121. caught_up = await self.db_pool.runInteraction(
  1122. "_handle_new_receipts_for_notifs_txn",
  1123. self._handle_new_receipts_for_notifs_txn,
  1124. )
  1125. if caught_up:
  1126. break
  1127. # Then we update the event push summaries for any new events
  1128. while True:
  1129. logger.info("Rotating notifications")
  1130. caught_up = await self.db_pool.runInteraction(
  1131. "_rotate_notifs", self._rotate_notifs_txn
  1132. )
  1133. if caught_up:
  1134. break
  1135. # Finally we clear out old event push actions.
  1136. await self._remove_old_push_actions_that_have_rotated()
  1137. finally:
  1138. self._doing_notif_rotation = False
  1139. def _handle_new_receipts_for_notifs_txn(self, txn: LoggingTransaction) -> bool:
  1140. """Check for new read receipts and delete from event push actions.
  1141. Any push actions which predate the user's most recent read receipt are
  1142. now redundant, so we can remove them from `event_push_actions` and
  1143. update `event_push_summary`.
  1144. Returns true if all new receipts have been processed.
  1145. """
  1146. limit = 100
  1147. # The (inclusive) receipt stream ID that was previously processed..
  1148. min_receipts_stream_id = self.db_pool.simple_select_one_onecol_txn(
  1149. txn,
  1150. table="event_push_summary_last_receipt_stream_id",
  1151. keyvalues={},
  1152. retcol="stream_id",
  1153. )
  1154. max_receipts_stream_id = self._receipts_id_gen.get_current_token()
  1155. # The (inclusive) event stream ordering that was previously summarised.
  1156. old_rotate_stream_ordering = self.db_pool.simple_select_one_onecol_txn(
  1157. txn,
  1158. table="event_push_summary_stream_ordering",
  1159. keyvalues={},
  1160. retcol="stream_ordering",
  1161. )
  1162. sql = """
  1163. SELECT r.stream_id, r.room_id, r.user_id, r.thread_id, e.stream_ordering
  1164. FROM receipts_linearized AS r
  1165. INNER JOIN events AS e USING (event_id)
  1166. WHERE ? < r.stream_id AND r.stream_id <= ? AND user_id LIKE ?
  1167. ORDER BY r.stream_id ASC
  1168. LIMIT ?
  1169. """
  1170. # We only want local users, so we add a dodgy filter to the above query
  1171. # and recheck it below.
  1172. user_filter = "%:" + self.hs.hostname
  1173. txn.execute(
  1174. sql,
  1175. (
  1176. min_receipts_stream_id,
  1177. max_receipts_stream_id,
  1178. user_filter,
  1179. limit,
  1180. ),
  1181. )
  1182. rows = cast(List[Tuple[int, str, str, Optional[str], int]], txn.fetchall())
  1183. # For each new read receipt we delete push actions from before it and
  1184. # recalculate the summary.
  1185. #
  1186. # Care must be taken of whether it is a threaded or unthreaded receipt.
  1187. for _, room_id, user_id, thread_id, stream_ordering in rows:
  1188. # Only handle our own read receipts.
  1189. if not self.hs.is_mine_id(user_id):
  1190. continue
  1191. thread_clause = ""
  1192. thread_args: Tuple = ()
  1193. if thread_id is not None:
  1194. thread_clause = "AND thread_id = ?"
  1195. thread_args = (thread_id,)
  1196. # For each new read receipt we delete push actions from before it and
  1197. # recalculate the summary.
  1198. txn.execute(
  1199. f"""
  1200. DELETE FROM event_push_actions
  1201. WHERE room_id = ?
  1202. AND user_id = ?
  1203. AND stream_ordering <= ?
  1204. AND highlight = 0
  1205. {thread_clause}
  1206. """,
  1207. (room_id, user_id, stream_ordering, *thread_args),
  1208. )
  1209. # Fetch the notification counts between the stream ordering of the
  1210. # latest receipt and what was previously summarised.
  1211. unread_counts = self._get_notif_unread_count_for_user_room(
  1212. txn,
  1213. room_id,
  1214. user_id,
  1215. stream_ordering,
  1216. old_rotate_stream_ordering,
  1217. thread_id,
  1218. )
  1219. # For an unthreaded receipt, mark the summary for all threads in the room
  1220. # as cleared.
  1221. if thread_id is None:
  1222. self.db_pool.simple_update_txn(
  1223. txn,
  1224. table="event_push_summary",
  1225. keyvalues={"user_id": user_id, "room_id": room_id},
  1226. updatevalues={
  1227. "notif_count": 0,
  1228. "unread_count": 0,
  1229. "stream_ordering": old_rotate_stream_ordering,
  1230. "last_receipt_stream_ordering": stream_ordering,
  1231. },
  1232. )
  1233. # For a threaded receipt, we *always* want to update that receipt,
  1234. # event if there are no new notifications in that thread. This ensures
  1235. # the stream_ordering & last_receipt_stream_ordering are updated.
  1236. elif not unread_counts:
  1237. unread_counts = [(0, 0, thread_id)]
  1238. # Then any updated threads get their notification count and unread
  1239. # count updated.
  1240. self.db_pool.simple_update_many_txn(
  1241. txn,
  1242. table="event_push_summary",
  1243. key_names=("room_id", "user_id", "thread_id"),
  1244. key_values=[(room_id, user_id, row[2]) for row in unread_counts],
  1245. value_names=(
  1246. "notif_count",
  1247. "unread_count",
  1248. "stream_ordering",
  1249. "last_receipt_stream_ordering",
  1250. ),
  1251. value_values=[
  1252. (row[0], row[1], old_rotate_stream_ordering, stream_ordering)
  1253. for row in unread_counts
  1254. ],
  1255. )
  1256. # We always update `event_push_summary_last_receipt_stream_id` to
  1257. # ensure that we don't rescan the same receipts for remote users.
  1258. receipts_last_processed_stream_id = max_receipts_stream_id
  1259. if len(rows) >= limit:
  1260. # If we pulled out a limited number of rows we only update the
  1261. # position to the last receipt we processed, so we continue
  1262. # processing the rest next iteration.
  1263. receipts_last_processed_stream_id = rows[-1][0]
  1264. self.db_pool.simple_update_txn(
  1265. txn,
  1266. table="event_push_summary_last_receipt_stream_id",
  1267. keyvalues={},
  1268. updatevalues={"stream_id": receipts_last_processed_stream_id},
  1269. )
  1270. return len(rows) < limit
  1271. def _rotate_notifs_txn(self, txn: LoggingTransaction) -> bool:
  1272. """Archives older notifications (from event_push_actions) into event_push_summary.
  1273. Returns whether the archiving process has caught up or not.
  1274. """
  1275. # The (inclusive) event stream ordering that was previously summarised.
  1276. old_rotate_stream_ordering = self.db_pool.simple_select_one_onecol_txn(
  1277. txn,
  1278. table="event_push_summary_stream_ordering",
  1279. keyvalues={},
  1280. retcol="stream_ordering",
  1281. )
  1282. # We don't to try and rotate millions of rows at once, so we cap the
  1283. # maximum stream ordering we'll rotate before.
  1284. txn.execute(
  1285. """
  1286. SELECT stream_ordering FROM event_push_actions
  1287. WHERE stream_ordering > ?
  1288. ORDER BY stream_ordering ASC LIMIT 1 OFFSET ?
  1289. """,
  1290. (old_rotate_stream_ordering, self._rotate_count),
  1291. )
  1292. stream_row = txn.fetchone()
  1293. if stream_row:
  1294. (offset_stream_ordering,) = stream_row
  1295. # We need to bound by the current token to ensure that we handle
  1296. # out-of-order writes correctly.
  1297. rotate_to_stream_ordering = min(
  1298. offset_stream_ordering, self._stream_id_gen.get_current_token()
  1299. )
  1300. caught_up = False
  1301. else:
  1302. rotate_to_stream_ordering = self._stream_id_gen.get_current_token()
  1303. caught_up = True
  1304. logger.info("Rotating notifications up to: %s", rotate_to_stream_ordering)
  1305. self._rotate_notifs_before_txn(
  1306. txn, old_rotate_stream_ordering, rotate_to_stream_ordering
  1307. )
  1308. return caught_up
  1309. def _rotate_notifs_before_txn(
  1310. self,
  1311. txn: LoggingTransaction,
  1312. old_rotate_stream_ordering: int,
  1313. rotate_to_stream_ordering: int,
  1314. ) -> None:
  1315. """Archives older notifications (from event_push_actions) into event_push_summary.
  1316. Any event_push_actions between old_rotate_stream_ordering (exclusive) and
  1317. rotate_to_stream_ordering (inclusive) will be added to the event_push_summary
  1318. table.
  1319. Args:
  1320. txn: The database transaction.
  1321. old_rotate_stream_ordering: The previous maximum event stream ordering.
  1322. rotate_to_stream_ordering: The new maximum event stream ordering to summarise.
  1323. """
  1324. # Calculate the new counts that should be upserted into event_push_summary
  1325. sql = """
  1326. SELECT user_id, room_id, thread_id,
  1327. coalesce(old.%s, 0) + upd.cnt,
  1328. upd.stream_ordering
  1329. FROM (
  1330. SELECT user_id, room_id, thread_id, count(*) as cnt,
  1331. max(ea.stream_ordering) as stream_ordering
  1332. FROM event_push_actions AS ea
  1333. LEFT JOIN event_push_summary AS old USING (user_id, room_id, thread_id)
  1334. WHERE ? < ea.stream_ordering AND ea.stream_ordering <= ?
  1335. AND (
  1336. old.last_receipt_stream_ordering IS NULL
  1337. OR old.last_receipt_stream_ordering < ea.stream_ordering
  1338. )
  1339. AND %s = 1
  1340. GROUP BY user_id, room_id, thread_id
  1341. ) AS upd
  1342. LEFT JOIN event_push_summary AS old USING (user_id, room_id, thread_id)
  1343. """
  1344. # First get the count of unread messages.
  1345. txn.execute(
  1346. sql % ("unread_count", "unread"),
  1347. (old_rotate_stream_ordering, rotate_to_stream_ordering),
  1348. )
  1349. # We need to merge results from the two requests (the one that retrieves the
  1350. # unread count and the one that retrieves the notifications count) into a single
  1351. # object because we might not have the same amount of rows in each of them. To do
  1352. # this, we use a dict indexed on the user ID and room ID to make it easier to
  1353. # populate.
  1354. summaries: Dict[Tuple[str, str, str], _EventPushSummary] = {}
  1355. for row in txn:
  1356. summaries[(row[0], row[1], row[2])] = _EventPushSummary(
  1357. unread_count=row[3],
  1358. stream_ordering=row[4],
  1359. notif_count=0,
  1360. )
  1361. # Then get the count of notifications.
  1362. txn.execute(
  1363. sql % ("notif_count", "notif"),
  1364. (old_rotate_stream_ordering, rotate_to_stream_ordering),
  1365. )
  1366. for row in txn:
  1367. if (row[0], row[1], row[2]) in summaries:
  1368. summaries[(row[0], row[1], row[2])].notif_count = row[3]
  1369. else:
  1370. # Because the rules on notifying are different than the rules on marking
  1371. # a message unread, we might end up with messages that notify but aren't
  1372. # marked unread, so we might not have a summary for this (user, room)
  1373. # tuple to complete.
  1374. summaries[(row[0], row[1], row[2])] = _EventPushSummary(
  1375. unread_count=0,
  1376. stream_ordering=row[4],
  1377. notif_count=row[3],
  1378. )
  1379. logger.info("Rotating notifications, handling %d rows", len(summaries))
  1380. self.db_pool.simple_upsert_many_txn(
  1381. txn,
  1382. table="event_push_summary",
  1383. key_names=("user_id", "room_id", "thread_id"),
  1384. key_values=list(summaries),
  1385. value_names=("notif_count", "unread_count", "stream_ordering"),
  1386. value_values=[
  1387. (
  1388. summary.notif_count,
  1389. summary.unread_count,
  1390. summary.stream_ordering,
  1391. )
  1392. for summary in summaries.values()
  1393. ],
  1394. )
  1395. txn.execute(
  1396. "UPDATE event_push_summary_stream_ordering SET stream_ordering = ?",
  1397. (rotate_to_stream_ordering,),
  1398. )
  1399. async def _remove_old_push_actions_that_have_rotated(self) -> None:
  1400. """
  1401. Clear out old push actions that have been summarised (and are older than
  1402. 1 day ago).
  1403. """
  1404. # We want to clear out anything that is older than a day that *has* already
  1405. # been rotated.
  1406. rotated_upto_stream_ordering = await self.db_pool.simple_select_one_onecol(
  1407. table="event_push_summary_stream_ordering",
  1408. keyvalues={},
  1409. retcol="stream_ordering",
  1410. )
  1411. max_stream_ordering_to_delete = min(
  1412. rotated_upto_stream_ordering, self.stream_ordering_day_ago
  1413. )
  1414. def remove_old_push_actions_that_have_rotated_txn(
  1415. txn: LoggingTransaction,
  1416. ) -> bool:
  1417. # We don't want to clear out too much at a time, so we bound our
  1418. # deletes.
  1419. batch_size = self._rotate_count
  1420. if isinstance(self.database_engine, PostgresEngine):
  1421. # Temporarily disable sequential scans in this transaction. We
  1422. # need to do this as the postgres statistics don't take into
  1423. # account the `highlight = 0` part when estimating the
  1424. # distribution of `stream_ordering`. I.e. since we keep old
  1425. # highlight rows the query planner thinks there are way more old
  1426. # rows to delete than there actually are.
  1427. txn.execute("SET LOCAL enable_seqscan=off")
  1428. txn.execute(
  1429. """
  1430. SELECT stream_ordering FROM event_push_actions
  1431. WHERE stream_ordering <= ? AND highlight = 0
  1432. ORDER BY stream_ordering ASC LIMIT 1 OFFSET ?
  1433. """,
  1434. (
  1435. max_stream_ordering_to_delete,
  1436. batch_size,
  1437. ),
  1438. )
  1439. stream_row = txn.fetchone()
  1440. if stream_row:
  1441. (stream_ordering,) = stream_row
  1442. else:
  1443. stream_ordering = max_stream_ordering_to_delete
  1444. # We need to use a inclusive bound here to handle the case where a
  1445. # single stream ordering has more than `batch_size` rows.
  1446. txn.execute(
  1447. """
  1448. DELETE FROM event_push_actions
  1449. WHERE stream_ordering <= ? AND highlight = 0
  1450. """,
  1451. (stream_ordering,),
  1452. )
  1453. logger.info("Rotating notifications, deleted %s push actions", txn.rowcount)
  1454. return txn.rowcount < batch_size
  1455. while True:
  1456. done = await self.db_pool.runInteraction(
  1457. "_remove_old_push_actions_that_have_rotated",
  1458. remove_old_push_actions_that_have_rotated_txn,
  1459. )
  1460. if done:
  1461. break
  1462. @wrap_as_background_process("_clear_old_push_actions_staging")
  1463. async def _clear_old_push_actions_staging(self) -> None:
  1464. """Clear out any old event push actions from the staging table for
  1465. events that we failed to persist.
  1466. """
  1467. # We delete anything more than an hour old, on the assumption that we'll
  1468. # never take more than an hour to persist an event.
  1469. delete_before_ts = self._clock.time_msec() - 60 * 60 * 1000
  1470. if self._started_ts > delete_before_ts:
  1471. # We need to wait for at least an hour before we started deleting,
  1472. # so that we know it's safe to delete rows with NULL `inserted_ts`.
  1473. return
  1474. # We don't have an index on `inserted_ts`, instead we assume that the
  1475. # number of "live" rows in `event_push_actions_staging` is small enough
  1476. # that an infrequent periodic scan won't cause a problem.
  1477. #
  1478. # Note: we also delete any columns with NULL `inserted_ts`, this is safe
  1479. # as we added a default value to new rows and so they must be at least
  1480. # an hour old.
  1481. limit = 1000
  1482. sql = """
  1483. DELETE FROM event_push_actions_staging WHERE event_id IN (
  1484. SELECT event_id FROM event_push_actions_staging WHERE
  1485. inserted_ts < ? OR inserted_ts IS NULL
  1486. LIMIT ?
  1487. )
  1488. """
  1489. def _clear_old_push_actions_staging_txn(txn: LoggingTransaction) -> bool:
  1490. txn.execute(sql, (delete_before_ts, limit))
  1491. return txn.rowcount >= limit
  1492. while True:
  1493. # Returns true if we have more stuff to delete from the table.
  1494. deleted = await self.db_pool.runInteraction(
  1495. "_clear_old_push_actions_staging", _clear_old_push_actions_staging_txn
  1496. )
  1497. if not deleted:
  1498. return
  1499. # We sleep to ensure that we don't overwhelm the DB.
  1500. await self._clock.sleep(1.0)
  1501. async def get_push_actions_for_user(
  1502. self,
  1503. user_id: str,
  1504. before: Optional[str] = None,
  1505. limit: int = 50,
  1506. only_highlight: bool = False,
  1507. ) -> List[UserPushAction]:
  1508. def f(
  1509. txn: LoggingTransaction,
  1510. ) -> List[Tuple[str, str, int, int, str, bool, str, int]]:
  1511. before_clause = ""
  1512. if before:
  1513. before_clause = "AND epa.stream_ordering < ?"
  1514. args = [user_id, before, limit]
  1515. else:
  1516. args = [user_id, limit]
  1517. if only_highlight:
  1518. if len(before_clause) > 0:
  1519. before_clause += " "
  1520. before_clause += "AND epa.highlight = 1"
  1521. # NB. This assumes event_ids are globally unique since
  1522. # it makes the query easier to index
  1523. sql = """
  1524. SELECT epa.event_id, epa.room_id,
  1525. epa.stream_ordering, epa.topological_ordering,
  1526. epa.actions, epa.highlight, epa.profile_tag, e.received_ts
  1527. FROM event_push_actions epa, events e
  1528. WHERE epa.event_id = e.event_id
  1529. AND epa.user_id = ? %s
  1530. AND epa.notif = 1
  1531. ORDER BY epa.stream_ordering DESC
  1532. LIMIT ?
  1533. """ % (
  1534. before_clause,
  1535. )
  1536. txn.execute(sql, args)
  1537. return cast(
  1538. List[Tuple[str, str, int, int, str, bool, str, int]], txn.fetchall()
  1539. )
  1540. push_actions = await self.db_pool.runInteraction("get_push_actions_for_user", f)
  1541. return [
  1542. UserPushAction(
  1543. event_id=row[0],
  1544. room_id=row[1],
  1545. stream_ordering=row[2],
  1546. actions=_deserialize_action(row[4], row[5]),
  1547. received_ts=row[7],
  1548. topological_ordering=row[3],
  1549. highlight=row[5],
  1550. profile_tag=row[6],
  1551. )
  1552. for row in push_actions
  1553. ]
  1554. class EventPushActionsStore(EventPushActionsWorkerStore):
  1555. EPA_HIGHLIGHT_INDEX = "epa_highlight_index"
  1556. def __init__(
  1557. self,
  1558. database: DatabasePool,
  1559. db_conn: LoggingDatabaseConnection,
  1560. hs: "HomeServer",
  1561. ):
  1562. super().__init__(database, db_conn, hs)
  1563. self.db_pool.updates.register_background_index_update(
  1564. self.EPA_HIGHLIGHT_INDEX,
  1565. index_name="event_push_actions_u_highlight",
  1566. table="event_push_actions",
  1567. columns=["user_id", "stream_ordering"],
  1568. )
  1569. self.db_pool.updates.register_background_index_update(
  1570. "event_push_actions_highlights_index",
  1571. index_name="event_push_actions_highlights_index",
  1572. table="event_push_actions",
  1573. columns=["user_id", "room_id", "topological_ordering", "stream_ordering"],
  1574. where_clause="highlight=1",
  1575. )
  1576. # Add index to make deleting old push actions faster.
  1577. self.db_pool.updates.register_background_index_update(
  1578. "event_push_actions_stream_highlight_index",
  1579. index_name="event_push_actions_stream_highlight_index",
  1580. table="event_push_actions",
  1581. columns=["highlight", "stream_ordering"],
  1582. where_clause="highlight=0",
  1583. )
  1584. def _action_has_highlight(actions: Collection[Union[Mapping, str]]) -> bool:
  1585. for action in actions:
  1586. if not isinstance(action, dict):
  1587. continue
  1588. if action.get("set_tweak", None) == "highlight":
  1589. return action.get("value", True)
  1590. return False
  1591. @attr.s(slots=True, auto_attribs=True)
  1592. class _EventPushSummary:
  1593. """Summary of pending event push actions for a given user in a given room.
  1594. Used in _rotate_notifs_before_txn to manipulate results from event_push_actions.
  1595. """
  1596. unread_count: int
  1597. stream_ordering: int
  1598. notif_count: int