event_push_actions.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. from six import iteritems
  18. from canonicaljson import json
  19. from twisted.internet import defer
  20. from synapse.metrics.background_process_metrics import run_as_background_process
  21. from synapse.storage._base import LoggingTransaction, SQLBaseStore
  22. from synapse.storage.database import Database
  23. from synapse.util.caches.descriptors import cachedInlineCallbacks
  24. logger = logging.getLogger(__name__)
  25. DEFAULT_NOTIF_ACTION = ["notify", {"set_tweak": "highlight", "value": False}]
  26. DEFAULT_HIGHLIGHT_ACTION = [
  27. "notify",
  28. {"set_tweak": "sound", "value": "default"},
  29. {"set_tweak": "highlight"},
  30. ]
  31. def _serialize_action(actions, is_highlight):
  32. """Custom serializer for actions. This allows us to "compress" common actions.
  33. We use the fact that most users have the same actions for notifs (and for
  34. highlights).
  35. We store these default actions as the empty string rather than the full JSON.
  36. Since the empty string isn't valid JSON there is no risk of this clashing with
  37. any real JSON actions
  38. """
  39. if is_highlight:
  40. if actions == DEFAULT_HIGHLIGHT_ACTION:
  41. return "" # We use empty string as the column is non-NULL
  42. else:
  43. if actions == DEFAULT_NOTIF_ACTION:
  44. return ""
  45. return json.dumps(actions)
  46. def _deserialize_action(actions, is_highlight):
  47. """Custom deserializer for actions. This allows us to "compress" common actions
  48. """
  49. if actions:
  50. return json.loads(actions)
  51. if is_highlight:
  52. return DEFAULT_HIGHLIGHT_ACTION
  53. else:
  54. return DEFAULT_NOTIF_ACTION
  55. class EventPushActionsWorkerStore(SQLBaseStore):
  56. def __init__(self, database: Database, db_conn, hs):
  57. super(EventPushActionsWorkerStore, self).__init__(database, db_conn, hs)
  58. # These get correctly set by _find_stream_orderings_for_times_txn
  59. self.stream_ordering_month_ago = None
  60. self.stream_ordering_day_ago = None
  61. cur = LoggingTransaction(
  62. db_conn.cursor(),
  63. name="_find_stream_orderings_for_times_txn",
  64. database_engine=self.database_engine,
  65. )
  66. self._find_stream_orderings_for_times_txn(cur)
  67. cur.close()
  68. self.find_stream_orderings_looping_call = self._clock.looping_call(
  69. self._find_stream_orderings_for_times, 10 * 60 * 1000
  70. )
  71. self._rotate_delay = 3
  72. self._rotate_count = 10000
  73. @cachedInlineCallbacks(num_args=3, tree=True, max_entries=5000)
  74. def get_unread_event_push_actions_by_room_for_user(
  75. self, room_id, user_id, last_read_event_id
  76. ):
  77. ret = yield self.db.runInteraction(
  78. "get_unread_event_push_actions_by_room",
  79. self._get_unread_counts_by_receipt_txn,
  80. room_id,
  81. user_id,
  82. last_read_event_id,
  83. )
  84. return ret
  85. def _get_unread_counts_by_receipt_txn(
  86. self, txn, room_id, user_id, last_read_event_id
  87. ):
  88. sql = (
  89. "SELECT stream_ordering"
  90. " FROM events"
  91. " WHERE room_id = ? AND event_id = ?"
  92. )
  93. txn.execute(sql, (room_id, last_read_event_id))
  94. results = txn.fetchall()
  95. if len(results) == 0:
  96. return {"notify_count": 0, "highlight_count": 0}
  97. stream_ordering = results[0][0]
  98. return self._get_unread_counts_by_pos_txn(
  99. txn, room_id, user_id, stream_ordering
  100. )
  101. def _get_unread_counts_by_pos_txn(self, txn, room_id, user_id, stream_ordering):
  102. # First get number of notifications.
  103. # We don't need to put a notif=1 clause as all rows always have
  104. # notif=1
  105. sql = (
  106. "SELECT count(*)"
  107. " FROM event_push_actions ea"
  108. " WHERE"
  109. " user_id = ?"
  110. " AND room_id = ?"
  111. " AND stream_ordering > ?"
  112. )
  113. txn.execute(sql, (user_id, room_id, stream_ordering))
  114. row = txn.fetchone()
  115. notify_count = row[0] if row else 0
  116. txn.execute(
  117. """
  118. SELECT notif_count FROM event_push_summary
  119. WHERE room_id = ? AND user_id = ? AND stream_ordering > ?
  120. """,
  121. (room_id, user_id, stream_ordering),
  122. )
  123. rows = txn.fetchall()
  124. if rows:
  125. notify_count += rows[0][0]
  126. # Now get the number of highlights
  127. sql = (
  128. "SELECT count(*)"
  129. " FROM event_push_actions ea"
  130. " WHERE"
  131. " highlight = 1"
  132. " AND user_id = ?"
  133. " AND room_id = ?"
  134. " AND stream_ordering > ?"
  135. )
  136. txn.execute(sql, (user_id, room_id, stream_ordering))
  137. row = txn.fetchone()
  138. highlight_count = row[0] if row else 0
  139. return {"notify_count": notify_count, "highlight_count": highlight_count}
  140. @defer.inlineCallbacks
  141. def get_push_action_users_in_range(self, min_stream_ordering, max_stream_ordering):
  142. def f(txn):
  143. sql = (
  144. "SELECT DISTINCT(user_id) FROM event_push_actions WHERE"
  145. " stream_ordering >= ? AND stream_ordering <= ?"
  146. )
  147. txn.execute(sql, (min_stream_ordering, max_stream_ordering))
  148. return [r[0] for r in txn]
  149. ret = yield self.db.runInteraction("get_push_action_users_in_range", f)
  150. return ret
  151. @defer.inlineCallbacks
  152. def get_unread_push_actions_for_user_in_range_for_http(
  153. self, user_id, min_stream_ordering, max_stream_ordering, limit=20
  154. ):
  155. """Get a list of the most recent unread push actions for a given user,
  156. within the given stream ordering range. Called by the httppusher.
  157. Args:
  158. user_id (str): The user to fetch push actions for.
  159. min_stream_ordering(int): The exclusive lower bound on the
  160. stream ordering of event push actions to fetch.
  161. max_stream_ordering(int): The inclusive upper bound on the
  162. stream ordering of event push actions to fetch.
  163. limit (int): The maximum number of rows to return.
  164. Returns:
  165. A promise which resolves to a list of dicts with the keys "event_id",
  166. "room_id", "stream_ordering", "actions".
  167. The list will be ordered by ascending stream_ordering.
  168. The list will have between 0~limit entries.
  169. """
  170. # find rooms that have a read receipt in them and return the next
  171. # push actions
  172. def get_after_receipt(txn):
  173. # find rooms that have a read receipt in them and return the next
  174. # push actions
  175. sql = (
  176. "SELECT ep.event_id, ep.room_id, ep.stream_ordering, ep.actions,"
  177. " ep.highlight "
  178. " FROM ("
  179. " SELECT room_id,"
  180. " MAX(stream_ordering) as stream_ordering"
  181. " FROM events"
  182. " INNER JOIN receipts_linearized USING (room_id, event_id)"
  183. " WHERE receipt_type = 'm.read' AND user_id = ?"
  184. " GROUP BY room_id"
  185. ") AS rl,"
  186. " event_push_actions AS ep"
  187. " WHERE"
  188. " ep.room_id = rl.room_id"
  189. " AND ep.stream_ordering > rl.stream_ordering"
  190. " AND ep.user_id = ?"
  191. " AND ep.stream_ordering > ?"
  192. " AND ep.stream_ordering <= ?"
  193. " ORDER BY ep.stream_ordering ASC LIMIT ?"
  194. )
  195. args = [user_id, user_id, min_stream_ordering, max_stream_ordering, limit]
  196. txn.execute(sql, args)
  197. return txn.fetchall()
  198. after_read_receipt = yield self.db.runInteraction(
  199. "get_unread_push_actions_for_user_in_range_http_arr", get_after_receipt
  200. )
  201. # There are rooms with push actions in them but you don't have a read receipt in
  202. # them e.g. rooms you've been invited to, so get push actions for rooms which do
  203. # not have read receipts in them too.
  204. def get_no_receipt(txn):
  205. sql = (
  206. "SELECT ep.event_id, ep.room_id, ep.stream_ordering, ep.actions,"
  207. " ep.highlight "
  208. " FROM event_push_actions AS ep"
  209. " INNER JOIN events AS e USING (room_id, event_id)"
  210. " WHERE"
  211. " ep.room_id NOT IN ("
  212. " SELECT room_id FROM receipts_linearized"
  213. " WHERE receipt_type = 'm.read' AND user_id = ?"
  214. " GROUP BY room_id"
  215. " )"
  216. " AND ep.user_id = ?"
  217. " AND ep.stream_ordering > ?"
  218. " AND ep.stream_ordering <= ?"
  219. " ORDER BY ep.stream_ordering ASC LIMIT ?"
  220. )
  221. args = [user_id, user_id, min_stream_ordering, max_stream_ordering, limit]
  222. txn.execute(sql, args)
  223. return txn.fetchall()
  224. no_read_receipt = yield self.db.runInteraction(
  225. "get_unread_push_actions_for_user_in_range_http_nrr", get_no_receipt
  226. )
  227. notifs = [
  228. {
  229. "event_id": row[0],
  230. "room_id": row[1],
  231. "stream_ordering": row[2],
  232. "actions": _deserialize_action(row[3], row[4]),
  233. }
  234. for row in after_read_receipt + no_read_receipt
  235. ]
  236. # Now sort it so it's ordered correctly, since currently it will
  237. # contain results from the first query, correctly ordered, followed
  238. # by results from the second query, but we want them all ordered
  239. # by stream_ordering, oldest first.
  240. notifs.sort(key=lambda r: r["stream_ordering"])
  241. # Take only up to the limit. We have to stop at the limit because
  242. # one of the subqueries may have hit the limit.
  243. return notifs[:limit]
  244. @defer.inlineCallbacks
  245. def get_unread_push_actions_for_user_in_range_for_email(
  246. self, user_id, min_stream_ordering, max_stream_ordering, limit=20
  247. ):
  248. """Get a list of the most recent unread push actions for a given user,
  249. within the given stream ordering range. Called by the emailpusher
  250. Args:
  251. user_id (str): The user to fetch push actions for.
  252. min_stream_ordering(int): The exclusive lower bound on the
  253. stream ordering of event push actions to fetch.
  254. max_stream_ordering(int): The inclusive upper bound on the
  255. stream ordering of event push actions to fetch.
  256. limit (int): The maximum number of rows to return.
  257. Returns:
  258. A promise which resolves to a list of dicts with the keys "event_id",
  259. "room_id", "stream_ordering", "actions", "received_ts".
  260. The list will be ordered by descending received_ts.
  261. The list will have between 0~limit entries.
  262. """
  263. # find rooms that have a read receipt in them and return the most recent
  264. # push actions
  265. def get_after_receipt(txn):
  266. sql = (
  267. "SELECT ep.event_id, ep.room_id, ep.stream_ordering, ep.actions,"
  268. " ep.highlight, e.received_ts"
  269. " FROM ("
  270. " SELECT room_id,"
  271. " MAX(stream_ordering) as stream_ordering"
  272. " FROM events"
  273. " INNER JOIN receipts_linearized USING (room_id, event_id)"
  274. " WHERE receipt_type = 'm.read' AND user_id = ?"
  275. " GROUP BY room_id"
  276. ") AS rl,"
  277. " event_push_actions AS ep"
  278. " INNER JOIN events AS e USING (room_id, event_id)"
  279. " WHERE"
  280. " ep.room_id = rl.room_id"
  281. " AND ep.stream_ordering > rl.stream_ordering"
  282. " AND ep.user_id = ?"
  283. " AND ep.stream_ordering > ?"
  284. " AND ep.stream_ordering <= ?"
  285. " ORDER BY ep.stream_ordering DESC LIMIT ?"
  286. )
  287. args = [user_id, user_id, min_stream_ordering, max_stream_ordering, limit]
  288. txn.execute(sql, args)
  289. return txn.fetchall()
  290. after_read_receipt = yield self.db.runInteraction(
  291. "get_unread_push_actions_for_user_in_range_email_arr", get_after_receipt
  292. )
  293. # There are rooms with push actions in them but you don't have a read receipt in
  294. # them e.g. rooms you've been invited to, so get push actions for rooms which do
  295. # not have read receipts in them too.
  296. def get_no_receipt(txn):
  297. sql = (
  298. "SELECT ep.event_id, ep.room_id, ep.stream_ordering, ep.actions,"
  299. " ep.highlight, e.received_ts"
  300. " FROM event_push_actions AS ep"
  301. " INNER JOIN events AS e USING (room_id, event_id)"
  302. " WHERE"
  303. " ep.room_id NOT IN ("
  304. " SELECT room_id FROM receipts_linearized"
  305. " WHERE receipt_type = 'm.read' AND user_id = ?"
  306. " GROUP BY room_id"
  307. " )"
  308. " AND ep.user_id = ?"
  309. " AND ep.stream_ordering > ?"
  310. " AND ep.stream_ordering <= ?"
  311. " ORDER BY ep.stream_ordering DESC LIMIT ?"
  312. )
  313. args = [user_id, user_id, min_stream_ordering, max_stream_ordering, limit]
  314. txn.execute(sql, args)
  315. return txn.fetchall()
  316. no_read_receipt = yield self.db.runInteraction(
  317. "get_unread_push_actions_for_user_in_range_email_nrr", get_no_receipt
  318. )
  319. # Make a list of dicts from the two sets of results.
  320. notifs = [
  321. {
  322. "event_id": row[0],
  323. "room_id": row[1],
  324. "stream_ordering": row[2],
  325. "actions": _deserialize_action(row[3], row[4]),
  326. "received_ts": row[5],
  327. }
  328. for row in after_read_receipt + no_read_receipt
  329. ]
  330. # Now sort it so it's ordered correctly, since currently it will
  331. # contain results from the first query, correctly ordered, followed
  332. # by results from the second query, but we want them all ordered
  333. # by received_ts (most recent first)
  334. notifs.sort(key=lambda r: -(r["received_ts"] or 0))
  335. # Now return the first `limit`
  336. return notifs[:limit]
  337. def get_if_maybe_push_in_range_for_user(self, user_id, min_stream_ordering):
  338. """A fast check to see if there might be something to push for the
  339. user since the given stream ordering. May return false positives.
  340. Useful to know whether to bother starting a pusher on start up or not.
  341. Args:
  342. user_id (str)
  343. min_stream_ordering (int)
  344. Returns:
  345. Deferred[bool]: True if there may be push to process, False if
  346. there definitely isn't.
  347. """
  348. def _get_if_maybe_push_in_range_for_user_txn(txn):
  349. sql = """
  350. SELECT 1 FROM event_push_actions
  351. WHERE user_id = ? AND stream_ordering > ?
  352. LIMIT 1
  353. """
  354. txn.execute(sql, (user_id, min_stream_ordering))
  355. return bool(txn.fetchone())
  356. return self.db.runInteraction(
  357. "get_if_maybe_push_in_range_for_user",
  358. _get_if_maybe_push_in_range_for_user_txn,
  359. )
  360. def add_push_actions_to_staging(self, event_id, user_id_actions):
  361. """Add the push actions for the event to the push action staging area.
  362. Args:
  363. event_id (str)
  364. user_id_actions (dict[str, list[dict|str])]): A dictionary mapping
  365. user_id to list of push actions, where an action can either be
  366. a string or dict.
  367. Returns:
  368. Deferred
  369. """
  370. if not user_id_actions:
  371. return
  372. # This is a helper function for generating the necessary tuple that
  373. # can be used to inert into the `event_push_actions_staging` table.
  374. def _gen_entry(user_id, actions):
  375. is_highlight = 1 if _action_has_highlight(actions) else 0
  376. return (
  377. event_id, # event_id column
  378. user_id, # user_id column
  379. _serialize_action(actions, is_highlight), # actions column
  380. 1, # notif column
  381. is_highlight, # highlight column
  382. )
  383. def _add_push_actions_to_staging_txn(txn):
  384. # We don't use simple_insert_many here to avoid the overhead
  385. # of generating lists of dicts.
  386. sql = """
  387. INSERT INTO event_push_actions_staging
  388. (event_id, user_id, actions, notif, highlight)
  389. VALUES (?, ?, ?, ?, ?)
  390. """
  391. txn.executemany(
  392. sql,
  393. (
  394. _gen_entry(user_id, actions)
  395. for user_id, actions in iteritems(user_id_actions)
  396. ),
  397. )
  398. return self.db.runInteraction(
  399. "add_push_actions_to_staging", _add_push_actions_to_staging_txn
  400. )
  401. @defer.inlineCallbacks
  402. def remove_push_actions_from_staging(self, event_id):
  403. """Called if we failed to persist the event to ensure that stale push
  404. actions don't build up in the DB
  405. Args:
  406. event_id (str)
  407. """
  408. try:
  409. res = yield self.db.simple_delete(
  410. table="event_push_actions_staging",
  411. keyvalues={"event_id": event_id},
  412. desc="remove_push_actions_from_staging",
  413. )
  414. return res
  415. except Exception:
  416. # this method is called from an exception handler, so propagating
  417. # another exception here really isn't helpful - there's nothing
  418. # the caller can do about it. Just log the exception and move on.
  419. logger.exception(
  420. "Error removing push actions after event persistence failure"
  421. )
  422. def _find_stream_orderings_for_times(self):
  423. return run_as_background_process(
  424. "event_push_action_stream_orderings",
  425. self.db.runInteraction,
  426. "_find_stream_orderings_for_times",
  427. self._find_stream_orderings_for_times_txn,
  428. )
  429. def _find_stream_orderings_for_times_txn(self, txn):
  430. logger.info("Searching for stream ordering 1 month ago")
  431. self.stream_ordering_month_ago = self._find_first_stream_ordering_after_ts_txn(
  432. txn, self._clock.time_msec() - 30 * 24 * 60 * 60 * 1000
  433. )
  434. logger.info(
  435. "Found stream ordering 1 month ago: it's %d", self.stream_ordering_month_ago
  436. )
  437. logger.info("Searching for stream ordering 1 day ago")
  438. self.stream_ordering_day_ago = self._find_first_stream_ordering_after_ts_txn(
  439. txn, self._clock.time_msec() - 24 * 60 * 60 * 1000
  440. )
  441. logger.info(
  442. "Found stream ordering 1 day ago: it's %d", self.stream_ordering_day_ago
  443. )
  444. def find_first_stream_ordering_after_ts(self, ts):
  445. """Gets the stream ordering corresponding to a given timestamp.
  446. Specifically, finds the stream_ordering of the first event that was
  447. received on or after the timestamp. This is done by a binary search on
  448. the events table, since there is no index on received_ts, so is
  449. relatively slow.
  450. Args:
  451. ts (int): timestamp in millis
  452. Returns:
  453. Deferred[int]: stream ordering of the first event received on/after
  454. the timestamp
  455. """
  456. return self.db.runInteraction(
  457. "_find_first_stream_ordering_after_ts_txn",
  458. self._find_first_stream_ordering_after_ts_txn,
  459. ts,
  460. )
  461. @staticmethod
  462. def _find_first_stream_ordering_after_ts_txn(txn, ts):
  463. """
  464. Find the stream_ordering of the first event that was received on or
  465. after a given timestamp. This is relatively slow as there is no index
  466. on received_ts but we can then use this to delete push actions before
  467. this.
  468. received_ts must necessarily be in the same order as stream_ordering
  469. and stream_ordering is indexed, so we manually binary search using
  470. stream_ordering
  471. Args:
  472. txn (twisted.enterprise.adbapi.Transaction):
  473. ts (int): timestamp to search for
  474. Returns:
  475. int: stream ordering
  476. """
  477. txn.execute("SELECT MAX(stream_ordering) FROM events")
  478. max_stream_ordering = txn.fetchone()[0]
  479. if max_stream_ordering is None:
  480. return 0
  481. # We want the first stream_ordering in which received_ts is greater
  482. # than or equal to ts. Call this point X.
  483. #
  484. # We maintain the invariants:
  485. #
  486. # range_start <= X <= range_end
  487. #
  488. range_start = 0
  489. range_end = max_stream_ordering + 1
  490. # Given a stream_ordering, look up the timestamp at that
  491. # stream_ordering.
  492. #
  493. # The array may be sparse (we may be missing some stream_orderings).
  494. # We treat the gaps as the same as having the same value as the
  495. # preceding entry, because we will pick the lowest stream_ordering
  496. # which satisfies our requirement of received_ts >= ts.
  497. #
  498. # For example, if our array of events indexed by stream_ordering is
  499. # [10, <none>, 20], we should treat this as being equivalent to
  500. # [10, 10, 20].
  501. #
  502. sql = (
  503. "SELECT received_ts FROM events"
  504. " WHERE stream_ordering <= ?"
  505. " ORDER BY stream_ordering DESC"
  506. " LIMIT 1"
  507. )
  508. while range_end - range_start > 0:
  509. middle = (range_end + range_start) // 2
  510. txn.execute(sql, (middle,))
  511. row = txn.fetchone()
  512. if row is None:
  513. # no rows with stream_ordering<=middle
  514. range_start = middle + 1
  515. continue
  516. middle_ts = row[0]
  517. if ts > middle_ts:
  518. # we got a timestamp lower than the one we were looking for.
  519. # definitely need to look higher: X > middle.
  520. range_start = middle + 1
  521. else:
  522. # we got a timestamp higher than (or the same as) the one we
  523. # were looking for. We aren't yet sure about the point we
  524. # looked up, but we can be sure that X <= middle.
  525. range_end = middle
  526. return range_end
  527. class EventPushActionsStore(EventPushActionsWorkerStore):
  528. EPA_HIGHLIGHT_INDEX = "epa_highlight_index"
  529. def __init__(self, database: Database, db_conn, hs):
  530. super(EventPushActionsStore, self).__init__(database, db_conn, hs)
  531. self.db.updates.register_background_index_update(
  532. self.EPA_HIGHLIGHT_INDEX,
  533. index_name="event_push_actions_u_highlight",
  534. table="event_push_actions",
  535. columns=["user_id", "stream_ordering"],
  536. )
  537. self.db.updates.register_background_index_update(
  538. "event_push_actions_highlights_index",
  539. index_name="event_push_actions_highlights_index",
  540. table="event_push_actions",
  541. columns=["user_id", "room_id", "topological_ordering", "stream_ordering"],
  542. where_clause="highlight=1",
  543. )
  544. self._doing_notif_rotation = False
  545. self._rotate_notif_loop = self._clock.looping_call(
  546. self._start_rotate_notifs, 30 * 60 * 1000
  547. )
  548. def _set_push_actions_for_event_and_users_txn(
  549. self, txn, events_and_contexts, all_events_and_contexts
  550. ):
  551. """Handles moving push actions from staging table to main
  552. event_push_actions table for all events in `events_and_contexts`.
  553. Also ensures that all events in `all_events_and_contexts` are removed
  554. from the push action staging area.
  555. Args:
  556. events_and_contexts (list[(EventBase, EventContext)]): events
  557. we are persisting
  558. all_events_and_contexts (list[(EventBase, EventContext)]): all
  559. events that we were going to persist. This includes events
  560. we've already persisted, etc, that wouldn't appear in
  561. events_and_context.
  562. """
  563. sql = """
  564. INSERT INTO event_push_actions (
  565. room_id, event_id, user_id, actions, stream_ordering,
  566. topological_ordering, notif, highlight
  567. )
  568. SELECT ?, event_id, user_id, actions, ?, ?, notif, highlight
  569. FROM event_push_actions_staging
  570. WHERE event_id = ?
  571. """
  572. if events_and_contexts:
  573. txn.executemany(
  574. sql,
  575. (
  576. (
  577. event.room_id,
  578. event.internal_metadata.stream_ordering,
  579. event.depth,
  580. event.event_id,
  581. )
  582. for event, _ in events_and_contexts
  583. ),
  584. )
  585. for event, _ in events_and_contexts:
  586. user_ids = self.db.simple_select_onecol_txn(
  587. txn,
  588. table="event_push_actions_staging",
  589. keyvalues={"event_id": event.event_id},
  590. retcol="user_id",
  591. )
  592. for uid in user_ids:
  593. txn.call_after(
  594. self.get_unread_event_push_actions_by_room_for_user.invalidate_many,
  595. (event.room_id, uid),
  596. )
  597. # Now we delete the staging area for *all* events that were being
  598. # persisted.
  599. txn.executemany(
  600. "DELETE FROM event_push_actions_staging WHERE event_id = ?",
  601. ((event.event_id,) for event, _ in all_events_and_contexts),
  602. )
  603. @defer.inlineCallbacks
  604. def get_push_actions_for_user(
  605. self, user_id, before=None, limit=50, only_highlight=False
  606. ):
  607. def f(txn):
  608. before_clause = ""
  609. if before:
  610. before_clause = "AND epa.stream_ordering < ?"
  611. args = [user_id, before, limit]
  612. else:
  613. args = [user_id, limit]
  614. if only_highlight:
  615. if len(before_clause) > 0:
  616. before_clause += " "
  617. before_clause += "AND epa.highlight = 1"
  618. # NB. This assumes event_ids are globally unique since
  619. # it makes the query easier to index
  620. sql = (
  621. "SELECT epa.event_id, epa.room_id,"
  622. " epa.stream_ordering, epa.topological_ordering,"
  623. " epa.actions, epa.highlight, epa.profile_tag, e.received_ts"
  624. " FROM event_push_actions epa, events e"
  625. " WHERE epa.event_id = e.event_id"
  626. " AND epa.user_id = ? %s"
  627. " ORDER BY epa.stream_ordering DESC"
  628. " LIMIT ?" % (before_clause,)
  629. )
  630. txn.execute(sql, args)
  631. return self.db.cursor_to_dict(txn)
  632. push_actions = yield self.db.runInteraction("get_push_actions_for_user", f)
  633. for pa in push_actions:
  634. pa["actions"] = _deserialize_action(pa["actions"], pa["highlight"])
  635. return push_actions
  636. @defer.inlineCallbacks
  637. def get_time_of_last_push_action_before(self, stream_ordering):
  638. def f(txn):
  639. sql = (
  640. "SELECT e.received_ts"
  641. " FROM event_push_actions AS ep"
  642. " JOIN events e ON ep.room_id = e.room_id AND ep.event_id = e.event_id"
  643. " WHERE ep.stream_ordering > ?"
  644. " ORDER BY ep.stream_ordering ASC"
  645. " LIMIT 1"
  646. )
  647. txn.execute(sql, (stream_ordering,))
  648. return txn.fetchone()
  649. result = yield self.db.runInteraction("get_time_of_last_push_action_before", f)
  650. return result[0] if result else None
  651. @defer.inlineCallbacks
  652. def get_latest_push_action_stream_ordering(self):
  653. def f(txn):
  654. txn.execute("SELECT MAX(stream_ordering) FROM event_push_actions")
  655. return txn.fetchone()
  656. result = yield self.db.runInteraction(
  657. "get_latest_push_action_stream_ordering", f
  658. )
  659. return result[0] or 0
  660. def _remove_push_actions_for_event_id_txn(self, txn, room_id, event_id):
  661. # Sad that we have to blow away the cache for the whole room here
  662. txn.call_after(
  663. self.get_unread_event_push_actions_by_room_for_user.invalidate_many,
  664. (room_id,),
  665. )
  666. txn.execute(
  667. "DELETE FROM event_push_actions WHERE room_id = ? AND event_id = ?",
  668. (room_id, event_id),
  669. )
  670. def _remove_old_push_actions_before_txn(
  671. self, txn, room_id, user_id, stream_ordering
  672. ):
  673. """
  674. Purges old push actions for a user and room before a given
  675. stream_ordering.
  676. We however keep a months worth of highlighted notifications, so that
  677. users can still get a list of recent highlights.
  678. Args:
  679. txn: The transcation
  680. room_id: Room ID to delete from
  681. user_id: user ID to delete for
  682. stream_ordering: The lowest stream ordering which will
  683. not be deleted.
  684. """
  685. txn.call_after(
  686. self.get_unread_event_push_actions_by_room_for_user.invalidate_many,
  687. (room_id, user_id),
  688. )
  689. # We need to join on the events table to get the received_ts for
  690. # event_push_actions and sqlite won't let us use a join in a delete so
  691. # we can't just delete where received_ts < x. Furthermore we can
  692. # only identify event_push_actions by a tuple of room_id, event_id
  693. # we we can't use a subquery.
  694. # Instead, we look up the stream ordering for the last event in that
  695. # room received before the threshold time and delete event_push_actions
  696. # in the room with a stream_odering before that.
  697. txn.execute(
  698. "DELETE FROM event_push_actions "
  699. " WHERE user_id = ? AND room_id = ? AND "
  700. " stream_ordering <= ?"
  701. " AND ((stream_ordering < ? AND highlight = 1) or highlight = 0)",
  702. (user_id, room_id, stream_ordering, self.stream_ordering_month_ago),
  703. )
  704. txn.execute(
  705. """
  706. DELETE FROM event_push_summary
  707. WHERE room_id = ? AND user_id = ? AND stream_ordering <= ?
  708. """,
  709. (room_id, user_id, stream_ordering),
  710. )
  711. def _start_rotate_notifs(self):
  712. return run_as_background_process("rotate_notifs", self._rotate_notifs)
  713. @defer.inlineCallbacks
  714. def _rotate_notifs(self):
  715. if self._doing_notif_rotation or self.stream_ordering_day_ago is None:
  716. return
  717. self._doing_notif_rotation = True
  718. try:
  719. while True:
  720. logger.info("Rotating notifications")
  721. caught_up = yield self.db.runInteraction(
  722. "_rotate_notifs", self._rotate_notifs_txn
  723. )
  724. if caught_up:
  725. break
  726. yield self.hs.get_clock().sleep(self._rotate_delay)
  727. finally:
  728. self._doing_notif_rotation = False
  729. def _rotate_notifs_txn(self, txn):
  730. """Archives older notifications into event_push_summary. Returns whether
  731. the archiving process has caught up or not.
  732. """
  733. old_rotate_stream_ordering = self.db.simple_select_one_onecol_txn(
  734. txn,
  735. table="event_push_summary_stream_ordering",
  736. keyvalues={},
  737. retcol="stream_ordering",
  738. )
  739. # We don't to try and rotate millions of rows at once, so we cap the
  740. # maximum stream ordering we'll rotate before.
  741. txn.execute(
  742. """
  743. SELECT stream_ordering FROM event_push_actions
  744. WHERE stream_ordering > ?
  745. ORDER BY stream_ordering ASC LIMIT 1 OFFSET ?
  746. """,
  747. (old_rotate_stream_ordering, self._rotate_count),
  748. )
  749. stream_row = txn.fetchone()
  750. if stream_row:
  751. (offset_stream_ordering,) = stream_row
  752. rotate_to_stream_ordering = min(
  753. self.stream_ordering_day_ago, offset_stream_ordering
  754. )
  755. caught_up = offset_stream_ordering >= self.stream_ordering_day_ago
  756. else:
  757. rotate_to_stream_ordering = self.stream_ordering_day_ago
  758. caught_up = True
  759. logger.info("Rotating notifications up to: %s", rotate_to_stream_ordering)
  760. self._rotate_notifs_before_txn(txn, rotate_to_stream_ordering)
  761. # We have caught up iff we were limited by `stream_ordering_day_ago`
  762. return caught_up
  763. def _rotate_notifs_before_txn(self, txn, rotate_to_stream_ordering):
  764. old_rotate_stream_ordering = self.db.simple_select_one_onecol_txn(
  765. txn,
  766. table="event_push_summary_stream_ordering",
  767. keyvalues={},
  768. retcol="stream_ordering",
  769. )
  770. # Calculate the new counts that should be upserted into event_push_summary
  771. sql = """
  772. SELECT user_id, room_id,
  773. coalesce(old.notif_count, 0) + upd.notif_count,
  774. upd.stream_ordering,
  775. old.user_id
  776. FROM (
  777. SELECT user_id, room_id, count(*) as notif_count,
  778. max(stream_ordering) as stream_ordering
  779. FROM event_push_actions
  780. WHERE ? <= stream_ordering AND stream_ordering < ?
  781. AND highlight = 0
  782. GROUP BY user_id, room_id
  783. ) AS upd
  784. LEFT JOIN event_push_summary AS old USING (user_id, room_id)
  785. """
  786. txn.execute(sql, (old_rotate_stream_ordering, rotate_to_stream_ordering))
  787. rows = txn.fetchall()
  788. logger.info("Rotating notifications, handling %d rows", len(rows))
  789. # If the `old.user_id` above is NULL then we know there isn't already an
  790. # entry in the table, so we simply insert it. Otherwise we update the
  791. # existing table.
  792. self.db.simple_insert_many_txn(
  793. txn,
  794. table="event_push_summary",
  795. values=[
  796. {
  797. "user_id": row[0],
  798. "room_id": row[1],
  799. "notif_count": row[2],
  800. "stream_ordering": row[3],
  801. }
  802. for row in rows
  803. if row[4] is None
  804. ],
  805. )
  806. txn.executemany(
  807. """
  808. UPDATE event_push_summary SET notif_count = ?, stream_ordering = ?
  809. WHERE user_id = ? AND room_id = ?
  810. """,
  811. ((row[2], row[3], row[0], row[1]) for row in rows if row[4] is not None),
  812. )
  813. txn.execute(
  814. "DELETE FROM event_push_actions"
  815. " WHERE ? <= stream_ordering AND stream_ordering < ? AND highlight = 0",
  816. (old_rotate_stream_ordering, rotate_to_stream_ordering),
  817. )
  818. logger.info("Rotating notifications, deleted %s push actions", txn.rowcount)
  819. txn.execute(
  820. "UPDATE event_push_summary_stream_ordering SET stream_ordering = ?",
  821. (rotate_to_stream_ordering,),
  822. )
  823. def _action_has_highlight(actions):
  824. for action in actions:
  825. try:
  826. if action.get("set_tweak", None) == "highlight":
  827. return action.get("value", True)
  828. except AttributeError:
  829. pass
  830. return False