push_rule.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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. import abc
  17. import logging
  18. from typing import List, Tuple, Union
  19. from canonicaljson import json
  20. from twisted.internet import defer
  21. from synapse.push.baserules import list_with_base_rules
  22. from synapse.replication.slave.storage._slaved_id_tracker import SlavedIdTracker
  23. from synapse.storage._base import SQLBaseStore, db_to_json
  24. from synapse.storage.database import DatabasePool
  25. from synapse.storage.databases.main.appservice import ApplicationServiceWorkerStore
  26. from synapse.storage.databases.main.events_worker import EventsWorkerStore
  27. from synapse.storage.databases.main.pusher import PusherWorkerStore
  28. from synapse.storage.databases.main.receipts import ReceiptsWorkerStore
  29. from synapse.storage.databases.main.roommember import RoomMemberWorkerStore
  30. from synapse.storage.push_rule import InconsistentRuleException, RuleNotFoundException
  31. from synapse.storage.util.id_generators import ChainedIdGenerator
  32. from synapse.util.caches.descriptors import cachedInlineCallbacks, cachedList
  33. from synapse.util.caches.stream_change_cache import StreamChangeCache
  34. logger = logging.getLogger(__name__)
  35. def _load_rules(rawrules, enabled_map):
  36. ruleslist = []
  37. for rawrule in rawrules:
  38. rule = dict(rawrule)
  39. rule["conditions"] = db_to_json(rawrule["conditions"])
  40. rule["actions"] = db_to_json(rawrule["actions"])
  41. rule["default"] = False
  42. ruleslist.append(rule)
  43. # We're going to be mutating this a lot, so do a deep copy
  44. rules = list(list_with_base_rules(ruleslist))
  45. for i, rule in enumerate(rules):
  46. rule_id = rule["rule_id"]
  47. if rule_id in enabled_map:
  48. if rule.get("enabled", True) != bool(enabled_map[rule_id]):
  49. # Rules are cached across users.
  50. rule = dict(rule)
  51. rule["enabled"] = bool(enabled_map[rule_id])
  52. rules[i] = rule
  53. return rules
  54. class PushRulesWorkerStore(
  55. ApplicationServiceWorkerStore,
  56. ReceiptsWorkerStore,
  57. PusherWorkerStore,
  58. RoomMemberWorkerStore,
  59. EventsWorkerStore,
  60. SQLBaseStore,
  61. ):
  62. """This is an abstract base class where subclasses must implement
  63. `get_max_push_rules_stream_id` which can be called in the initializer.
  64. """
  65. # This ABCMeta metaclass ensures that we cannot be instantiated without
  66. # the abstract methods being implemented.
  67. __metaclass__ = abc.ABCMeta
  68. def __init__(self, database: DatabasePool, db_conn, hs):
  69. super(PushRulesWorkerStore, self).__init__(database, db_conn, hs)
  70. if hs.config.worker.worker_app is None:
  71. self._push_rules_stream_id_gen = ChainedIdGenerator(
  72. self._stream_id_gen, db_conn, "push_rules_stream", "stream_id"
  73. ) # type: Union[ChainedIdGenerator, SlavedIdTracker]
  74. else:
  75. self._push_rules_stream_id_gen = SlavedIdTracker(
  76. db_conn, "push_rules_stream", "stream_id"
  77. )
  78. push_rules_prefill, push_rules_id = self.db_pool.get_cache_dict(
  79. db_conn,
  80. "push_rules_stream",
  81. entity_column="user_id",
  82. stream_column="stream_id",
  83. max_value=self.get_max_push_rules_stream_id(),
  84. )
  85. self.push_rules_stream_cache = StreamChangeCache(
  86. "PushRulesStreamChangeCache",
  87. push_rules_id,
  88. prefilled_cache=push_rules_prefill,
  89. )
  90. @abc.abstractmethod
  91. def get_max_push_rules_stream_id(self):
  92. """Get the position of the push rules stream.
  93. Returns:
  94. int
  95. """
  96. raise NotImplementedError()
  97. @cachedInlineCallbacks(max_entries=5000)
  98. def get_push_rules_for_user(self, user_id):
  99. rows = yield self.db_pool.simple_select_list(
  100. table="push_rules",
  101. keyvalues={"user_name": user_id},
  102. retcols=(
  103. "user_name",
  104. "rule_id",
  105. "priority_class",
  106. "priority",
  107. "conditions",
  108. "actions",
  109. ),
  110. desc="get_push_rules_enabled_for_user",
  111. )
  112. rows.sort(key=lambda row: (-int(row["priority_class"]), -int(row["priority"])))
  113. enabled_map = yield self.get_push_rules_enabled_for_user(user_id)
  114. rules = _load_rules(rows, enabled_map)
  115. return rules
  116. @cachedInlineCallbacks(max_entries=5000)
  117. def get_push_rules_enabled_for_user(self, user_id):
  118. results = yield self.db_pool.simple_select_list(
  119. table="push_rules_enable",
  120. keyvalues={"user_name": user_id},
  121. retcols=("user_name", "rule_id", "enabled"),
  122. desc="get_push_rules_enabled_for_user",
  123. )
  124. return {r["rule_id"]: False if r["enabled"] == 0 else True for r in results}
  125. def have_push_rules_changed_for_user(self, user_id, last_id):
  126. if not self.push_rules_stream_cache.has_entity_changed(user_id, last_id):
  127. return defer.succeed(False)
  128. else:
  129. def have_push_rules_changed_txn(txn):
  130. sql = (
  131. "SELECT COUNT(stream_id) FROM push_rules_stream"
  132. " WHERE user_id = ? AND ? < stream_id"
  133. )
  134. txn.execute(sql, (user_id, last_id))
  135. (count,) = txn.fetchone()
  136. return bool(count)
  137. return self.db_pool.runInteraction(
  138. "have_push_rules_changed", have_push_rules_changed_txn
  139. )
  140. @cachedList(
  141. cached_method_name="get_push_rules_for_user",
  142. list_name="user_ids",
  143. num_args=1,
  144. inlineCallbacks=True,
  145. )
  146. def bulk_get_push_rules(self, user_ids):
  147. if not user_ids:
  148. return {}
  149. results = {user_id: [] for user_id in user_ids}
  150. rows = yield self.db_pool.simple_select_many_batch(
  151. table="push_rules",
  152. column="user_name",
  153. iterable=user_ids,
  154. retcols=("*",),
  155. desc="bulk_get_push_rules",
  156. )
  157. rows.sort(key=lambda row: (-int(row["priority_class"]), -int(row["priority"])))
  158. for row in rows:
  159. results.setdefault(row["user_name"], []).append(row)
  160. enabled_map_by_user = yield self.bulk_get_push_rules_enabled(user_ids)
  161. for user_id, rules in results.items():
  162. results[user_id] = _load_rules(rules, enabled_map_by_user.get(user_id, {}))
  163. return results
  164. @defer.inlineCallbacks
  165. def copy_push_rule_from_room_to_room(self, new_room_id, user_id, rule):
  166. """Copy a single push rule from one room to another for a specific user.
  167. Args:
  168. new_room_id (str): ID of the new room.
  169. user_id (str): ID of user the push rule belongs to.
  170. rule (Dict): A push rule.
  171. """
  172. # Create new rule id
  173. rule_id_scope = "/".join(rule["rule_id"].split("/")[:-1])
  174. new_rule_id = rule_id_scope + "/" + new_room_id
  175. # Change room id in each condition
  176. for condition in rule.get("conditions", []):
  177. if condition.get("key") == "room_id":
  178. condition["pattern"] = new_room_id
  179. # Add the rule for the new room
  180. yield self.add_push_rule(
  181. user_id=user_id,
  182. rule_id=new_rule_id,
  183. priority_class=rule["priority_class"],
  184. conditions=rule["conditions"],
  185. actions=rule["actions"],
  186. )
  187. @defer.inlineCallbacks
  188. def copy_push_rules_from_room_to_room_for_user(
  189. self, old_room_id, new_room_id, user_id
  190. ):
  191. """Copy all of the push rules from one room to another for a specific
  192. user.
  193. Args:
  194. old_room_id (str): ID of the old room.
  195. new_room_id (str): ID of the new room.
  196. user_id (str): ID of user to copy push rules for.
  197. """
  198. # Retrieve push rules for this user
  199. user_push_rules = yield self.get_push_rules_for_user(user_id)
  200. # Get rules relating to the old room and copy them to the new room
  201. for rule in user_push_rules:
  202. conditions = rule.get("conditions", [])
  203. if any(
  204. (c.get("key") == "room_id" and c.get("pattern") == old_room_id)
  205. for c in conditions
  206. ):
  207. yield self.copy_push_rule_from_room_to_room(new_room_id, user_id, rule)
  208. @defer.inlineCallbacks
  209. def bulk_get_push_rules_for_room(self, event, context):
  210. state_group = context.state_group
  211. if not state_group:
  212. # If state_group is None it means it has yet to be assigned a
  213. # state group, i.e. we need to make sure that calls with a state_group
  214. # of None don't hit previous cached calls with a None state_group.
  215. # To do this we set the state_group to a new object as object() != object()
  216. state_group = object()
  217. current_state_ids = yield defer.ensureDeferred(context.get_current_state_ids())
  218. result = yield self._bulk_get_push_rules_for_room(
  219. event.room_id, state_group, current_state_ids, event=event
  220. )
  221. return result
  222. @cachedInlineCallbacks(num_args=2, cache_context=True)
  223. def _bulk_get_push_rules_for_room(
  224. self, room_id, state_group, current_state_ids, cache_context, event=None
  225. ):
  226. # We don't use `state_group`, its there so that we can cache based
  227. # on it. However, its important that its never None, since two current_state's
  228. # with a state_group of None are likely to be different.
  229. # See bulk_get_push_rules_for_room for how we work around this.
  230. assert state_group is not None
  231. # We also will want to generate notifs for other people in the room so
  232. # their unread countss are correct in the event stream, but to avoid
  233. # generating them for bot / AS users etc, we only do so for people who've
  234. # sent a read receipt into the room.
  235. users_in_room = yield self._get_joined_users_from_context(
  236. room_id,
  237. state_group,
  238. current_state_ids,
  239. on_invalidate=cache_context.invalidate,
  240. event=event,
  241. )
  242. # We ignore app service users for now. This is so that we don't fill
  243. # up the `get_if_users_have_pushers` cache with AS entries that we
  244. # know don't have pushers, nor even read receipts.
  245. local_users_in_room = {
  246. u
  247. for u in users_in_room
  248. if self.hs.is_mine_id(u)
  249. and not self.get_if_app_services_interested_in_user(u)
  250. }
  251. # users in the room who have pushers need to get push rules run because
  252. # that's how their pushers work
  253. if_users_with_pushers = yield self.get_if_users_have_pushers(
  254. local_users_in_room, on_invalidate=cache_context.invalidate
  255. )
  256. user_ids = {
  257. uid for uid, have_pusher in if_users_with_pushers.items() if have_pusher
  258. }
  259. users_with_receipts = yield self.get_users_with_read_receipts_in_room(
  260. room_id, on_invalidate=cache_context.invalidate
  261. )
  262. # any users with pushers must be ours: they have pushers
  263. for uid in users_with_receipts:
  264. if uid in local_users_in_room:
  265. user_ids.add(uid)
  266. rules_by_user = yield self.bulk_get_push_rules(
  267. user_ids, on_invalidate=cache_context.invalidate
  268. )
  269. rules_by_user = {k: v for k, v in rules_by_user.items() if v is not None}
  270. return rules_by_user
  271. @cachedList(
  272. cached_method_name="get_push_rules_enabled_for_user",
  273. list_name="user_ids",
  274. num_args=1,
  275. inlineCallbacks=True,
  276. )
  277. def bulk_get_push_rules_enabled(self, user_ids):
  278. if not user_ids:
  279. return {}
  280. results = {user_id: {} for user_id in user_ids}
  281. rows = yield self.db_pool.simple_select_many_batch(
  282. table="push_rules_enable",
  283. column="user_name",
  284. iterable=user_ids,
  285. retcols=("user_name", "rule_id", "enabled"),
  286. desc="bulk_get_push_rules_enabled",
  287. )
  288. for row in rows:
  289. enabled = bool(row["enabled"])
  290. results.setdefault(row["user_name"], {})[row["rule_id"]] = enabled
  291. return results
  292. async def get_all_push_rule_updates(
  293. self, instance_name: str, last_id: int, current_id: int, limit: int
  294. ) -> Tuple[List[Tuple[int, tuple]], int, bool]:
  295. """Get updates for push_rules replication stream.
  296. Args:
  297. instance_name: The writer we want to fetch updates from. Unused
  298. here since there is only ever one writer.
  299. last_id: The token to fetch updates from. Exclusive.
  300. current_id: The token to fetch updates up to. Inclusive.
  301. limit: The requested limit for the number of rows to return. The
  302. function may return more or fewer rows.
  303. Returns:
  304. A tuple consisting of: the updates, a token to use to fetch
  305. subsequent updates, and whether we returned fewer rows than exists
  306. between the requested tokens due to the limit.
  307. The token returned can be used in a subsequent call to this
  308. function to get further updatees.
  309. The updates are a list of 2-tuples of stream ID and the row data
  310. """
  311. if last_id == current_id:
  312. return [], current_id, False
  313. def get_all_push_rule_updates_txn(txn):
  314. sql = """
  315. SELECT stream_id, user_id
  316. FROM push_rules_stream
  317. WHERE ? < stream_id AND stream_id <= ?
  318. ORDER BY stream_id ASC
  319. LIMIT ?
  320. """
  321. txn.execute(sql, (last_id, current_id, limit))
  322. updates = [(stream_id, (user_id,)) for stream_id, user_id in txn]
  323. limited = False
  324. upper_bound = current_id
  325. if len(updates) == limit:
  326. limited = True
  327. upper_bound = updates[-1][0]
  328. return updates, upper_bound, limited
  329. return await self.db_pool.runInteraction(
  330. "get_all_push_rule_updates", get_all_push_rule_updates_txn
  331. )
  332. class PushRuleStore(PushRulesWorkerStore):
  333. @defer.inlineCallbacks
  334. def add_push_rule(
  335. self,
  336. user_id,
  337. rule_id,
  338. priority_class,
  339. conditions,
  340. actions,
  341. before=None,
  342. after=None,
  343. ):
  344. conditions_json = json.dumps(conditions)
  345. actions_json = json.dumps(actions)
  346. with self._push_rules_stream_id_gen.get_next() as ids:
  347. stream_id, event_stream_ordering = ids
  348. if before or after:
  349. yield self.db_pool.runInteraction(
  350. "_add_push_rule_relative_txn",
  351. self._add_push_rule_relative_txn,
  352. stream_id,
  353. event_stream_ordering,
  354. user_id,
  355. rule_id,
  356. priority_class,
  357. conditions_json,
  358. actions_json,
  359. before,
  360. after,
  361. )
  362. else:
  363. yield self.db_pool.runInteraction(
  364. "_add_push_rule_highest_priority_txn",
  365. self._add_push_rule_highest_priority_txn,
  366. stream_id,
  367. event_stream_ordering,
  368. user_id,
  369. rule_id,
  370. priority_class,
  371. conditions_json,
  372. actions_json,
  373. )
  374. def _add_push_rule_relative_txn(
  375. self,
  376. txn,
  377. stream_id,
  378. event_stream_ordering,
  379. user_id,
  380. rule_id,
  381. priority_class,
  382. conditions_json,
  383. actions_json,
  384. before,
  385. after,
  386. ):
  387. # Lock the table since otherwise we'll have annoying races between the
  388. # SELECT here and the UPSERT below.
  389. self.database_engine.lock_table(txn, "push_rules")
  390. relative_to_rule = before or after
  391. res = self.db_pool.simple_select_one_txn(
  392. txn,
  393. table="push_rules",
  394. keyvalues={"user_name": user_id, "rule_id": relative_to_rule},
  395. retcols=["priority_class", "priority"],
  396. allow_none=True,
  397. )
  398. if not res:
  399. raise RuleNotFoundException(
  400. "before/after rule not found: %s" % (relative_to_rule,)
  401. )
  402. base_priority_class = res["priority_class"]
  403. base_rule_priority = res["priority"]
  404. if base_priority_class != priority_class:
  405. raise InconsistentRuleException(
  406. "Given priority class does not match class of relative rule"
  407. )
  408. if before:
  409. # Higher priority rules are executed first, So adding a rule before
  410. # a rule means giving it a higher priority than that rule.
  411. new_rule_priority = base_rule_priority + 1
  412. else:
  413. # We increment the priority of the existing rules to make space for
  414. # the new rule. Therefore if we want this rule to appear after
  415. # an existing rule we give it the priority of the existing rule,
  416. # and then increment the priority of the existing rule.
  417. new_rule_priority = base_rule_priority
  418. sql = (
  419. "UPDATE push_rules SET priority = priority + 1"
  420. " WHERE user_name = ? AND priority_class = ? AND priority >= ?"
  421. )
  422. txn.execute(sql, (user_id, priority_class, new_rule_priority))
  423. self._upsert_push_rule_txn(
  424. txn,
  425. stream_id,
  426. event_stream_ordering,
  427. user_id,
  428. rule_id,
  429. priority_class,
  430. new_rule_priority,
  431. conditions_json,
  432. actions_json,
  433. )
  434. def _add_push_rule_highest_priority_txn(
  435. self,
  436. txn,
  437. stream_id,
  438. event_stream_ordering,
  439. user_id,
  440. rule_id,
  441. priority_class,
  442. conditions_json,
  443. actions_json,
  444. ):
  445. # Lock the table since otherwise we'll have annoying races between the
  446. # SELECT here and the UPSERT below.
  447. self.database_engine.lock_table(txn, "push_rules")
  448. # find the highest priority rule in that class
  449. sql = (
  450. "SELECT COUNT(*), MAX(priority) FROM push_rules"
  451. " WHERE user_name = ? and priority_class = ?"
  452. )
  453. txn.execute(sql, (user_id, priority_class))
  454. res = txn.fetchall()
  455. (how_many, highest_prio) = res[0]
  456. new_prio = 0
  457. if how_many > 0:
  458. new_prio = highest_prio + 1
  459. self._upsert_push_rule_txn(
  460. txn,
  461. stream_id,
  462. event_stream_ordering,
  463. user_id,
  464. rule_id,
  465. priority_class,
  466. new_prio,
  467. conditions_json,
  468. actions_json,
  469. )
  470. def _upsert_push_rule_txn(
  471. self,
  472. txn,
  473. stream_id,
  474. event_stream_ordering,
  475. user_id,
  476. rule_id,
  477. priority_class,
  478. priority,
  479. conditions_json,
  480. actions_json,
  481. update_stream=True,
  482. ):
  483. """Specialised version of simple_upsert_txn that picks a push_rule_id
  484. using the _push_rule_id_gen if it needs to insert the rule. It assumes
  485. that the "push_rules" table is locked"""
  486. sql = (
  487. "UPDATE push_rules"
  488. " SET priority_class = ?, priority = ?, conditions = ?, actions = ?"
  489. " WHERE user_name = ? AND rule_id = ?"
  490. )
  491. txn.execute(
  492. sql,
  493. (priority_class, priority, conditions_json, actions_json, user_id, rule_id),
  494. )
  495. if txn.rowcount == 0:
  496. # We didn't update a row with the given rule_id so insert one
  497. push_rule_id = self._push_rule_id_gen.get_next()
  498. self.db_pool.simple_insert_txn(
  499. txn,
  500. table="push_rules",
  501. values={
  502. "id": push_rule_id,
  503. "user_name": user_id,
  504. "rule_id": rule_id,
  505. "priority_class": priority_class,
  506. "priority": priority,
  507. "conditions": conditions_json,
  508. "actions": actions_json,
  509. },
  510. )
  511. if update_stream:
  512. self._insert_push_rules_update_txn(
  513. txn,
  514. stream_id,
  515. event_stream_ordering,
  516. user_id,
  517. rule_id,
  518. op="ADD",
  519. data={
  520. "priority_class": priority_class,
  521. "priority": priority,
  522. "conditions": conditions_json,
  523. "actions": actions_json,
  524. },
  525. )
  526. @defer.inlineCallbacks
  527. def delete_push_rule(self, user_id, rule_id):
  528. """
  529. Delete a push rule. Args specify the row to be deleted and can be
  530. any of the columns in the push_rule table, but below are the
  531. standard ones
  532. Args:
  533. user_id (str): The matrix ID of the push rule owner
  534. rule_id (str): The rule_id of the rule to be deleted
  535. """
  536. def delete_push_rule_txn(txn, stream_id, event_stream_ordering):
  537. self.db_pool.simple_delete_one_txn(
  538. txn, "push_rules", {"user_name": user_id, "rule_id": rule_id}
  539. )
  540. self._insert_push_rules_update_txn(
  541. txn, stream_id, event_stream_ordering, user_id, rule_id, op="DELETE"
  542. )
  543. with self._push_rules_stream_id_gen.get_next() as ids:
  544. stream_id, event_stream_ordering = ids
  545. yield self.db_pool.runInteraction(
  546. "delete_push_rule",
  547. delete_push_rule_txn,
  548. stream_id,
  549. event_stream_ordering,
  550. )
  551. @defer.inlineCallbacks
  552. def set_push_rule_enabled(self, user_id, rule_id, enabled):
  553. with self._push_rules_stream_id_gen.get_next() as ids:
  554. stream_id, event_stream_ordering = ids
  555. yield self.db_pool.runInteraction(
  556. "_set_push_rule_enabled_txn",
  557. self._set_push_rule_enabled_txn,
  558. stream_id,
  559. event_stream_ordering,
  560. user_id,
  561. rule_id,
  562. enabled,
  563. )
  564. def _set_push_rule_enabled_txn(
  565. self, txn, stream_id, event_stream_ordering, user_id, rule_id, enabled
  566. ):
  567. new_id = self._push_rules_enable_id_gen.get_next()
  568. self.db_pool.simple_upsert_txn(
  569. txn,
  570. "push_rules_enable",
  571. {"user_name": user_id, "rule_id": rule_id},
  572. {"enabled": 1 if enabled else 0},
  573. {"id": new_id},
  574. )
  575. self._insert_push_rules_update_txn(
  576. txn,
  577. stream_id,
  578. event_stream_ordering,
  579. user_id,
  580. rule_id,
  581. op="ENABLE" if enabled else "DISABLE",
  582. )
  583. @defer.inlineCallbacks
  584. def set_push_rule_actions(self, user_id, rule_id, actions, is_default_rule):
  585. actions_json = json.dumps(actions)
  586. def set_push_rule_actions_txn(txn, stream_id, event_stream_ordering):
  587. if is_default_rule:
  588. # Add a dummy rule to the rules table with the user specified
  589. # actions.
  590. priority_class = -1
  591. priority = 1
  592. self._upsert_push_rule_txn(
  593. txn,
  594. stream_id,
  595. event_stream_ordering,
  596. user_id,
  597. rule_id,
  598. priority_class,
  599. priority,
  600. "[]",
  601. actions_json,
  602. update_stream=False,
  603. )
  604. else:
  605. self.db_pool.simple_update_one_txn(
  606. txn,
  607. "push_rules",
  608. {"user_name": user_id, "rule_id": rule_id},
  609. {"actions": actions_json},
  610. )
  611. self._insert_push_rules_update_txn(
  612. txn,
  613. stream_id,
  614. event_stream_ordering,
  615. user_id,
  616. rule_id,
  617. op="ACTIONS",
  618. data={"actions": actions_json},
  619. )
  620. with self._push_rules_stream_id_gen.get_next() as ids:
  621. stream_id, event_stream_ordering = ids
  622. yield self.db_pool.runInteraction(
  623. "set_push_rule_actions",
  624. set_push_rule_actions_txn,
  625. stream_id,
  626. event_stream_ordering,
  627. )
  628. def _insert_push_rules_update_txn(
  629. self, txn, stream_id, event_stream_ordering, user_id, rule_id, op, data=None
  630. ):
  631. values = {
  632. "stream_id": stream_id,
  633. "event_stream_ordering": event_stream_ordering,
  634. "user_id": user_id,
  635. "rule_id": rule_id,
  636. "op": op,
  637. }
  638. if data is not None:
  639. values.update(data)
  640. self.db_pool.simple_insert_txn(txn, "push_rules_stream", values=values)
  641. txn.call_after(self.get_push_rules_for_user.invalidate, (user_id,))
  642. txn.call_after(self.get_push_rules_enabled_for_user.invalidate, (user_id,))
  643. txn.call_after(
  644. self.push_rules_stream_cache.entity_has_changed, user_id, stream_id
  645. )
  646. def get_push_rules_stream_token(self):
  647. """Get the position of the push rules stream.
  648. Returns a pair of a stream id for the push_rules stream and the
  649. room stream ordering it corresponds to."""
  650. return self._push_rules_stream_id_gen.get_current_token()
  651. def get_max_push_rules_stream_id(self):
  652. return self.get_push_rules_stream_token()[0]