bulk_push_rule_evaluator.py 18 KB

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