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.
 
 
 
 
 
 

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