event_push_actions.py 35 KB

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