push_rule.py 15 KB

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