event_push_actions.py 35 KB

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