1
0

push_rule.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 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 ._base import SQLBaseStore
  17. from synapse.storage.appservice import ApplicationServiceWorkerStore
  18. from synapse.storage.pusher import PusherWorkerStore
  19. from synapse.storage.receipts import ReceiptsWorkerStore
  20. from synapse.storage.roommember import RoomMemberWorkerStore
  21. from synapse.util.caches.descriptors import cachedInlineCallbacks, cachedList
  22. from synapse.util.caches.stream_change_cache import StreamChangeCache
  23. from synapse.push.baserules import list_with_base_rules
  24. from synapse.api.constants import EventTypes
  25. from twisted.internet import defer
  26. from canonicaljson import json
  27. import abc
  28. import logging
  29. logger = logging.getLogger(__name__)
  30. def _load_rules(rawrules, enabled_map):
  31. ruleslist = []
  32. for rawrule in rawrules:
  33. rule = dict(rawrule)
  34. rule["conditions"] = json.loads(rawrule["conditions"])
  35. rule["actions"] = json.loads(rawrule["actions"])
  36. ruleslist.append(rule)
  37. # We're going to be mutating this a lot, so do a deep copy
  38. rules = list(list_with_base_rules(ruleslist))
  39. for i, rule in enumerate(rules):
  40. rule_id = rule['rule_id']
  41. if rule_id in enabled_map:
  42. if rule.get('enabled', True) != bool(enabled_map[rule_id]):
  43. # Rules are cached across users.
  44. rule = dict(rule)
  45. rule['enabled'] = bool(enabled_map[rule_id])
  46. rules[i] = rule
  47. return rules
  48. class PushRulesWorkerStore(ApplicationServiceWorkerStore,
  49. ReceiptsWorkerStore,
  50. PusherWorkerStore,
  51. RoomMemberWorkerStore,
  52. SQLBaseStore):
  53. """This is an abstract base class where subclasses must implement
  54. `get_max_push_rules_stream_id` which can be called in the initializer.
  55. """
  56. # This ABCMeta metaclass ensures that we cannot be instantiated without
  57. # the abstract methods being implemented.
  58. __metaclass__ = abc.ABCMeta
  59. def __init__(self, db_conn, hs):
  60. super(PushRulesWorkerStore, self).__init__(db_conn, hs)
  61. push_rules_prefill, push_rules_id = self._get_cache_dict(
  62. db_conn, "push_rules_stream",
  63. entity_column="user_id",
  64. stream_column="stream_id",
  65. max_value=self.get_max_push_rules_stream_id(),
  66. )
  67. self.push_rules_stream_cache = StreamChangeCache(
  68. "PushRulesStreamChangeCache", push_rules_id,
  69. prefilled_cache=push_rules_prefill,
  70. )
  71. @abc.abstractmethod
  72. def get_max_push_rules_stream_id(self):
  73. """Get the position of the push rules stream.
  74. Returns:
  75. int
  76. """
  77. raise NotImplementedError()
  78. @cachedInlineCallbacks(max_entries=5000)
  79. def get_push_rules_for_user(self, user_id):
  80. rows = yield self._simple_select_list(
  81. table="push_rules",
  82. keyvalues={
  83. "user_name": user_id,
  84. },
  85. retcols=(
  86. "user_name", "rule_id", "priority_class", "priority",
  87. "conditions", "actions",
  88. ),
  89. desc="get_push_rules_enabled_for_user",
  90. )
  91. rows.sort(
  92. key=lambda row: (-int(row["priority_class"]), -int(row["priority"]))
  93. )
  94. enabled_map = yield self.get_push_rules_enabled_for_user(user_id)
  95. rules = _load_rules(rows, enabled_map)
  96. defer.returnValue(rules)
  97. @cachedInlineCallbacks(max_entries=5000)
  98. def get_push_rules_enabled_for_user(self, user_id):
  99. results = yield self._simple_select_list(
  100. table="push_rules_enable",
  101. keyvalues={
  102. 'user_name': user_id
  103. },
  104. retcols=(
  105. "user_name", "rule_id", "enabled",
  106. ),
  107. desc="get_push_rules_enabled_for_user",
  108. )
  109. defer.returnValue({
  110. r['rule_id']: False if r['enabled'] == 0 else True for r in results
  111. })
  112. def have_push_rules_changed_for_user(self, user_id, last_id):
  113. if not self.push_rules_stream_cache.has_entity_changed(user_id, last_id):
  114. return defer.succeed(False)
  115. else:
  116. def have_push_rules_changed_txn(txn):
  117. sql = (
  118. "SELECT COUNT(stream_id) FROM push_rules_stream"
  119. " WHERE user_id = ? AND ? < stream_id"
  120. )
  121. txn.execute(sql, (user_id, last_id))
  122. count, = txn.fetchone()
  123. return bool(count)
  124. return self.runInteraction(
  125. "have_push_rules_changed", have_push_rules_changed_txn
  126. )
  127. @cachedList(cached_method_name="get_push_rules_for_user",
  128. list_name="user_ids", num_args=1, inlineCallbacks=True)
  129. def bulk_get_push_rules(self, user_ids):
  130. if not user_ids:
  131. defer.returnValue({})
  132. results = {
  133. user_id: []
  134. for user_id in user_ids
  135. }
  136. rows = yield self._simple_select_many_batch(
  137. table="push_rules",
  138. column="user_name",
  139. iterable=user_ids,
  140. retcols=("*",),
  141. desc="bulk_get_push_rules",
  142. )
  143. rows.sort(
  144. key=lambda row: (-int(row["priority_class"]), -int(row["priority"]))
  145. )
  146. for row in rows:
  147. results.setdefault(row['user_name'], []).append(row)
  148. enabled_map_by_user = yield self.bulk_get_push_rules_enabled(user_ids)
  149. for user_id, rules in results.items():
  150. results[user_id] = _load_rules(
  151. rules, enabled_map_by_user.get(user_id, {})
  152. )
  153. defer.returnValue(results)
  154. def bulk_get_push_rules_for_room(self, event, context):
  155. state_group = context.state_group
  156. if not state_group:
  157. # If state_group is None it means it has yet to be assigned a
  158. # state group, i.e. we need to make sure that calls with a state_group
  159. # of None don't hit previous cached calls with a None state_group.
  160. # To do this we set the state_group to a new object as object() != object()
  161. state_group = object()
  162. return self._bulk_get_push_rules_for_room(
  163. event.room_id, state_group, context.current_state_ids, event=event
  164. )
  165. @cachedInlineCallbacks(num_args=2, cache_context=True)
  166. def _bulk_get_push_rules_for_room(self, room_id, state_group, current_state_ids,
  167. cache_context, event=None):
  168. # We don't use `state_group`, its there so that we can cache based
  169. # on it. However, its important that its never None, since two current_state's
  170. # with a state_group of None are likely to be different.
  171. # See bulk_get_push_rules_for_room for how we work around this.
  172. assert state_group is not None
  173. # We also will want to generate notifs for other people in the room so
  174. # their unread countss are correct in the event stream, but to avoid
  175. # generating them for bot / AS users etc, we only do so for people who've
  176. # sent a read receipt into the room.
  177. users_in_room = yield self._get_joined_users_from_context(
  178. room_id, state_group, current_state_ids,
  179. on_invalidate=cache_context.invalidate,
  180. event=event,
  181. )
  182. # We ignore app service users for now. This is so that we don't fill
  183. # up the `get_if_users_have_pushers` cache with AS entries that we
  184. # know don't have pushers, nor even read receipts.
  185. local_users_in_room = set(
  186. u for u in users_in_room
  187. if self.hs.is_mine_id(u)
  188. and not self.get_if_app_services_interested_in_user(u)
  189. )
  190. # users in the room who have pushers need to get push rules run because
  191. # that's how their pushers work
  192. if_users_with_pushers = yield self.get_if_users_have_pushers(
  193. local_users_in_room,
  194. on_invalidate=cache_context.invalidate,
  195. )
  196. user_ids = set(
  197. uid for uid, have_pusher in if_users_with_pushers.items() if have_pusher
  198. )
  199. users_with_receipts = yield self.get_users_with_read_receipts_in_room(
  200. room_id, on_invalidate=cache_context.invalidate,
  201. )
  202. # any users with pushers must be ours: they have pushers
  203. for uid in users_with_receipts:
  204. if uid in local_users_in_room:
  205. user_ids.add(uid)
  206. forgotten = yield self.who_forgot_in_room(
  207. event.room_id, on_invalidate=cache_context.invalidate,
  208. )
  209. for row in forgotten:
  210. user_id = row["user_id"]
  211. event_id = row["event_id"]
  212. mem_id = current_state_ids.get((EventTypes.Member, user_id), None)
  213. if event_id == mem_id:
  214. user_ids.discard(user_id)
  215. rules_by_user = yield self.bulk_get_push_rules(
  216. user_ids, on_invalidate=cache_context.invalidate,
  217. )
  218. rules_by_user = {k: v for k, v in rules_by_user.items() if v is not None}
  219. defer.returnValue(rules_by_user)
  220. @cachedList(cached_method_name="get_push_rules_enabled_for_user",
  221. list_name="user_ids", num_args=1, inlineCallbacks=True)
  222. def bulk_get_push_rules_enabled(self, user_ids):
  223. if not user_ids:
  224. defer.returnValue({})
  225. results = {
  226. user_id: {}
  227. for user_id in user_ids
  228. }
  229. rows = yield self._simple_select_many_batch(
  230. table="push_rules_enable",
  231. column="user_name",
  232. iterable=user_ids,
  233. retcols=("user_name", "rule_id", "enabled",),
  234. desc="bulk_get_push_rules_enabled",
  235. )
  236. for row in rows:
  237. enabled = bool(row['enabled'])
  238. results.setdefault(row['user_name'], {})[row['rule_id']] = enabled
  239. defer.returnValue(results)
  240. class PushRuleStore(PushRulesWorkerStore):
  241. @defer.inlineCallbacks
  242. def add_push_rule(
  243. self, user_id, rule_id, priority_class, conditions, actions,
  244. before=None, after=None
  245. ):
  246. conditions_json = json.dumps(conditions)
  247. actions_json = json.dumps(actions)
  248. with self._push_rules_stream_id_gen.get_next() as ids:
  249. stream_id, event_stream_ordering = ids
  250. if before or after:
  251. yield self.runInteraction(
  252. "_add_push_rule_relative_txn",
  253. self._add_push_rule_relative_txn,
  254. stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  255. conditions_json, actions_json, before, after,
  256. )
  257. else:
  258. yield self.runInteraction(
  259. "_add_push_rule_highest_priority_txn",
  260. self._add_push_rule_highest_priority_txn,
  261. stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  262. conditions_json, actions_json,
  263. )
  264. def _add_push_rule_relative_txn(
  265. self, txn, stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  266. conditions_json, actions_json, before, after
  267. ):
  268. # Lock the table since otherwise we'll have annoying races between the
  269. # SELECT here and the UPSERT below.
  270. self.database_engine.lock_table(txn, "push_rules")
  271. relative_to_rule = before or after
  272. res = self._simple_select_one_txn(
  273. txn,
  274. table="push_rules",
  275. keyvalues={
  276. "user_name": user_id,
  277. "rule_id": relative_to_rule,
  278. },
  279. retcols=["priority_class", "priority"],
  280. allow_none=True,
  281. )
  282. if not res:
  283. raise RuleNotFoundException(
  284. "before/after rule not found: %s" % (relative_to_rule,)
  285. )
  286. base_priority_class = res["priority_class"]
  287. base_rule_priority = res["priority"]
  288. if base_priority_class != priority_class:
  289. raise InconsistentRuleException(
  290. "Given priority class does not match class of relative rule"
  291. )
  292. if before:
  293. # Higher priority rules are executed first, So adding a rule before
  294. # a rule means giving it a higher priority than that rule.
  295. new_rule_priority = base_rule_priority + 1
  296. else:
  297. # We increment the priority of the existing rules to make space for
  298. # the new rule. Therefore if we want this rule to appear after
  299. # an existing rule we give it the priority of the existing rule,
  300. # and then increment the priority of the existing rule.
  301. new_rule_priority = base_rule_priority
  302. sql = (
  303. "UPDATE push_rules SET priority = priority + 1"
  304. " WHERE user_name = ? AND priority_class = ? AND priority >= ?"
  305. )
  306. txn.execute(sql, (user_id, priority_class, new_rule_priority))
  307. self._upsert_push_rule_txn(
  308. txn, stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  309. new_rule_priority, conditions_json, actions_json,
  310. )
  311. def _add_push_rule_highest_priority_txn(
  312. self, txn, stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  313. conditions_json, actions_json
  314. ):
  315. # Lock the table since otherwise we'll have annoying races between the
  316. # SELECT here and the UPSERT below.
  317. self.database_engine.lock_table(txn, "push_rules")
  318. # find the highest priority rule in that class
  319. sql = (
  320. "SELECT COUNT(*), MAX(priority) FROM push_rules"
  321. " WHERE user_name = ? and priority_class = ?"
  322. )
  323. txn.execute(sql, (user_id, priority_class))
  324. res = txn.fetchall()
  325. (how_many, highest_prio) = res[0]
  326. new_prio = 0
  327. if how_many > 0:
  328. new_prio = highest_prio + 1
  329. self._upsert_push_rule_txn(
  330. txn,
  331. stream_id, event_stream_ordering, user_id, rule_id, priority_class, new_prio,
  332. conditions_json, actions_json,
  333. )
  334. def _upsert_push_rule_txn(
  335. self, txn, stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  336. priority, conditions_json, actions_json, update_stream=True
  337. ):
  338. """Specialised version of _simple_upsert_txn that picks a push_rule_id
  339. using the _push_rule_id_gen if it needs to insert the rule. It assumes
  340. that the "push_rules" table is locked"""
  341. sql = (
  342. "UPDATE push_rules"
  343. " SET priority_class = ?, priority = ?, conditions = ?, actions = ?"
  344. " WHERE user_name = ? AND rule_id = ?"
  345. )
  346. txn.execute(sql, (
  347. priority_class, priority, conditions_json, actions_json,
  348. user_id, rule_id,
  349. ))
  350. if txn.rowcount == 0:
  351. # We didn't update a row with the given rule_id so insert one
  352. push_rule_id = self._push_rule_id_gen.get_next()
  353. self._simple_insert_txn(
  354. txn,
  355. table="push_rules",
  356. values={
  357. "id": push_rule_id,
  358. "user_name": user_id,
  359. "rule_id": rule_id,
  360. "priority_class": priority_class,
  361. "priority": priority,
  362. "conditions": conditions_json,
  363. "actions": actions_json,
  364. },
  365. )
  366. if update_stream:
  367. self._insert_push_rules_update_txn(
  368. txn, stream_id, event_stream_ordering, user_id, rule_id,
  369. op="ADD",
  370. data={
  371. "priority_class": priority_class,
  372. "priority": priority,
  373. "conditions": conditions_json,
  374. "actions": actions_json,
  375. }
  376. )
  377. @defer.inlineCallbacks
  378. def delete_push_rule(self, user_id, rule_id):
  379. """
  380. Delete a push rule. Args specify the row to be deleted and can be
  381. any of the columns in the push_rule table, but below are the
  382. standard ones
  383. Args:
  384. user_id (str): The matrix ID of the push rule owner
  385. rule_id (str): The rule_id of the rule to be deleted
  386. """
  387. def delete_push_rule_txn(txn, stream_id, event_stream_ordering):
  388. self._simple_delete_one_txn(
  389. txn,
  390. "push_rules",
  391. {'user_name': user_id, 'rule_id': rule_id},
  392. )
  393. self._insert_push_rules_update_txn(
  394. txn, stream_id, event_stream_ordering, user_id, rule_id,
  395. op="DELETE"
  396. )
  397. with self._push_rules_stream_id_gen.get_next() as ids:
  398. stream_id, event_stream_ordering = ids
  399. yield self.runInteraction(
  400. "delete_push_rule", delete_push_rule_txn, stream_id, event_stream_ordering
  401. )
  402. @defer.inlineCallbacks
  403. def set_push_rule_enabled(self, user_id, rule_id, enabled):
  404. with self._push_rules_stream_id_gen.get_next() as ids:
  405. stream_id, event_stream_ordering = ids
  406. yield self.runInteraction(
  407. "_set_push_rule_enabled_txn",
  408. self._set_push_rule_enabled_txn,
  409. stream_id, event_stream_ordering, user_id, rule_id, enabled
  410. )
  411. def _set_push_rule_enabled_txn(
  412. self, txn, stream_id, event_stream_ordering, user_id, rule_id, enabled
  413. ):
  414. new_id = self._push_rules_enable_id_gen.get_next()
  415. self._simple_upsert_txn(
  416. txn,
  417. "push_rules_enable",
  418. {'user_name': user_id, 'rule_id': rule_id},
  419. {'enabled': 1 if enabled else 0},
  420. {'id': new_id},
  421. )
  422. self._insert_push_rules_update_txn(
  423. txn, stream_id, event_stream_ordering, user_id, rule_id,
  424. op="ENABLE" if enabled else "DISABLE"
  425. )
  426. @defer.inlineCallbacks
  427. def set_push_rule_actions(self, user_id, rule_id, actions, is_default_rule):
  428. actions_json = json.dumps(actions)
  429. def set_push_rule_actions_txn(txn, stream_id, event_stream_ordering):
  430. if is_default_rule:
  431. # Add a dummy rule to the rules table with the user specified
  432. # actions.
  433. priority_class = -1
  434. priority = 1
  435. self._upsert_push_rule_txn(
  436. txn, stream_id, event_stream_ordering, user_id, rule_id,
  437. priority_class, priority, "[]", actions_json,
  438. update_stream=False
  439. )
  440. else:
  441. self._simple_update_one_txn(
  442. txn,
  443. "push_rules",
  444. {'user_name': user_id, 'rule_id': rule_id},
  445. {'actions': actions_json},
  446. )
  447. self._insert_push_rules_update_txn(
  448. txn, stream_id, event_stream_ordering, user_id, rule_id,
  449. op="ACTIONS", data={"actions": actions_json}
  450. )
  451. with self._push_rules_stream_id_gen.get_next() as ids:
  452. stream_id, event_stream_ordering = ids
  453. yield self.runInteraction(
  454. "set_push_rule_actions", set_push_rule_actions_txn,
  455. stream_id, event_stream_ordering
  456. )
  457. def _insert_push_rules_update_txn(
  458. self, txn, stream_id, event_stream_ordering, user_id, rule_id, op, data=None
  459. ):
  460. values = {
  461. "stream_id": stream_id,
  462. "event_stream_ordering": event_stream_ordering,
  463. "user_id": user_id,
  464. "rule_id": rule_id,
  465. "op": op,
  466. }
  467. if data is not None:
  468. values.update(data)
  469. self._simple_insert_txn(txn, "push_rules_stream", values=values)
  470. txn.call_after(
  471. self.get_push_rules_for_user.invalidate, (user_id,)
  472. )
  473. txn.call_after(
  474. self.get_push_rules_enabled_for_user.invalidate, (user_id,)
  475. )
  476. txn.call_after(
  477. self.push_rules_stream_cache.entity_has_changed, user_id, stream_id
  478. )
  479. def get_all_push_rule_updates(self, last_id, current_id, limit):
  480. """Get all the push rules changes that have happend on the server"""
  481. if last_id == current_id:
  482. return defer.succeed([])
  483. def get_all_push_rule_updates_txn(txn):
  484. sql = (
  485. "SELECT stream_id, event_stream_ordering, user_id, rule_id,"
  486. " op, priority_class, priority, conditions, actions"
  487. " FROM push_rules_stream"
  488. " WHERE ? < stream_id AND stream_id <= ?"
  489. " ORDER BY stream_id ASC LIMIT ?"
  490. )
  491. txn.execute(sql, (last_id, current_id, limit))
  492. return txn.fetchall()
  493. return self.runInteraction(
  494. "get_all_push_rule_updates", get_all_push_rule_updates_txn
  495. )
  496. def get_push_rules_stream_token(self):
  497. """Get the position of the push rules stream.
  498. Returns a pair of a stream id for the push_rules stream and the
  499. room stream ordering it corresponds to."""
  500. return self._push_rules_stream_id_gen.get_current_token()
  501. def get_max_push_rules_stream_id(self):
  502. return self.get_push_rules_stream_token()[0]
  503. class RuleNotFoundException(Exception):
  504. pass
  505. class InconsistentRuleException(Exception):
  506. pass