Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

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