push_rule.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from ._base import SQLBaseStore
  16. from synapse.util.caches.descriptors import cachedInlineCallbacks, cachedList
  17. from synapse.push.baserules import list_with_base_rules
  18. from twisted.internet import defer
  19. import logging
  20. import simplejson as json
  21. logger = logging.getLogger(__name__)
  22. def _load_rules(rawrules, enabled_map):
  23. ruleslist = []
  24. for rawrule in rawrules:
  25. rule = dict(rawrule)
  26. rule["conditions"] = json.loads(rawrule["conditions"])
  27. rule["actions"] = json.loads(rawrule["actions"])
  28. ruleslist.append(rule)
  29. # We're going to be mutating this a lot, so do a deep copy
  30. rules = list(list_with_base_rules(ruleslist))
  31. for i, rule in enumerate(rules):
  32. rule_id = rule['rule_id']
  33. if rule_id in enabled_map:
  34. if rule.get('enabled', True) != bool(enabled_map[rule_id]):
  35. # Rules are cached across users.
  36. rule = dict(rule)
  37. rule['enabled'] = bool(enabled_map[rule_id])
  38. rules[i] = rule
  39. return rules
  40. class PushRuleStore(SQLBaseStore):
  41. @cachedInlineCallbacks(lru=True)
  42. def get_push_rules_for_user(self, user_id):
  43. rows = yield self._simple_select_list(
  44. table="push_rules",
  45. keyvalues={
  46. "user_name": user_id,
  47. },
  48. retcols=(
  49. "user_name", "rule_id", "priority_class", "priority",
  50. "conditions", "actions",
  51. ),
  52. desc="get_push_rules_enabled_for_user",
  53. )
  54. rows.sort(
  55. key=lambda row: (-int(row["priority_class"]), -int(row["priority"]))
  56. )
  57. enabled_map = yield self.get_push_rules_enabled_for_user(user_id)
  58. rules = _load_rules(rows, enabled_map)
  59. defer.returnValue(rules)
  60. @cachedInlineCallbacks(lru=True)
  61. def get_push_rules_enabled_for_user(self, user_id):
  62. results = yield self._simple_select_list(
  63. table="push_rules_enable",
  64. keyvalues={
  65. 'user_name': user_id
  66. },
  67. retcols=(
  68. "user_name", "rule_id", "enabled",
  69. ),
  70. desc="get_push_rules_enabled_for_user",
  71. )
  72. defer.returnValue({
  73. r['rule_id']: False if r['enabled'] == 0 else True for r in results
  74. })
  75. @cachedList(cached_method_name="get_push_rules_for_user",
  76. list_name="user_ids", num_args=1, inlineCallbacks=True)
  77. def bulk_get_push_rules(self, user_ids):
  78. if not user_ids:
  79. defer.returnValue({})
  80. results = {
  81. user_id: []
  82. for user_id in user_ids
  83. }
  84. rows = yield self._simple_select_many_batch(
  85. table="push_rules",
  86. column="user_name",
  87. iterable=user_ids,
  88. retcols=("*",),
  89. desc="bulk_get_push_rules",
  90. )
  91. rows.sort(
  92. key=lambda row: (-int(row["priority_class"]), -int(row["priority"]))
  93. )
  94. for row in rows:
  95. results.setdefault(row['user_name'], []).append(row)
  96. enabled_map_by_user = yield self.bulk_get_push_rules_enabled(user_ids)
  97. for user_id, rules in results.items():
  98. results[user_id] = _load_rules(
  99. rules, enabled_map_by_user.get(user_id, {})
  100. )
  101. defer.returnValue(results)
  102. @cachedList(cached_method_name="get_push_rules_enabled_for_user",
  103. list_name="user_ids", num_args=1, inlineCallbacks=True)
  104. def bulk_get_push_rules_enabled(self, user_ids):
  105. if not user_ids:
  106. defer.returnValue({})
  107. results = {
  108. user_id: {}
  109. for user_id in user_ids
  110. }
  111. rows = yield self._simple_select_many_batch(
  112. table="push_rules_enable",
  113. column="user_name",
  114. iterable=user_ids,
  115. retcols=("user_name", "rule_id", "enabled",),
  116. desc="bulk_get_push_rules_enabled",
  117. )
  118. for row in rows:
  119. enabled = bool(row['enabled'])
  120. results.setdefault(row['user_name'], {})[row['rule_id']] = enabled
  121. defer.returnValue(results)
  122. @defer.inlineCallbacks
  123. def add_push_rule(
  124. self, user_id, rule_id, priority_class, conditions, actions,
  125. before=None, after=None
  126. ):
  127. conditions_json = json.dumps(conditions)
  128. actions_json = json.dumps(actions)
  129. with self._push_rules_stream_id_gen.get_next() as ids:
  130. stream_id, event_stream_ordering = ids
  131. if before or after:
  132. yield self.runInteraction(
  133. "_add_push_rule_relative_txn",
  134. self._add_push_rule_relative_txn,
  135. stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  136. conditions_json, actions_json, before, after,
  137. )
  138. else:
  139. yield self.runInteraction(
  140. "_add_push_rule_highest_priority_txn",
  141. self._add_push_rule_highest_priority_txn,
  142. stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  143. conditions_json, actions_json,
  144. )
  145. def _add_push_rule_relative_txn(
  146. self, txn, stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  147. conditions_json, actions_json, before, after
  148. ):
  149. # Lock the table since otherwise we'll have annoying races between the
  150. # SELECT here and the UPSERT below.
  151. self.database_engine.lock_table(txn, "push_rules")
  152. relative_to_rule = before or after
  153. res = self._simple_select_one_txn(
  154. txn,
  155. table="push_rules",
  156. keyvalues={
  157. "user_name": user_id,
  158. "rule_id": relative_to_rule,
  159. },
  160. retcols=["priority_class", "priority"],
  161. allow_none=True,
  162. )
  163. if not res:
  164. raise RuleNotFoundException(
  165. "before/after rule not found: %s" % (relative_to_rule,)
  166. )
  167. base_priority_class = res["priority_class"]
  168. base_rule_priority = res["priority"]
  169. if base_priority_class != priority_class:
  170. raise InconsistentRuleException(
  171. "Given priority class does not match class of relative rule"
  172. )
  173. if before:
  174. # Higher priority rules are executed first, So adding a rule before
  175. # a rule means giving it a higher priority than that rule.
  176. new_rule_priority = base_rule_priority + 1
  177. else:
  178. # We increment the priority of the existing rules to make space for
  179. # the new rule. Therefore if we want this rule to appear after
  180. # an existing rule we give it the priority of the existing rule,
  181. # and then increment the priority of the existing rule.
  182. new_rule_priority = base_rule_priority
  183. sql = (
  184. "UPDATE push_rules SET priority = priority + 1"
  185. " WHERE user_name = ? AND priority_class = ? AND priority >= ?"
  186. )
  187. txn.execute(sql, (user_id, priority_class, new_rule_priority))
  188. self._upsert_push_rule_txn(
  189. txn, stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  190. new_rule_priority, conditions_json, actions_json,
  191. )
  192. def _add_push_rule_highest_priority_txn(
  193. self, txn, stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  194. conditions_json, actions_json
  195. ):
  196. # Lock the table since otherwise we'll have annoying races between the
  197. # SELECT here and the UPSERT below.
  198. self.database_engine.lock_table(txn, "push_rules")
  199. # find the highest priority rule in that class
  200. sql = (
  201. "SELECT COUNT(*), MAX(priority) FROM push_rules"
  202. " WHERE user_name = ? and priority_class = ?"
  203. )
  204. txn.execute(sql, (user_id, priority_class))
  205. res = txn.fetchall()
  206. (how_many, highest_prio) = res[0]
  207. new_prio = 0
  208. if how_many > 0:
  209. new_prio = highest_prio + 1
  210. self._upsert_push_rule_txn(
  211. txn,
  212. stream_id, event_stream_ordering, user_id, rule_id, priority_class, new_prio,
  213. conditions_json, actions_json,
  214. )
  215. def _upsert_push_rule_txn(
  216. self, txn, stream_id, event_stream_ordering, user_id, rule_id, priority_class,
  217. priority, conditions_json, actions_json, update_stream=True
  218. ):
  219. """Specialised version of _simple_upsert_txn that picks a push_rule_id
  220. using the _push_rule_id_gen if it needs to insert the rule. It assumes
  221. that the "push_rules" table is locked"""
  222. sql = (
  223. "UPDATE push_rules"
  224. " SET priority_class = ?, priority = ?, conditions = ?, actions = ?"
  225. " WHERE user_name = ? AND rule_id = ?"
  226. )
  227. txn.execute(sql, (
  228. priority_class, priority, conditions_json, actions_json,
  229. user_id, rule_id,
  230. ))
  231. if txn.rowcount == 0:
  232. # We didn't update a row with the given rule_id so insert one
  233. push_rule_id = self._push_rule_id_gen.get_next()
  234. self._simple_insert_txn(
  235. txn,
  236. table="push_rules",
  237. values={
  238. "id": push_rule_id,
  239. "user_name": user_id,
  240. "rule_id": rule_id,
  241. "priority_class": priority_class,
  242. "priority": priority,
  243. "conditions": conditions_json,
  244. "actions": actions_json,
  245. },
  246. )
  247. if update_stream:
  248. self._insert_push_rules_update_txn(
  249. txn, stream_id, event_stream_ordering, user_id, rule_id,
  250. op="ADD",
  251. data={
  252. "priority_class": priority_class,
  253. "priority": priority,
  254. "conditions": conditions_json,
  255. "actions": actions_json,
  256. }
  257. )
  258. @defer.inlineCallbacks
  259. def delete_push_rule(self, user_id, rule_id):
  260. """
  261. Delete a push rule. Args specify the row to be deleted and can be
  262. any of the columns in the push_rule table, but below are the
  263. standard ones
  264. Args:
  265. user_id (str): The matrix ID of the push rule owner
  266. rule_id (str): The rule_id of the rule to be deleted
  267. """
  268. def delete_push_rule_txn(txn, stream_id, event_stream_ordering):
  269. self._simple_delete_one_txn(
  270. txn,
  271. "push_rules",
  272. {'user_name': user_id, 'rule_id': rule_id},
  273. )
  274. self._insert_push_rules_update_txn(
  275. txn, stream_id, event_stream_ordering, user_id, rule_id,
  276. op="DELETE"
  277. )
  278. with self._push_rules_stream_id_gen.get_next() as ids:
  279. stream_id, event_stream_ordering = ids
  280. yield self.runInteraction(
  281. "delete_push_rule", delete_push_rule_txn, stream_id, event_stream_ordering
  282. )
  283. @defer.inlineCallbacks
  284. def set_push_rule_enabled(self, user_id, rule_id, enabled):
  285. with self._push_rules_stream_id_gen.get_next() as ids:
  286. stream_id, event_stream_ordering = ids
  287. yield self.runInteraction(
  288. "_set_push_rule_enabled_txn",
  289. self._set_push_rule_enabled_txn,
  290. stream_id, event_stream_ordering, user_id, rule_id, enabled
  291. )
  292. def _set_push_rule_enabled_txn(
  293. self, txn, stream_id, event_stream_ordering, user_id, rule_id, enabled
  294. ):
  295. new_id = self._push_rules_enable_id_gen.get_next()
  296. self._simple_upsert_txn(
  297. txn,
  298. "push_rules_enable",
  299. {'user_name': user_id, 'rule_id': rule_id},
  300. {'enabled': 1 if enabled else 0},
  301. {'id': new_id},
  302. )
  303. self._insert_push_rules_update_txn(
  304. txn, stream_id, event_stream_ordering, user_id, rule_id,
  305. op="ENABLE" if enabled else "DISABLE"
  306. )
  307. @defer.inlineCallbacks
  308. def set_push_rule_actions(self, user_id, rule_id, actions, is_default_rule):
  309. actions_json = json.dumps(actions)
  310. def set_push_rule_actions_txn(txn, stream_id, event_stream_ordering):
  311. if is_default_rule:
  312. # Add a dummy rule to the rules table with the user specified
  313. # actions.
  314. priority_class = -1
  315. priority = 1
  316. self._upsert_push_rule_txn(
  317. txn, stream_id, event_stream_ordering, user_id, rule_id,
  318. priority_class, priority, "[]", actions_json,
  319. update_stream=False
  320. )
  321. else:
  322. self._simple_update_one_txn(
  323. txn,
  324. "push_rules",
  325. {'user_name': user_id, 'rule_id': rule_id},
  326. {'actions': actions_json},
  327. )
  328. self._insert_push_rules_update_txn(
  329. txn, stream_id, event_stream_ordering, user_id, rule_id,
  330. op="ACTIONS", data={"actions": actions_json}
  331. )
  332. with self._push_rules_stream_id_gen.get_next() as ids:
  333. stream_id, event_stream_ordering = ids
  334. yield self.runInteraction(
  335. "set_push_rule_actions", set_push_rule_actions_txn,
  336. stream_id, event_stream_ordering
  337. )
  338. def _insert_push_rules_update_txn(
  339. self, txn, stream_id, event_stream_ordering, user_id, rule_id, op, data=None
  340. ):
  341. values = {
  342. "stream_id": stream_id,
  343. "event_stream_ordering": event_stream_ordering,
  344. "user_id": user_id,
  345. "rule_id": rule_id,
  346. "op": op,
  347. }
  348. if data is not None:
  349. values.update(data)
  350. self._simple_insert_txn(txn, "push_rules_stream", values=values)
  351. txn.call_after(
  352. self.get_push_rules_for_user.invalidate, (user_id,)
  353. )
  354. txn.call_after(
  355. self.get_push_rules_enabled_for_user.invalidate, (user_id,)
  356. )
  357. txn.call_after(
  358. self.push_rules_stream_cache.entity_has_changed, user_id, stream_id
  359. )
  360. def get_all_push_rule_updates(self, last_id, current_id, limit):
  361. """Get all the push rules changes that have happend on the server"""
  362. def get_all_push_rule_updates_txn(txn):
  363. sql = (
  364. "SELECT stream_id, event_stream_ordering, user_id, rule_id,"
  365. " op, priority_class, priority, conditions, actions"
  366. " FROM push_rules_stream"
  367. " WHERE ? < stream_id AND stream_id <= ?"
  368. " ORDER BY stream_id ASC LIMIT ?"
  369. )
  370. txn.execute(sql, (last_id, current_id, limit))
  371. return txn.fetchall()
  372. return self.runInteraction(
  373. "get_all_push_rule_updates", get_all_push_rule_updates_txn
  374. )
  375. def get_push_rules_stream_token(self):
  376. """Get the position of the push rules stream.
  377. Returns a pair of a stream id for the push_rules stream and the
  378. room stream ordering it corresponds to."""
  379. return self._push_rules_stream_id_gen.get_current_token()
  380. def have_push_rules_changed_for_user(self, user_id, last_id):
  381. if not self.push_rules_stream_cache.has_entity_changed(user_id, last_id):
  382. return defer.succeed(False)
  383. else:
  384. def have_push_rules_changed_txn(txn):
  385. sql = (
  386. "SELECT COUNT(stream_id) FROM push_rules_stream"
  387. " WHERE user_id = ? AND ? < stream_id"
  388. )
  389. txn.execute(sql, (user_id, last_id))
  390. count, = txn.fetchone()
  391. return bool(count)
  392. return self.runInteraction(
  393. "have_push_rules_changed", have_push_rules_changed_txn
  394. )
  395. class RuleNotFoundException(Exception):
  396. pass
  397. class InconsistentRuleException(Exception):
  398. pass