event_push_actions.py 35 KB

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