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.
 
 
 
 
 
 

1463 lines
54 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 typing import (
  65. TYPE_CHECKING,
  66. Collection,
  67. Dict,
  68. List,
  69. Mapping,
  70. Optional,
  71. Tuple,
  72. Union,
  73. cast,
  74. )
  75. import attr
  76. from synapse.api.constants import ReceiptTypes
  77. from synapse.metrics.background_process_metrics import wrap_as_background_process
  78. from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause
  79. from synapse.storage.database import (
  80. DatabasePool,
  81. LoggingDatabaseConnection,
  82. LoggingTransaction,
  83. )
  84. from synapse.storage.databases.main.receipts import ReceiptsWorkerStore
  85. from synapse.storage.databases.main.stream import StreamWorkerStore
  86. from synapse.types import JsonDict
  87. from synapse.util import json_encoder
  88. from synapse.util.caches.descriptors import cached
  89. if TYPE_CHECKING:
  90. from synapse.server import HomeServer
  91. logger = logging.getLogger(__name__)
  92. DEFAULT_NOTIF_ACTION: List[Union[dict, str]] = [
  93. "notify",
  94. {"set_tweak": "highlight", "value": False},
  95. ]
  96. DEFAULT_HIGHLIGHT_ACTION: List[Union[dict, str]] = [
  97. "notify",
  98. {"set_tweak": "sound", "value": "default"},
  99. {"set_tweak": "highlight"},
  100. ]
  101. @attr.s(slots=True, frozen=True, auto_attribs=True)
  102. class HttpPushAction:
  103. """
  104. HttpPushAction instances include the information used to generate HTTP
  105. requests to a push gateway.
  106. """
  107. event_id: str
  108. room_id: str
  109. stream_ordering: int
  110. actions: List[Union[dict, str]]
  111. @attr.s(slots=True, frozen=True, auto_attribs=True)
  112. class EmailPushAction(HttpPushAction):
  113. """
  114. EmailPushAction instances include the information used to render an email
  115. push notification.
  116. """
  117. received_ts: Optional[int]
  118. @attr.s(slots=True, frozen=True, auto_attribs=True)
  119. class UserPushAction(EmailPushAction):
  120. """
  121. UserPushAction instances include the necessary information to respond to
  122. /notifications requests.
  123. """
  124. topological_ordering: int
  125. highlight: bool
  126. profile_tag: str
  127. @attr.s(slots=True, auto_attribs=True)
  128. class NotifCounts:
  129. """
  130. The per-user, per-room count of notifications. Used by sync and push.
  131. """
  132. notify_count: int = 0
  133. unread_count: int = 0
  134. highlight_count: int = 0
  135. def _serialize_action(
  136. actions: Collection[Union[Mapping, str]], is_highlight: bool
  137. ) -> str:
  138. """Custom serializer for actions. This allows us to "compress" common actions.
  139. We use the fact that most users have the same actions for notifs (and for
  140. highlights).
  141. We store these default actions as the empty string rather than the full JSON.
  142. Since the empty string isn't valid JSON there is no risk of this clashing with
  143. any real JSON actions
  144. """
  145. if is_highlight:
  146. if actions == DEFAULT_HIGHLIGHT_ACTION:
  147. return "" # We use empty string as the column is non-NULL
  148. else:
  149. if actions == DEFAULT_NOTIF_ACTION:
  150. return ""
  151. return json_encoder.encode(actions)
  152. def _deserialize_action(actions: str, is_highlight: bool) -> List[Union[dict, str]]:
  153. """Custom deserializer for actions. This allows us to "compress" common actions"""
  154. if actions:
  155. return db_to_json(actions)
  156. if is_highlight:
  157. return DEFAULT_HIGHLIGHT_ACTION
  158. else:
  159. return DEFAULT_NOTIF_ACTION
  160. class EventPushActionsWorkerStore(ReceiptsWorkerStore, StreamWorkerStore, SQLBaseStore):
  161. def __init__(
  162. self,
  163. database: DatabasePool,
  164. db_conn: LoggingDatabaseConnection,
  165. hs: "HomeServer",
  166. ):
  167. super().__init__(database, db_conn, hs)
  168. # These get correctly set by _find_stream_orderings_for_times_txn
  169. self.stream_ordering_month_ago: Optional[int] = None
  170. self.stream_ordering_day_ago: Optional[int] = None
  171. cur = db_conn.cursor(txn_name="_find_stream_orderings_for_times_txn")
  172. self._find_stream_orderings_for_times_txn(cur)
  173. cur.close()
  174. self.find_stream_orderings_looping_call = self._clock.looping_call(
  175. self._find_stream_orderings_for_times, 10 * 60 * 1000
  176. )
  177. self._rotate_count = 10000
  178. self._doing_notif_rotation = False
  179. if hs.config.worker.run_background_tasks:
  180. self._rotate_notif_loop = self._clock.looping_call(
  181. self._rotate_notifs, 30 * 1000
  182. )
  183. self.db_pool.updates.register_background_index_update(
  184. "event_push_summary_unique_index",
  185. index_name="event_push_summary_unique_index",
  186. table="event_push_summary",
  187. columns=["user_id", "room_id"],
  188. unique=True,
  189. replaces_index="event_push_summary_user_rm",
  190. )
  191. self.db_pool.updates.register_background_index_update(
  192. "event_push_summary_unique_index2",
  193. index_name="event_push_summary_unique_index2",
  194. table="event_push_summary",
  195. columns=["user_id", "room_id", "thread_id"],
  196. unique=True,
  197. )
  198. self.db_pool.updates.register_background_update_handler(
  199. "event_push_backfill_thread_id",
  200. self._background_backfill_thread_id,
  201. )
  202. async def _background_backfill_thread_id(
  203. self, progress: JsonDict, batch_size: int
  204. ) -> int:
  205. """
  206. Fill in the thread_id field for event_push_actions and event_push_summary.
  207. This is preparatory so that it can be made non-nullable in the future.
  208. Because all current (null) data is done in an unthreaded manner this
  209. simply assumes it is on the "main" timeline. Since event_push_actions
  210. are periodically cleared it is not possible to correctly re-calculate
  211. the thread_id.
  212. """
  213. event_push_actions_done = progress.get("event_push_actions_done", False)
  214. def add_thread_id_txn(
  215. txn: LoggingTransaction, table_name: str, start_stream_ordering: int
  216. ) -> int:
  217. sql = f"""
  218. SELECT stream_ordering
  219. FROM {table_name}
  220. WHERE
  221. thread_id IS NULL
  222. AND stream_ordering > ?
  223. ORDER BY stream_ordering
  224. LIMIT ?
  225. """
  226. txn.execute(sql, (start_stream_ordering, batch_size))
  227. # No more rows to process.
  228. rows = txn.fetchall()
  229. if not rows:
  230. progress[f"{table_name}_done"] = True
  231. self.db_pool.updates._background_update_progress_txn(
  232. txn, "event_push_backfill_thread_id", progress
  233. )
  234. return 0
  235. # Update the thread ID for any of those rows.
  236. max_stream_ordering = rows[-1][0]
  237. sql = f"""
  238. UPDATE {table_name}
  239. SET thread_id = 'main'
  240. WHERE stream_ordering <= ? AND thread_id IS NULL
  241. """
  242. txn.execute(sql, (max_stream_ordering,))
  243. # Update progress.
  244. processed_rows = txn.rowcount
  245. progress[f"max_{table_name}_stream_ordering"] = max_stream_ordering
  246. self.db_pool.updates._background_update_progress_txn(
  247. txn, "event_push_backfill_thread_id", progress
  248. )
  249. return processed_rows
  250. # First update the event_push_actions table, then the event_push_summary table.
  251. #
  252. # Note that the event_push_actions_staging table is ignored since it is
  253. # assumed that items in that table will only exist for a short period of
  254. # time.
  255. if not event_push_actions_done:
  256. result = await self.db_pool.runInteraction(
  257. "event_push_backfill_thread_id",
  258. add_thread_id_txn,
  259. "event_push_actions",
  260. progress.get("max_event_push_actions_stream_ordering", 0),
  261. )
  262. else:
  263. result = await self.db_pool.runInteraction(
  264. "event_push_backfill_thread_id",
  265. add_thread_id_txn,
  266. "event_push_summary",
  267. progress.get("max_event_push_summary_stream_ordering", 0),
  268. )
  269. # Only done after the event_push_summary table is done.
  270. if not result:
  271. await self.db_pool.updates._end_background_update(
  272. "event_push_backfill_thread_id"
  273. )
  274. return result
  275. @cached(tree=True, max_entries=5000)
  276. async def get_unread_event_push_actions_by_room_for_user(
  277. self,
  278. room_id: str,
  279. user_id: str,
  280. ) -> NotifCounts:
  281. """Get the notification count, the highlight count and the unread message count
  282. for a given user in a given room after their latest read receipt.
  283. Note that this function assumes the user to be a current member of the room,
  284. since it's either called by the sync handler to handle joined room entries, or by
  285. the HTTP pusher to calculate the badge of unread joined rooms.
  286. Args:
  287. room_id: The room to retrieve the counts in.
  288. user_id: The user to retrieve the counts for.
  289. Returns
  290. A NotifCounts object containing the notification count, the highlight count
  291. and the unread message count.
  292. """
  293. return await self.db_pool.runInteraction(
  294. "get_unread_event_push_actions_by_room",
  295. self._get_unread_counts_by_receipt_txn,
  296. room_id,
  297. user_id,
  298. )
  299. def _get_unread_counts_by_receipt_txn(
  300. self,
  301. txn: LoggingTransaction,
  302. room_id: str,
  303. user_id: str,
  304. ) -> NotifCounts:
  305. # Get the stream ordering of the user's latest receipt in the room.
  306. result = self.get_last_receipt_for_user_txn(
  307. txn,
  308. user_id,
  309. room_id,
  310. receipt_types=(
  311. ReceiptTypes.READ,
  312. ReceiptTypes.READ_PRIVATE,
  313. ),
  314. )
  315. if result:
  316. _, stream_ordering = result
  317. else:
  318. # If the user has no receipts in the room, retrieve the stream ordering for
  319. # the latest membership event from this user in this room (which we assume is
  320. # a join).
  321. event_id = self.db_pool.simple_select_one_onecol_txn(
  322. txn=txn,
  323. table="local_current_membership",
  324. keyvalues={"room_id": room_id, "user_id": user_id},
  325. retcol="event_id",
  326. )
  327. stream_ordering = self.get_stream_id_for_event_txn(txn, event_id)
  328. return self._get_unread_counts_by_pos_txn(
  329. txn, room_id, user_id, stream_ordering
  330. )
  331. def _get_unread_counts_by_pos_txn(
  332. self,
  333. txn: LoggingTransaction,
  334. room_id: str,
  335. user_id: str,
  336. receipt_stream_ordering: int,
  337. ) -> NotifCounts:
  338. """Get the number of unread messages for a user/room that have happened
  339. since the given stream ordering.
  340. Args:
  341. txn: The database transaction.
  342. room_id: The room ID to get unread counts for.
  343. user_id: The user ID to get unread counts for.
  344. receipt_stream_ordering: The stream ordering of the user's latest
  345. receipt in the room. If there are no receipts, the stream ordering
  346. of the user's join event.
  347. Returns
  348. A NotifCounts object containing the notification count, the highlight count
  349. and the unread message count.
  350. """
  351. counts = NotifCounts()
  352. # First we pull the counts from the summary table.
  353. #
  354. # We check that `last_receipt_stream_ordering` matches the stream
  355. # ordering given. If it doesn't match then a new read receipt has arrived and
  356. # we haven't yet updated the counts in `event_push_summary` to reflect
  357. # that; in that case we simply ignore `event_push_summary` counts
  358. # and do a manual count of all of the rows in the `event_push_actions` table
  359. # for this user/room.
  360. #
  361. # If `last_receipt_stream_ordering` is null then that means it's up to
  362. # date (as the row was written by an older version of Synapse that
  363. # updated `event_push_summary` synchronously when persisting a new read
  364. # receipt).
  365. txn.execute(
  366. """
  367. SELECT stream_ordering, notif_count, COALESCE(unread_count, 0)
  368. FROM event_push_summary
  369. WHERE room_id = ? AND user_id = ?
  370. AND (
  371. (last_receipt_stream_ordering IS NULL AND stream_ordering > ?)
  372. OR last_receipt_stream_ordering = ?
  373. )
  374. """,
  375. (room_id, user_id, receipt_stream_ordering, receipt_stream_ordering),
  376. )
  377. row = txn.fetchone()
  378. summary_stream_ordering = 0
  379. if row:
  380. summary_stream_ordering = row[0]
  381. counts.notify_count += row[1]
  382. counts.unread_count += row[2]
  383. # Next we need to count highlights, which aren't summarised
  384. sql = """
  385. SELECT COUNT(*) FROM event_push_actions
  386. WHERE user_id = ?
  387. AND room_id = ?
  388. AND stream_ordering > ?
  389. AND highlight = 1
  390. """
  391. txn.execute(sql, (user_id, room_id, receipt_stream_ordering))
  392. row = txn.fetchone()
  393. if row:
  394. counts.highlight_count += row[0]
  395. # Finally we need to count push actions that aren't included in the
  396. # summary returned above. This might be due to recent events that haven't
  397. # been summarised yet or the summary is out of date due to a recent read
  398. # receipt.
  399. start_unread_stream_ordering = max(
  400. receipt_stream_ordering, summary_stream_ordering
  401. )
  402. notify_count, unread_count = self._get_notif_unread_count_for_user_room(
  403. txn, room_id, user_id, start_unread_stream_ordering
  404. )
  405. counts.notify_count += notify_count
  406. counts.unread_count += unread_count
  407. return counts
  408. def _get_notif_unread_count_for_user_room(
  409. self,
  410. txn: LoggingTransaction,
  411. room_id: str,
  412. user_id: str,
  413. stream_ordering: int,
  414. max_stream_ordering: Optional[int] = None,
  415. ) -> Tuple[int, int]:
  416. """Returns the notify and unread counts from `event_push_actions` for
  417. the given user/room in the given range.
  418. Does not consult `event_push_summary` table, which may include push
  419. actions that have been deleted from `event_push_actions` table.
  420. Args:
  421. txn: The database transaction.
  422. room_id: The room ID to get unread counts for.
  423. user_id: The user ID to get unread counts for.
  424. stream_ordering: The (exclusive) minimum stream ordering to consider.
  425. max_stream_ordering: The (inclusive) maximum stream ordering to consider.
  426. If this is not given, then no maximum is applied.
  427. Return:
  428. A tuple of the notif count and unread count in the given range.
  429. """
  430. # If there have been no events in the room since the stream ordering,
  431. # there can't be any push actions either.
  432. if not self._events_stream_cache.has_entity_changed(room_id, stream_ordering):
  433. return 0, 0
  434. clause = ""
  435. args = [user_id, room_id, stream_ordering]
  436. if max_stream_ordering is not None:
  437. clause = "AND ea.stream_ordering <= ?"
  438. args.append(max_stream_ordering)
  439. # If the max stream ordering is less than the min stream ordering,
  440. # then obviously there are zero push actions in that range.
  441. if max_stream_ordering <= stream_ordering:
  442. return 0, 0
  443. sql = f"""
  444. SELECT
  445. COUNT(CASE WHEN notif = 1 THEN 1 END),
  446. COUNT(CASE WHEN unread = 1 THEN 1 END)
  447. FROM event_push_actions ea
  448. WHERE user_id = ?
  449. AND room_id = ?
  450. AND ea.stream_ordering > ?
  451. {clause}
  452. """
  453. txn.execute(sql, args)
  454. row = txn.fetchone()
  455. if row:
  456. return cast(Tuple[int, int], row)
  457. return 0, 0
  458. async def get_push_action_users_in_range(
  459. self, min_stream_ordering: int, max_stream_ordering: int
  460. ) -> List[str]:
  461. def f(txn: LoggingTransaction) -> List[str]:
  462. sql = (
  463. "SELECT DISTINCT(user_id) FROM event_push_actions WHERE"
  464. " stream_ordering >= ? AND stream_ordering <= ? AND notif = 1"
  465. )
  466. txn.execute(sql, (min_stream_ordering, max_stream_ordering))
  467. return [r[0] for r in txn]
  468. return await self.db_pool.runInteraction("get_push_action_users_in_range", f)
  469. def _get_receipts_by_room_txn(
  470. self, txn: LoggingTransaction, user_id: str
  471. ) -> Dict[str, int]:
  472. """
  473. Generate a map of room ID to the latest stream ordering that has been
  474. read by the given user.
  475. Args:
  476. txn:
  477. user_id: The user to fetch receipts for.
  478. Returns:
  479. A map of room ID to stream ordering for all rooms the user has a receipt in.
  480. """
  481. receipt_types_clause, args = make_in_list_sql_clause(
  482. self.database_engine,
  483. "receipt_type",
  484. (
  485. ReceiptTypes.READ,
  486. ReceiptTypes.READ_PRIVATE,
  487. ),
  488. )
  489. sql = f"""
  490. SELECT room_id, MAX(stream_ordering)
  491. FROM receipts_linearized
  492. INNER JOIN events USING (room_id, event_id)
  493. WHERE {receipt_types_clause}
  494. AND user_id = ?
  495. GROUP BY room_id
  496. """
  497. args.extend((user_id,))
  498. txn.execute(sql, args)
  499. return {
  500. room_id: latest_stream_ordering
  501. for room_id, latest_stream_ordering in txn.fetchall()
  502. }
  503. async def get_unread_push_actions_for_user_in_range_for_http(
  504. self,
  505. user_id: str,
  506. min_stream_ordering: int,
  507. max_stream_ordering: int,
  508. limit: int = 20,
  509. ) -> List[HttpPushAction]:
  510. """Get a list of the most recent unread push actions for a given user,
  511. within the given stream ordering range. Called by the httppusher.
  512. Args:
  513. user_id: The user to fetch push actions for.
  514. min_stream_ordering: The exclusive lower bound on the
  515. stream ordering of event push actions to fetch.
  516. max_stream_ordering: The inclusive upper bound on the
  517. stream ordering of event push actions to fetch.
  518. limit: The maximum number of rows to return.
  519. Returns:
  520. A list of dicts with the keys "event_id", "room_id", "stream_ordering", "actions".
  521. The list will be ordered by ascending stream_ordering.
  522. The list will have between 0~limit entries.
  523. """
  524. receipts_by_room = await self.db_pool.runInteraction(
  525. "get_unread_push_actions_for_user_in_range_http_receipts",
  526. self._get_receipts_by_room_txn,
  527. user_id=user_id,
  528. )
  529. def get_push_actions_txn(
  530. txn: LoggingTransaction,
  531. ) -> List[Tuple[str, str, int, str, bool]]:
  532. sql = """
  533. SELECT ep.event_id, ep.room_id, ep.stream_ordering, ep.actions, ep.highlight
  534. FROM event_push_actions AS ep
  535. WHERE
  536. ep.user_id = ?
  537. AND ep.stream_ordering > ?
  538. AND ep.stream_ordering <= ?
  539. AND ep.notif = 1
  540. ORDER BY ep.stream_ordering ASC LIMIT ?
  541. """
  542. txn.execute(sql, (user_id, min_stream_ordering, max_stream_ordering, limit))
  543. return cast(List[Tuple[str, str, int, str, bool]], txn.fetchall())
  544. push_actions = await self.db_pool.runInteraction(
  545. "get_unread_push_actions_for_user_in_range_http", get_push_actions_txn
  546. )
  547. notifs = [
  548. HttpPushAction(
  549. event_id=event_id,
  550. room_id=room_id,
  551. stream_ordering=stream_ordering,
  552. actions=_deserialize_action(actions, highlight),
  553. )
  554. for event_id, room_id, stream_ordering, actions, highlight in push_actions
  555. # Only include push actions with a stream ordering after any receipt, or without any
  556. # receipt present (invited to but never read rooms).
  557. if stream_ordering > receipts_by_room.get(room_id, 0)
  558. ]
  559. # Now sort it so it's ordered correctly, since currently it will
  560. # contain results from the first query, correctly ordered, followed
  561. # by results from the second query, but we want them all ordered
  562. # by stream_ordering, oldest first.
  563. notifs.sort(key=lambda r: r.stream_ordering)
  564. # Take only up to the limit. We have to stop at the limit because
  565. # one of the subqueries may have hit the limit.
  566. return notifs[:limit]
  567. async def get_unread_push_actions_for_user_in_range_for_email(
  568. self,
  569. user_id: str,
  570. min_stream_ordering: int,
  571. max_stream_ordering: int,
  572. limit: int = 20,
  573. ) -> List[EmailPushAction]:
  574. """Get a list of the most recent unread push actions for a given user,
  575. within the given stream ordering range. Called by the emailpusher
  576. Args:
  577. user_id: The user to fetch push actions for.
  578. min_stream_ordering: The exclusive lower bound on the
  579. stream ordering of event push actions to fetch.
  580. max_stream_ordering: The inclusive upper bound on the
  581. stream ordering of event push actions to fetch.
  582. limit: The maximum number of rows to return.
  583. Returns:
  584. A list of dicts with the keys "event_id", "room_id", "stream_ordering", "actions", "received_ts".
  585. The list will be ordered by descending received_ts.
  586. The list will have between 0~limit entries.
  587. """
  588. receipts_by_room = await self.db_pool.runInteraction(
  589. "get_unread_push_actions_for_user_in_range_email_receipts",
  590. self._get_receipts_by_room_txn,
  591. user_id=user_id,
  592. )
  593. def get_push_actions_txn(
  594. txn: LoggingTransaction,
  595. ) -> List[Tuple[str, str, int, str, bool, int]]:
  596. sql = """
  597. SELECT ep.event_id, ep.room_id, ep.stream_ordering, ep.actions,
  598. ep.highlight, e.received_ts
  599. FROM event_push_actions AS ep
  600. INNER JOIN events AS e USING (room_id, event_id)
  601. WHERE
  602. ep.user_id = ?
  603. AND ep.stream_ordering > ?
  604. AND ep.stream_ordering <= ?
  605. AND ep.notif = 1
  606. ORDER BY ep.stream_ordering DESC LIMIT ?
  607. """
  608. txn.execute(sql, (user_id, min_stream_ordering, max_stream_ordering, limit))
  609. return cast(List[Tuple[str, str, int, str, bool, int]], txn.fetchall())
  610. push_actions = await self.db_pool.runInteraction(
  611. "get_unread_push_actions_for_user_in_range_email", get_push_actions_txn
  612. )
  613. # Make a list of dicts from the two sets of results.
  614. notifs = [
  615. EmailPushAction(
  616. event_id=event_id,
  617. room_id=room_id,
  618. stream_ordering=stream_ordering,
  619. actions=_deserialize_action(actions, highlight),
  620. received_ts=received_ts,
  621. )
  622. for event_id, room_id, stream_ordering, actions, highlight, received_ts in push_actions
  623. # Only include push actions with a stream ordering after any receipt, or without any
  624. # receipt present (invited to but never read rooms).
  625. if stream_ordering > receipts_by_room.get(room_id, 0)
  626. ]
  627. # Now sort it so it's ordered correctly, since currently it will
  628. # contain results from the first query, correctly ordered, followed
  629. # by results from the second query, but we want them all ordered
  630. # by received_ts (most recent first)
  631. notifs.sort(key=lambda r: -(r.received_ts or 0))
  632. # Now return the first `limit`
  633. return notifs[:limit]
  634. async def get_if_maybe_push_in_range_for_user(
  635. self, user_id: str, min_stream_ordering: int
  636. ) -> bool:
  637. """A fast check to see if there might be something to push for the
  638. user since the given stream ordering. May return false positives.
  639. Useful to know whether to bother starting a pusher on start up or not.
  640. Args:
  641. user_id
  642. min_stream_ordering
  643. Returns:
  644. True if there may be push to process, False if there definitely isn't.
  645. """
  646. def _get_if_maybe_push_in_range_for_user_txn(txn: LoggingTransaction) -> bool:
  647. sql = """
  648. SELECT 1 FROM event_push_actions
  649. WHERE user_id = ? AND stream_ordering > ? AND notif = 1
  650. LIMIT 1
  651. """
  652. txn.execute(sql, (user_id, min_stream_ordering))
  653. return bool(txn.fetchone())
  654. return await self.db_pool.runInteraction(
  655. "get_if_maybe_push_in_range_for_user",
  656. _get_if_maybe_push_in_range_for_user_txn,
  657. )
  658. async def add_push_actions_to_staging(
  659. self,
  660. event_id: str,
  661. user_id_actions: Dict[str, Collection[Union[Mapping, str]]],
  662. count_as_unread: bool,
  663. thread_id: str,
  664. ) -> None:
  665. """Add the push actions for the event to the push action staging area.
  666. Args:
  667. event_id
  668. user_id_actions: A mapping of user_id to list of push actions, where
  669. an action can either be a string or dict.
  670. count_as_unread: Whether this event should increment unread counts.
  671. thread_id: The thread this event is parent of, if applicable.
  672. """
  673. if not user_id_actions:
  674. return
  675. # This is a helper function for generating the necessary tuple that
  676. # can be used to insert into the `event_push_actions_staging` table.
  677. def _gen_entry(
  678. user_id: str, actions: Collection[Union[Mapping, str]]
  679. ) -> Tuple[str, str, str, int, int, int, str]:
  680. is_highlight = 1 if _action_has_highlight(actions) else 0
  681. notif = 1 if "notify" in actions else 0
  682. return (
  683. event_id, # event_id column
  684. user_id, # user_id column
  685. _serialize_action(actions, bool(is_highlight)), # actions column
  686. notif, # notif column
  687. is_highlight, # highlight column
  688. int(count_as_unread), # unread column
  689. thread_id, # thread_id column
  690. )
  691. await self.db_pool.simple_insert_many(
  692. "event_push_actions_staging",
  693. keys=(
  694. "event_id",
  695. "user_id",
  696. "actions",
  697. "notif",
  698. "highlight",
  699. "unread",
  700. "thread_id",
  701. ),
  702. values=[
  703. _gen_entry(user_id, actions)
  704. for user_id, actions in user_id_actions.items()
  705. ],
  706. desc="add_push_actions_to_staging",
  707. )
  708. async def remove_push_actions_from_staging(self, event_id: str) -> None:
  709. """Called if we failed to persist the event to ensure that stale push
  710. actions don't build up in the DB
  711. """
  712. try:
  713. await self.db_pool.simple_delete(
  714. table="event_push_actions_staging",
  715. keyvalues={"event_id": event_id},
  716. desc="remove_push_actions_from_staging",
  717. )
  718. except Exception:
  719. # this method is called from an exception handler, so propagating
  720. # another exception here really isn't helpful - there's nothing
  721. # the caller can do about it. Just log the exception and move on.
  722. logger.exception(
  723. "Error removing push actions after event persistence failure"
  724. )
  725. @wrap_as_background_process("event_push_action_stream_orderings")
  726. async def _find_stream_orderings_for_times(self) -> None:
  727. await self.db_pool.runInteraction(
  728. "_find_stream_orderings_for_times",
  729. self._find_stream_orderings_for_times_txn,
  730. )
  731. def _find_stream_orderings_for_times_txn(self, txn: LoggingTransaction) -> None:
  732. logger.info("Searching for stream ordering 1 month ago")
  733. self.stream_ordering_month_ago = self._find_first_stream_ordering_after_ts_txn(
  734. txn, self._clock.time_msec() - 30 * 24 * 60 * 60 * 1000
  735. )
  736. logger.info(
  737. "Found stream ordering 1 month ago: it's %d", self.stream_ordering_month_ago
  738. )
  739. logger.info("Searching for stream ordering 1 day ago")
  740. self.stream_ordering_day_ago = self._find_first_stream_ordering_after_ts_txn(
  741. txn, self._clock.time_msec() - 24 * 60 * 60 * 1000
  742. )
  743. logger.info(
  744. "Found stream ordering 1 day ago: it's %d", self.stream_ordering_day_ago
  745. )
  746. async def find_first_stream_ordering_after_ts(self, ts: int) -> int:
  747. """Gets the stream ordering corresponding to a given timestamp.
  748. Specifically, finds the stream_ordering of the first event that was
  749. received on or after the timestamp. This is done by a binary search on
  750. the events table, since there is no index on received_ts, so is
  751. relatively slow.
  752. Args:
  753. ts: timestamp in millis
  754. Returns:
  755. stream ordering of the first event received on/after the timestamp
  756. """
  757. return await self.db_pool.runInteraction(
  758. "_find_first_stream_ordering_after_ts_txn",
  759. self._find_first_stream_ordering_after_ts_txn,
  760. ts,
  761. )
  762. @staticmethod
  763. def _find_first_stream_ordering_after_ts_txn(
  764. txn: LoggingTransaction, ts: int
  765. ) -> int:
  766. """
  767. Find the stream_ordering of the first event that was received on or
  768. after a given timestamp. This is relatively slow as there is no index
  769. on received_ts but we can then use this to delete push actions before
  770. this.
  771. received_ts must necessarily be in the same order as stream_ordering
  772. and stream_ordering is indexed, so we manually binary search using
  773. stream_ordering
  774. Args:
  775. txn:
  776. ts: timestamp to search for
  777. Returns:
  778. The stream ordering
  779. """
  780. txn.execute("SELECT MAX(stream_ordering) FROM events")
  781. max_stream_ordering = cast(Tuple[Optional[int]], txn.fetchone())[0]
  782. if max_stream_ordering is None:
  783. return 0
  784. # We want the first stream_ordering in which received_ts is greater
  785. # than or equal to ts. Call this point X.
  786. #
  787. # We maintain the invariants:
  788. #
  789. # range_start <= X <= range_end
  790. #
  791. range_start = 0
  792. range_end = max_stream_ordering + 1
  793. # Given a stream_ordering, look up the timestamp at that
  794. # stream_ordering.
  795. #
  796. # The array may be sparse (we may be missing some stream_orderings).
  797. # We treat the gaps as the same as having the same value as the
  798. # preceding entry, because we will pick the lowest stream_ordering
  799. # which satisfies our requirement of received_ts >= ts.
  800. #
  801. # For example, if our array of events indexed by stream_ordering is
  802. # [10, <none>, 20], we should treat this as being equivalent to
  803. # [10, 10, 20].
  804. #
  805. sql = """
  806. SELECT received_ts FROM events
  807. WHERE stream_ordering <= ?
  808. ORDER BY stream_ordering DESC
  809. LIMIT 1
  810. """
  811. while range_end - range_start > 0:
  812. middle = (range_end + range_start) // 2
  813. txn.execute(sql, (middle,))
  814. row = txn.fetchone()
  815. if row is None:
  816. # no rows with stream_ordering<=middle
  817. range_start = middle + 1
  818. continue
  819. middle_ts = row[0]
  820. if ts > middle_ts:
  821. # we got a timestamp lower than the one we were looking for.
  822. # definitely need to look higher: X > middle.
  823. range_start = middle + 1
  824. else:
  825. # we got a timestamp higher than (or the same as) the one we
  826. # were looking for. We aren't yet sure about the point we
  827. # looked up, but we can be sure that X <= middle.
  828. range_end = middle
  829. return range_end
  830. async def get_time_of_last_push_action_before(
  831. self, stream_ordering: int
  832. ) -> Optional[int]:
  833. def f(txn: LoggingTransaction) -> Optional[Tuple[int]]:
  834. sql = """
  835. SELECT e.received_ts
  836. FROM event_push_actions AS ep
  837. JOIN events e ON ep.room_id = e.room_id AND ep.event_id = e.event_id
  838. WHERE ep.stream_ordering > ? AND notif = 1
  839. ORDER BY ep.stream_ordering ASC
  840. LIMIT 1
  841. """
  842. txn.execute(sql, (stream_ordering,))
  843. return cast(Optional[Tuple[int]], txn.fetchone())
  844. result = await self.db_pool.runInteraction(
  845. "get_time_of_last_push_action_before", f
  846. )
  847. return result[0] if result else None
  848. @wrap_as_background_process("rotate_notifs")
  849. async def _rotate_notifs(self) -> None:
  850. if self._doing_notif_rotation or self.stream_ordering_day_ago is None:
  851. return
  852. self._doing_notif_rotation = True
  853. try:
  854. # First we recalculate push summaries and delete stale push actions
  855. # for rooms/users with new receipts.
  856. while True:
  857. logger.debug("Handling new receipts")
  858. caught_up = await self.db_pool.runInteraction(
  859. "_handle_new_receipts_for_notifs_txn",
  860. self._handle_new_receipts_for_notifs_txn,
  861. )
  862. if caught_up:
  863. break
  864. # Then we update the event push summaries for any new events
  865. while True:
  866. logger.info("Rotating notifications")
  867. caught_up = await self.db_pool.runInteraction(
  868. "_rotate_notifs", self._rotate_notifs_txn
  869. )
  870. if caught_up:
  871. break
  872. # Finally we clear out old event push actions.
  873. await self._remove_old_push_actions_that_have_rotated()
  874. finally:
  875. self._doing_notif_rotation = False
  876. def _handle_new_receipts_for_notifs_txn(self, txn: LoggingTransaction) -> bool:
  877. """Check for new read receipts and delete from event push actions.
  878. Any push actions which predate the user's most recent read receipt are
  879. now redundant, so we can remove them from `event_push_actions` and
  880. update `event_push_summary`.
  881. Returns true if all new receipts have been processed.
  882. """
  883. limit = 100
  884. # The (inclusive) receipt stream ID that was previously processed..
  885. min_receipts_stream_id = self.db_pool.simple_select_one_onecol_txn(
  886. txn,
  887. table="event_push_summary_last_receipt_stream_id",
  888. keyvalues={},
  889. retcol="stream_id",
  890. )
  891. max_receipts_stream_id = self._receipts_id_gen.get_current_token()
  892. # The (inclusive) event stream ordering that was previously summarised.
  893. old_rotate_stream_ordering = self.db_pool.simple_select_one_onecol_txn(
  894. txn,
  895. table="event_push_summary_stream_ordering",
  896. keyvalues={},
  897. retcol="stream_ordering",
  898. )
  899. sql = """
  900. SELECT r.stream_id, r.room_id, r.user_id, e.stream_ordering
  901. FROM receipts_linearized AS r
  902. INNER JOIN events AS e USING (event_id)
  903. WHERE ? < r.stream_id AND r.stream_id <= ? AND user_id LIKE ?
  904. ORDER BY r.stream_id ASC
  905. LIMIT ?
  906. """
  907. # We only want local users, so we add a dodgy filter to the above query
  908. # and recheck it below.
  909. user_filter = "%:" + self.hs.hostname
  910. txn.execute(
  911. sql,
  912. (
  913. min_receipts_stream_id,
  914. max_receipts_stream_id,
  915. user_filter,
  916. limit,
  917. ),
  918. )
  919. rows = txn.fetchall()
  920. # For each new read receipt we delete push actions from before it and
  921. # recalculate the summary.
  922. for _, room_id, user_id, stream_ordering in rows:
  923. # Only handle our own read receipts.
  924. if not self.hs.is_mine_id(user_id):
  925. continue
  926. txn.execute(
  927. """
  928. DELETE FROM event_push_actions
  929. WHERE room_id = ?
  930. AND user_id = ?
  931. AND stream_ordering <= ?
  932. AND highlight = 0
  933. """,
  934. (room_id, user_id, stream_ordering),
  935. )
  936. # Fetch the notification counts between the stream ordering of the
  937. # latest receipt and what was previously summarised.
  938. notif_count, unread_count = self._get_notif_unread_count_for_user_room(
  939. txn, room_id, user_id, stream_ordering, old_rotate_stream_ordering
  940. )
  941. # Replace the previous summary with the new counts.
  942. #
  943. # TODO(threads): Upsert per-thread instead of setting them all to main.
  944. self.db_pool.simple_upsert_txn(
  945. txn,
  946. table="event_push_summary",
  947. keyvalues={"room_id": room_id, "user_id": user_id},
  948. values={
  949. "notif_count": notif_count,
  950. "unread_count": unread_count,
  951. "stream_ordering": old_rotate_stream_ordering,
  952. "last_receipt_stream_ordering": stream_ordering,
  953. "thread_id": "main",
  954. },
  955. )
  956. # We always update `event_push_summary_last_receipt_stream_id` to
  957. # ensure that we don't rescan the same receipts for remote users.
  958. upper_limit = max_receipts_stream_id
  959. if len(rows) >= limit:
  960. # If we pulled out a limited number of rows we only update the
  961. # position to the last receipt we processed, so we continue
  962. # processing the rest next iteration.
  963. upper_limit = rows[-1][0]
  964. self.db_pool.simple_update_txn(
  965. txn,
  966. table="event_push_summary_last_receipt_stream_id",
  967. keyvalues={},
  968. updatevalues={"stream_id": upper_limit},
  969. )
  970. return len(rows) < limit
  971. def _rotate_notifs_txn(self, txn: LoggingTransaction) -> bool:
  972. """Archives older notifications (from event_push_actions) into event_push_summary.
  973. Returns whether the archiving process has caught up or not.
  974. """
  975. # The (inclusive) event stream ordering that was previously summarised.
  976. old_rotate_stream_ordering = self.db_pool.simple_select_one_onecol_txn(
  977. txn,
  978. table="event_push_summary_stream_ordering",
  979. keyvalues={},
  980. retcol="stream_ordering",
  981. )
  982. # We don't to try and rotate millions of rows at once, so we cap the
  983. # maximum stream ordering we'll rotate before.
  984. txn.execute(
  985. """
  986. SELECT stream_ordering FROM event_push_actions
  987. WHERE stream_ordering > ?
  988. ORDER BY stream_ordering ASC LIMIT 1 OFFSET ?
  989. """,
  990. (old_rotate_stream_ordering, self._rotate_count),
  991. )
  992. stream_row = txn.fetchone()
  993. if stream_row:
  994. (offset_stream_ordering,) = stream_row
  995. # We need to bound by the current token to ensure that we handle
  996. # out-of-order writes correctly.
  997. rotate_to_stream_ordering = min(
  998. offset_stream_ordering, self._stream_id_gen.get_current_token()
  999. )
  1000. caught_up = False
  1001. else:
  1002. rotate_to_stream_ordering = self._stream_id_gen.get_current_token()
  1003. caught_up = True
  1004. logger.info("Rotating notifications up to: %s", rotate_to_stream_ordering)
  1005. self._rotate_notifs_before_txn(
  1006. txn, old_rotate_stream_ordering, rotate_to_stream_ordering
  1007. )
  1008. return caught_up
  1009. def _rotate_notifs_before_txn(
  1010. self,
  1011. txn: LoggingTransaction,
  1012. old_rotate_stream_ordering: int,
  1013. rotate_to_stream_ordering: int,
  1014. ) -> None:
  1015. """Archives older notifications (from event_push_actions) into event_push_summary.
  1016. Any event_push_actions between old_rotate_stream_ordering (exclusive) and
  1017. rotate_to_stream_ordering (inclusive) will be added to the event_push_summary
  1018. table.
  1019. Args:
  1020. txn: The database transaction.
  1021. old_rotate_stream_ordering: The previous maximum event stream ordering.
  1022. rotate_to_stream_ordering: The new maximum event stream ordering to summarise.
  1023. """
  1024. # Calculate the new counts that should be upserted into event_push_summary
  1025. sql = """
  1026. SELECT user_id, room_id,
  1027. coalesce(old.%s, 0) + upd.cnt,
  1028. upd.stream_ordering
  1029. FROM (
  1030. SELECT user_id, room_id, count(*) as cnt,
  1031. max(ea.stream_ordering) as stream_ordering
  1032. FROM event_push_actions AS ea
  1033. LEFT JOIN event_push_summary AS old USING (user_id, room_id)
  1034. WHERE ? < ea.stream_ordering AND ea.stream_ordering <= ?
  1035. AND (
  1036. old.last_receipt_stream_ordering IS NULL
  1037. OR old.last_receipt_stream_ordering < ea.stream_ordering
  1038. )
  1039. AND %s = 1
  1040. GROUP BY user_id, room_id
  1041. ) AS upd
  1042. LEFT JOIN event_push_summary AS old USING (user_id, room_id)
  1043. """
  1044. # First get the count of unread messages.
  1045. txn.execute(
  1046. sql % ("unread_count", "unread"),
  1047. (old_rotate_stream_ordering, rotate_to_stream_ordering),
  1048. )
  1049. # We need to merge results from the two requests (the one that retrieves the
  1050. # unread count and the one that retrieves the notifications count) into a single
  1051. # object because we might not have the same amount of rows in each of them. To do
  1052. # this, we use a dict indexed on the user ID and room ID to make it easier to
  1053. # populate.
  1054. summaries: Dict[Tuple[str, str], _EventPushSummary] = {}
  1055. for row in txn:
  1056. summaries[(row[0], row[1])] = _EventPushSummary(
  1057. unread_count=row[2],
  1058. stream_ordering=row[3],
  1059. notif_count=0,
  1060. )
  1061. # Then get the count of notifications.
  1062. txn.execute(
  1063. sql % ("notif_count", "notif"),
  1064. (old_rotate_stream_ordering, rotate_to_stream_ordering),
  1065. )
  1066. for row in txn:
  1067. if (row[0], row[1]) in summaries:
  1068. summaries[(row[0], row[1])].notif_count = row[2]
  1069. else:
  1070. # Because the rules on notifying are different than the rules on marking
  1071. # a message unread, we might end up with messages that notify but aren't
  1072. # marked unread, so we might not have a summary for this (user, room)
  1073. # tuple to complete.
  1074. summaries[(row[0], row[1])] = _EventPushSummary(
  1075. unread_count=0,
  1076. stream_ordering=row[3],
  1077. notif_count=row[2],
  1078. )
  1079. logger.info("Rotating notifications, handling %d rows", len(summaries))
  1080. # TODO(threads): Update on a per-thread basis.
  1081. self.db_pool.simple_upsert_many_txn(
  1082. txn,
  1083. table="event_push_summary",
  1084. key_names=("user_id", "room_id"),
  1085. key_values=[(user_id, room_id) for user_id, room_id in summaries],
  1086. value_names=("notif_count", "unread_count", "stream_ordering", "thread_id"),
  1087. value_values=[
  1088. (
  1089. summary.notif_count,
  1090. summary.unread_count,
  1091. summary.stream_ordering,
  1092. "main",
  1093. )
  1094. for summary in summaries.values()
  1095. ],
  1096. )
  1097. txn.execute(
  1098. "UPDATE event_push_summary_stream_ordering SET stream_ordering = ?",
  1099. (rotate_to_stream_ordering,),
  1100. )
  1101. async def _remove_old_push_actions_that_have_rotated(self) -> None:
  1102. """Clear out old push actions that have been summarised."""
  1103. # We want to clear out anything that is older than a day that *has* already
  1104. # been rotated.
  1105. rotated_upto_stream_ordering = await self.db_pool.simple_select_one_onecol(
  1106. table="event_push_summary_stream_ordering",
  1107. keyvalues={},
  1108. retcol="stream_ordering",
  1109. )
  1110. max_stream_ordering_to_delete = min(
  1111. rotated_upto_stream_ordering, self.stream_ordering_day_ago
  1112. )
  1113. def remove_old_push_actions_that_have_rotated_txn(
  1114. txn: LoggingTransaction,
  1115. ) -> bool:
  1116. # We don't want to clear out too much at a time, so we bound our
  1117. # deletes.
  1118. batch_size = self._rotate_count
  1119. txn.execute(
  1120. """
  1121. SELECT stream_ordering FROM event_push_actions
  1122. WHERE stream_ordering <= ? AND highlight = 0
  1123. ORDER BY stream_ordering ASC LIMIT 1 OFFSET ?
  1124. """,
  1125. (
  1126. max_stream_ordering_to_delete,
  1127. batch_size,
  1128. ),
  1129. )
  1130. stream_row = txn.fetchone()
  1131. if stream_row:
  1132. (stream_ordering,) = stream_row
  1133. else:
  1134. stream_ordering = max_stream_ordering_to_delete
  1135. # We need to use a inclusive bound here to handle the case where a
  1136. # single stream ordering has more than `batch_size` rows.
  1137. txn.execute(
  1138. """
  1139. DELETE FROM event_push_actions
  1140. WHERE stream_ordering <= ? AND highlight = 0
  1141. """,
  1142. (stream_ordering,),
  1143. )
  1144. logger.info("Rotating notifications, deleted %s push actions", txn.rowcount)
  1145. return txn.rowcount < batch_size
  1146. while True:
  1147. done = await self.db_pool.runInteraction(
  1148. "_remove_old_push_actions_that_have_rotated",
  1149. remove_old_push_actions_that_have_rotated_txn,
  1150. )
  1151. if done:
  1152. break
  1153. class EventPushActionsStore(EventPushActionsWorkerStore):
  1154. EPA_HIGHLIGHT_INDEX = "epa_highlight_index"
  1155. def __init__(
  1156. self,
  1157. database: DatabasePool,
  1158. db_conn: LoggingDatabaseConnection,
  1159. hs: "HomeServer",
  1160. ):
  1161. super().__init__(database, db_conn, hs)
  1162. self.db_pool.updates.register_background_index_update(
  1163. self.EPA_HIGHLIGHT_INDEX,
  1164. index_name="event_push_actions_u_highlight",
  1165. table="event_push_actions",
  1166. columns=["user_id", "stream_ordering"],
  1167. )
  1168. self.db_pool.updates.register_background_index_update(
  1169. "event_push_actions_highlights_index",
  1170. index_name="event_push_actions_highlights_index",
  1171. table="event_push_actions",
  1172. columns=["user_id", "room_id", "topological_ordering", "stream_ordering"],
  1173. where_clause="highlight=1",
  1174. )
  1175. # Add index to make deleting old push actions faster.
  1176. self.db_pool.updates.register_background_index_update(
  1177. "event_push_actions_stream_highlight_index",
  1178. index_name="event_push_actions_stream_highlight_index",
  1179. table="event_push_actions",
  1180. columns=["highlight", "stream_ordering"],
  1181. where_clause="highlight=0",
  1182. )
  1183. async def get_push_actions_for_user(
  1184. self,
  1185. user_id: str,
  1186. before: Optional[str] = None,
  1187. limit: int = 50,
  1188. only_highlight: bool = False,
  1189. ) -> List[UserPushAction]:
  1190. def f(
  1191. txn: LoggingTransaction,
  1192. ) -> List[Tuple[str, str, int, int, str, bool, str, int]]:
  1193. before_clause = ""
  1194. if before:
  1195. before_clause = "AND epa.stream_ordering < ?"
  1196. args = [user_id, before, limit]
  1197. else:
  1198. args = [user_id, limit]
  1199. if only_highlight:
  1200. if len(before_clause) > 0:
  1201. before_clause += " "
  1202. before_clause += "AND epa.highlight = 1"
  1203. # NB. This assumes event_ids are globally unique since
  1204. # it makes the query easier to index
  1205. sql = """
  1206. SELECT epa.event_id, epa.room_id,
  1207. epa.stream_ordering, epa.topological_ordering,
  1208. epa.actions, epa.highlight, epa.profile_tag, e.received_ts
  1209. FROM event_push_actions epa, events e
  1210. WHERE epa.event_id = e.event_id
  1211. AND epa.user_id = ? %s
  1212. AND epa.notif = 1
  1213. ORDER BY epa.stream_ordering DESC
  1214. LIMIT ?
  1215. """ % (
  1216. before_clause,
  1217. )
  1218. txn.execute(sql, args)
  1219. return cast(
  1220. List[Tuple[str, str, int, int, str, bool, str, int]], txn.fetchall()
  1221. )
  1222. push_actions = await self.db_pool.runInteraction("get_push_actions_for_user", f)
  1223. return [
  1224. UserPushAction(
  1225. event_id=row[0],
  1226. room_id=row[1],
  1227. stream_ordering=row[2],
  1228. actions=_deserialize_action(row[4], row[5]),
  1229. received_ts=row[7],
  1230. topological_ordering=row[3],
  1231. highlight=row[5],
  1232. profile_tag=row[6],
  1233. )
  1234. for row in push_actions
  1235. ]
  1236. def _action_has_highlight(actions: Collection[Union[Mapping, str]]) -> bool:
  1237. for action in actions:
  1238. if not isinstance(action, dict):
  1239. continue
  1240. if action.get("set_tweak", None) == "highlight":
  1241. return action.get("value", True)
  1242. return False
  1243. @attr.s(slots=True, auto_attribs=True)
  1244. class _EventPushSummary:
  1245. """Summary of pending event push actions for a given user in a given room.
  1246. Used in _rotate_notifs_before_txn to manipulate results from event_push_actions.
  1247. """
  1248. unread_count: int
  1249. stream_ordering: int
  1250. notif_count: int