bulk_push_rule_evaluator.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015 OpenMarket Ltd
  3. # Copyright 2017 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 logging
  17. from twisted.internet import defer
  18. from .push_rule_evaluator import PushRuleEvaluatorForEvent
  19. from synapse.event_auth import get_user_power_level
  20. from synapse.api.constants import EventTypes, Membership
  21. from synapse.metrics import get_metrics_for
  22. from synapse.util.caches import metrics as cache_metrics
  23. from synapse.util.caches.descriptors import cached
  24. from synapse.util.async import Linearizer
  25. from synapse.state import POWER_KEY
  26. from collections import namedtuple
  27. logger = logging.getLogger(__name__)
  28. rules_by_room = {}
  29. push_metrics = get_metrics_for(__name__)
  30. push_rules_invalidation_counter = push_metrics.register_counter(
  31. "push_rules_invalidation_counter"
  32. )
  33. push_rules_state_size_counter = push_metrics.register_counter(
  34. "push_rules_state_size_counter"
  35. )
  36. # Measures whether we use the fast path of using state deltas, or if we have to
  37. # recalculate from scratch
  38. push_rules_delta_state_cache_metric = cache_metrics.register_cache(
  39. "cache",
  40. size_callback=lambda: 0, # Meaningless size, as this isn't a cache that stores values
  41. cache_name="push_rules_delta_state_cache_metric",
  42. )
  43. class BulkPushRuleEvaluator(object):
  44. """Calculates the outcome of push rules for an event for all users in the
  45. room at once.
  46. """
  47. def __init__(self, hs):
  48. self.hs = hs
  49. self.store = hs.get_datastore()
  50. self.auth = hs.get_auth()
  51. self.room_push_rule_cache_metrics = cache_metrics.register_cache(
  52. "cache",
  53. size_callback=lambda: 0, # There's not good value for this
  54. cache_name="room_push_rule_cache",
  55. )
  56. @defer.inlineCallbacks
  57. def _get_rules_for_event(self, event, context):
  58. """This gets the rules for all users in the room at the time of the event,
  59. as well as the push rules for the invitee if the event is an invite.
  60. Returns:
  61. dict of user_id -> push_rules
  62. """
  63. room_id = event.room_id
  64. rules_for_room = self._get_rules_for_room(room_id)
  65. rules_by_user = yield rules_for_room.get_rules(event, context)
  66. # if this event is an invite event, we may need to run rules for the user
  67. # who's been invited, otherwise they won't get told they've been invited
  68. if event.type == 'm.room.member' and event.content['membership'] == 'invite':
  69. invited = event.state_key
  70. if invited and self.hs.is_mine_id(invited):
  71. has_pusher = yield self.store.user_has_pusher(invited)
  72. if has_pusher:
  73. rules_by_user = dict(rules_by_user)
  74. rules_by_user[invited] = yield self.store.get_push_rules_for_user(
  75. invited
  76. )
  77. defer.returnValue(rules_by_user)
  78. @cached()
  79. def _get_rules_for_room(self, room_id):
  80. """Get the current RulesForRoom object for the given room id
  81. Returns:
  82. RulesForRoom
  83. """
  84. # It's important that RulesForRoom gets added to self._get_rules_for_room.cache
  85. # before any lookup methods get called on it as otherwise there may be
  86. # a race if invalidate_all gets called (which assumes its in the cache)
  87. return RulesForRoom(
  88. self.hs, room_id, self._get_rules_for_room.cache,
  89. self.room_push_rule_cache_metrics,
  90. )
  91. @defer.inlineCallbacks
  92. def _get_power_levels_and_sender_level(self, event, context):
  93. pl_event_id = context.prev_state_ids.get(POWER_KEY)
  94. if pl_event_id:
  95. # fastpath: if there's a power level event, that's all we need, and
  96. # not having a power level event is an extreme edge case
  97. pl_event = yield self.store.get_event(pl_event_id)
  98. auth_events = {POWER_KEY: pl_event}
  99. else:
  100. auth_events_ids = yield self.auth.compute_auth_events(
  101. event, context.prev_state_ids, for_verification=False,
  102. )
  103. auth_events = yield self.store.get_events(auth_events_ids)
  104. auth_events = {
  105. (e.type, e.state_key): e for e in auth_events.itervalues()
  106. }
  107. sender_level = get_user_power_level(event.sender, auth_events)
  108. pl_event = auth_events.get(POWER_KEY)
  109. defer.returnValue((pl_event.content if pl_event else {}, sender_level))
  110. @defer.inlineCallbacks
  111. def action_for_event_by_user(self, event, context):
  112. """Given an event and context, evaluate the push rules and insert the
  113. results into the event_push_actions_staging table.
  114. Returns:
  115. Deferred
  116. """
  117. rules_by_user = yield self._get_rules_for_event(event, context)
  118. actions_by_user = {}
  119. room_members = yield self.store.get_joined_users_from_context(
  120. event, context
  121. )
  122. (power_levels, sender_power_level) = (
  123. yield self._get_power_levels_and_sender_level(event, context)
  124. )
  125. evaluator = PushRuleEvaluatorForEvent(
  126. event, len(room_members), sender_power_level, power_levels,
  127. )
  128. condition_cache = {}
  129. for uid, rules in rules_by_user.iteritems():
  130. if event.sender == uid:
  131. continue
  132. if not event.is_state():
  133. is_ignored = yield self.store.is_ignored_by(event.sender, uid)
  134. if is_ignored:
  135. continue
  136. display_name = None
  137. profile_info = room_members.get(uid)
  138. if profile_info:
  139. display_name = profile_info.display_name
  140. if not display_name:
  141. # Handle the case where we are pushing a membership event to
  142. # that user, as they might not be already joined.
  143. if event.type == EventTypes.Member and event.state_key == uid:
  144. display_name = event.content.get("displayname", None)
  145. for rule in rules:
  146. if 'enabled' in rule and not rule['enabled']:
  147. continue
  148. matches = _condition_checker(
  149. evaluator, rule['conditions'], uid, display_name, condition_cache
  150. )
  151. if matches:
  152. actions = [x for x in rule['actions'] if x != 'dont_notify']
  153. if actions and 'notify' in actions:
  154. # Push rules say we should notify the user of this event
  155. actions_by_user[uid] = actions
  156. break
  157. # Mark in the DB staging area the push actions for users who should be
  158. # notified for this event. (This will then get handled when we persist
  159. # the event)
  160. yield self.store.add_push_actions_to_staging(
  161. event.event_id, actions_by_user,
  162. )
  163. def _condition_checker(evaluator, conditions, uid, display_name, cache):
  164. for cond in conditions:
  165. _id = cond.get("_id", None)
  166. if _id:
  167. res = cache.get(_id, None)
  168. if res is False:
  169. return False
  170. elif res is True:
  171. continue
  172. res = evaluator.matches(cond, uid, display_name)
  173. if _id:
  174. cache[_id] = bool(res)
  175. if not res:
  176. return False
  177. return True
  178. class RulesForRoom(object):
  179. """Caches push rules for users in a room.
  180. This efficiently handles users joining/leaving the room by not invalidating
  181. the entire cache for the room.
  182. """
  183. def __init__(self, hs, room_id, rules_for_room_cache, room_push_rule_cache_metrics):
  184. """
  185. Args:
  186. hs (HomeServer)
  187. room_id (str)
  188. rules_for_room_cache(Cache): The cache object that caches these
  189. RoomsForUser objects.
  190. room_push_rule_cache_metrics (CacheMetric)
  191. """
  192. self.room_id = room_id
  193. self.is_mine_id = hs.is_mine_id
  194. self.store = hs.get_datastore()
  195. self.room_push_rule_cache_metrics = room_push_rule_cache_metrics
  196. self.linearizer = Linearizer(name="rules_for_room")
  197. self.member_map = {} # event_id -> (user_id, state)
  198. self.rules_by_user = {} # user_id -> rules
  199. # The last state group we updated the caches for. If the state_group of
  200. # a new event comes along, we know that we can just return the cached
  201. # result.
  202. # On invalidation of the rules themselves (if the user changes them),
  203. # we invalidate everything and set state_group to `object()`
  204. self.state_group = object()
  205. # A sequence number to keep track of when we're allowed to update the
  206. # cache. We bump the sequence number when we invalidate the cache. If
  207. # the sequence number changes while we're calculating stuff we should
  208. # not update the cache with it.
  209. self.sequence = 0
  210. # A cache of user_ids that we *know* aren't interesting, e.g. user_ids
  211. # owned by AS's, or remote users, etc. (I.e. users we will never need to
  212. # calculate push for)
  213. # These never need to be invalidated as we will never set up push for
  214. # them.
  215. self.uninteresting_user_set = set()
  216. # We need to be clever on the invalidating caches callbacks, as
  217. # otherwise the invalidation callback holds a reference to the object,
  218. # potentially causing it to leak.
  219. # To get around this we pass a function that on invalidations looks ups
  220. # the RoomsForUser entry in the cache, rather than keeping a reference
  221. # to self around in the callback.
  222. self.invalidate_all_cb = _Invalidation(rules_for_room_cache, room_id)
  223. @defer.inlineCallbacks
  224. def get_rules(self, event, context):
  225. """Given an event context return the rules for all users who are
  226. currently in the room.
  227. """
  228. state_group = context.state_group
  229. if state_group and self.state_group == state_group:
  230. logger.debug("Using cached rules for %r", self.room_id)
  231. self.room_push_rule_cache_metrics.inc_hits()
  232. defer.returnValue(self.rules_by_user)
  233. with (yield self.linearizer.queue(())):
  234. if state_group and self.state_group == state_group:
  235. logger.debug("Using cached rules for %r", self.room_id)
  236. self.room_push_rule_cache_metrics.inc_hits()
  237. defer.returnValue(self.rules_by_user)
  238. self.room_push_rule_cache_metrics.inc_misses()
  239. ret_rules_by_user = {}
  240. missing_member_event_ids = {}
  241. if state_group and self.state_group == context.prev_group:
  242. # If we have a simple delta then we can reuse most of the previous
  243. # results.
  244. ret_rules_by_user = self.rules_by_user
  245. current_state_ids = context.delta_ids
  246. push_rules_delta_state_cache_metric.inc_hits()
  247. else:
  248. current_state_ids = context.current_state_ids
  249. push_rules_delta_state_cache_metric.inc_misses()
  250. push_rules_state_size_counter.inc_by(len(current_state_ids))
  251. logger.debug(
  252. "Looking for member changes in %r %r", state_group, current_state_ids
  253. )
  254. # Loop through to see which member events we've seen and have rules
  255. # for and which we need to fetch
  256. for key in current_state_ids:
  257. typ, user_id = key
  258. if typ != EventTypes.Member:
  259. continue
  260. if user_id in self.uninteresting_user_set:
  261. continue
  262. if not self.is_mine_id(user_id):
  263. self.uninteresting_user_set.add(user_id)
  264. continue
  265. if self.store.get_if_app_services_interested_in_user(user_id):
  266. self.uninteresting_user_set.add(user_id)
  267. continue
  268. event_id = current_state_ids[key]
  269. res = self.member_map.get(event_id, None)
  270. if res:
  271. user_id, state = res
  272. if state == Membership.JOIN:
  273. rules = self.rules_by_user.get(user_id, None)
  274. if rules:
  275. ret_rules_by_user[user_id] = rules
  276. continue
  277. # If a user has left a room we remove their push rule. If they
  278. # joined then we readd it later in _update_rules_with_member_event_ids
  279. ret_rules_by_user.pop(user_id, None)
  280. missing_member_event_ids[user_id] = event_id
  281. if missing_member_event_ids:
  282. # If we have some memebr events we haven't seen, look them up
  283. # and fetch push rules for them if appropriate.
  284. logger.debug("Found new member events %r", missing_member_event_ids)
  285. yield self._update_rules_with_member_event_ids(
  286. ret_rules_by_user, missing_member_event_ids, state_group, event
  287. )
  288. else:
  289. # The push rules didn't change but lets update the cache anyway
  290. self.update_cache(
  291. self.sequence,
  292. members={}, # There were no membership changes
  293. rules_by_user=ret_rules_by_user,
  294. state_group=state_group
  295. )
  296. if logger.isEnabledFor(logging.DEBUG):
  297. logger.debug(
  298. "Returning push rules for %r %r",
  299. self.room_id, ret_rules_by_user.keys(),
  300. )
  301. defer.returnValue(ret_rules_by_user)
  302. @defer.inlineCallbacks
  303. def _update_rules_with_member_event_ids(self, ret_rules_by_user, member_event_ids,
  304. state_group, event):
  305. """Update the partially filled rules_by_user dict by fetching rules for
  306. any newly joined users in the `member_event_ids` list.
  307. Args:
  308. ret_rules_by_user (dict): Partiallly filled dict of push rules. Gets
  309. updated with any new rules.
  310. member_event_ids (list): List of event ids for membership events that
  311. have happened since the last time we filled rules_by_user
  312. state_group: The state group we are currently computing push rules
  313. for. Used when updating the cache.
  314. """
  315. sequence = self.sequence
  316. rows = yield self.store._simple_select_many_batch(
  317. table="room_memberships",
  318. column="event_id",
  319. iterable=member_event_ids.values(),
  320. retcols=('user_id', 'membership', 'event_id'),
  321. keyvalues={},
  322. batch_size=500,
  323. desc="_get_rules_for_member_event_ids",
  324. )
  325. members = {
  326. row["event_id"]: (row["user_id"], row["membership"])
  327. for row in rows
  328. }
  329. # If the event is a join event then it will be in current state evnts
  330. # map but not in the DB, so we have to explicitly insert it.
  331. if event.type == EventTypes.Member:
  332. for event_id in member_event_ids.itervalues():
  333. if event_id == event.event_id:
  334. members[event_id] = (event.state_key, event.membership)
  335. if logger.isEnabledFor(logging.DEBUG):
  336. logger.debug("Found members %r: %r", self.room_id, members.values())
  337. interested_in_user_ids = set(
  338. user_id for user_id, membership in members.itervalues()
  339. if membership == Membership.JOIN
  340. )
  341. logger.debug("Joined: %r", interested_in_user_ids)
  342. if_users_with_pushers = yield self.store.get_if_users_have_pushers(
  343. interested_in_user_ids,
  344. on_invalidate=self.invalidate_all_cb,
  345. )
  346. user_ids = set(
  347. uid for uid, have_pusher in if_users_with_pushers.iteritems() if have_pusher
  348. )
  349. logger.debug("With pushers: %r", user_ids)
  350. users_with_receipts = yield self.store.get_users_with_read_receipts_in_room(
  351. self.room_id, on_invalidate=self.invalidate_all_cb,
  352. )
  353. logger.debug("With receipts: %r", users_with_receipts)
  354. # any users with pushers must be ours: they have pushers
  355. for uid in users_with_receipts:
  356. if uid in interested_in_user_ids:
  357. user_ids.add(uid)
  358. rules_by_user = yield self.store.bulk_get_push_rules(
  359. user_ids, on_invalidate=self.invalidate_all_cb,
  360. )
  361. ret_rules_by_user.update(
  362. item for item in rules_by_user.iteritems() if item[0] is not None
  363. )
  364. self.update_cache(sequence, members, ret_rules_by_user, state_group)
  365. def invalidate_all(self):
  366. # Note: Don't hand this function directly to an invalidation callback
  367. # as it keeps a reference to self and will stop this instance from being
  368. # GC'd if it gets dropped from the rules_to_user cache. Instead use
  369. # `self.invalidate_all_cb`
  370. logger.debug("Invalidating RulesForRoom for %r", self.room_id)
  371. self.sequence += 1
  372. self.state_group = object()
  373. self.member_map = {}
  374. self.rules_by_user = {}
  375. push_rules_invalidation_counter.inc()
  376. def update_cache(self, sequence, members, rules_by_user, state_group):
  377. if sequence == self.sequence:
  378. self.member_map.update(members)
  379. self.rules_by_user = rules_by_user
  380. self.state_group = state_group
  381. class _Invalidation(namedtuple("_Invalidation", ("cache", "room_id"))):
  382. # We rely on _CacheContext implementing __eq__ and __hash__ sensibly,
  383. # which namedtuple does for us (i.e. two _CacheContext are the same if
  384. # their caches and keys match). This is important in particular to
  385. # dedupe when we add callbacks to lru cache nodes, otherwise the number
  386. # of callbacks would grow.
  387. def __call__(self):
  388. rules = self.cache.get(self.room_id, None, update_metrics=False)
  389. if rules:
  390. rules.invalidate_all()