bulk_push_rule_evaluator.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. )
  33. push_rules_state_size_counter = Counter(
  34. "synapse_push_bulk_push_rule_evaluator_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 = register_cache(
  39. "cache",
  40. "push_rules_delta_state_cache_metric",
  41. cache=[], # Meaningless size, as this isn't a cache that stores values
  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 = register_cache(
  52. "cache",
  53. "room_push_rule_cache",
  54. cache=[], # Meaningless size, as this isn't a cache that stores values
  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. return 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,
  89. room_id,
  90. self._get_rules_for_room.cache,
  91. self.room_push_rule_cache_metrics,
  92. )
  93. @defer.inlineCallbacks
  94. def _get_power_levels_and_sender_level(self, event, context):
  95. prev_state_ids = yield context.get_prev_state_ids(self.store)
  96. pl_event_id = prev_state_ids.get(POWER_KEY)
  97. if pl_event_id:
  98. # fastpath: if there's a power level event, that's all we need, and
  99. # not having a power level event is an extreme edge case
  100. pl_event = yield self.store.get_event(pl_event_id)
  101. auth_events = {POWER_KEY: pl_event}
  102. else:
  103. auth_events_ids = yield self.auth.compute_auth_events(
  104. event, prev_state_ids, for_verification=False
  105. )
  106. auth_events = yield self.store.get_events(auth_events_ids)
  107. auth_events = {(e.type, e.state_key): e for e in itervalues(auth_events)}
  108. sender_level = get_user_power_level(event.sender, auth_events)
  109. pl_event = auth_events.get(POWER_KEY)
  110. return pl_event.content if pl_event else {}, sender_level
  111. @defer.inlineCallbacks
  112. def action_for_event_by_user(self, event, context):
  113. """Given an event and context, evaluate the push rules and insert the
  114. results into the event_push_actions_staging table.
  115. Returns:
  116. Deferred
  117. """
  118. rules_by_user = yield self._get_rules_for_event(event, context)
  119. actions_by_user = {}
  120. room_members = yield self.store.get_joined_users_from_context(event, context)
  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(event.event_id, actions_by_user)
  160. def _condition_checker(evaluator, conditions, uid, display_name, cache):
  161. for cond in conditions:
  162. _id = cond.get("_id", None)
  163. if _id:
  164. res = cache.get(_id, None)
  165. if res is False:
  166. return False
  167. elif res is True:
  168. continue
  169. res = evaluator.matches(cond, uid, display_name)
  170. if _id:
  171. cache[_id] = bool(res)
  172. if not res:
  173. return False
  174. return True
  175. class RulesForRoom(object):
  176. """Caches push rules for users in a room.
  177. This efficiently handles users joining/leaving the room by not invalidating
  178. the entire cache for the room.
  179. """
  180. def __init__(self, hs, room_id, rules_for_room_cache, room_push_rule_cache_metrics):
  181. """
  182. Args:
  183. hs (HomeServer)
  184. room_id (str)
  185. rules_for_room_cache(Cache): The cache object that caches these
  186. RoomsForUser objects.
  187. room_push_rule_cache_metrics (CacheMetric)
  188. """
  189. self.room_id = room_id
  190. self.is_mine_id = hs.is_mine_id
  191. self.store = hs.get_datastore()
  192. self.room_push_rule_cache_metrics = room_push_rule_cache_metrics
  193. self.linearizer = Linearizer(name="rules_for_room")
  194. self.member_map = {} # event_id -> (user_id, state)
  195. self.rules_by_user = {} # user_id -> rules
  196. # The last state group we updated the caches for. If the state_group of
  197. # a new event comes along, we know that we can just return the cached
  198. # result.
  199. # On invalidation of the rules themselves (if the user changes them),
  200. # we invalidate everything and set state_group to `object()`
  201. self.state_group = object()
  202. # A sequence number to keep track of when we're allowed to update the
  203. # cache. We bump the sequence number when we invalidate the cache. If
  204. # the sequence number changes while we're calculating stuff we should
  205. # not update the cache with it.
  206. self.sequence = 0
  207. # A cache of user_ids that we *know* aren't interesting, e.g. user_ids
  208. # owned by AS's, or remote users, etc. (I.e. users we will never need to
  209. # calculate push for)
  210. # These never need to be invalidated as we will never set up push for
  211. # them.
  212. self.uninteresting_user_set = set()
  213. # We need to be clever on the invalidating caches callbacks, as
  214. # otherwise the invalidation callback holds a reference to the object,
  215. # potentially causing it to leak.
  216. # To get around this we pass a function that on invalidations looks ups
  217. # the RoomsForUser entry in the cache, rather than keeping a reference
  218. # to self around in the callback.
  219. self.invalidate_all_cb = _Invalidation(rules_for_room_cache, room_id)
  220. @defer.inlineCallbacks
  221. def get_rules(self, event, context):
  222. """Given an event context return the rules for all users who are
  223. currently in the room.
  224. """
  225. state_group = context.state_group
  226. if state_group and self.state_group == state_group:
  227. logger.debug("Using cached rules for %r", self.room_id)
  228. self.room_push_rule_cache_metrics.inc_hits()
  229. return self.rules_by_user
  230. with (yield self.linearizer.queue(())):
  231. if state_group and self.state_group == state_group:
  232. logger.debug("Using cached rules for %r", self.room_id)
  233. self.room_push_rule_cache_metrics.inc_hits()
  234. return self.rules_by_user
  235. self.room_push_rule_cache_metrics.inc_misses()
  236. ret_rules_by_user = {}
  237. missing_member_event_ids = {}
  238. if state_group and self.state_group == context.prev_group:
  239. # If we have a simple delta then we can reuse most of the previous
  240. # results.
  241. ret_rules_by_user = self.rules_by_user
  242. current_state_ids = context.delta_ids
  243. push_rules_delta_state_cache_metric.inc_hits()
  244. else:
  245. current_state_ids = yield context.get_current_state_ids(self.store)
  246. push_rules_delta_state_cache_metric.inc_misses()
  247. push_rules_state_size_counter.inc(len(current_state_ids))
  248. logger.debug(
  249. "Looking for member changes in %r %r", state_group, current_state_ids
  250. )
  251. # Loop through to see which member events we've seen and have rules
  252. # for and which we need to fetch
  253. for key in current_state_ids:
  254. typ, user_id = key
  255. if typ != EventTypes.Member:
  256. continue
  257. if user_id in self.uninteresting_user_set:
  258. continue
  259. if not self.is_mine_id(user_id):
  260. self.uninteresting_user_set.add(user_id)
  261. continue
  262. if self.store.get_if_app_services_interested_in_user(user_id):
  263. self.uninteresting_user_set.add(user_id)
  264. continue
  265. event_id = current_state_ids[key]
  266. res = self.member_map.get(event_id, None)
  267. if res:
  268. user_id, state = res
  269. if state == Membership.JOIN:
  270. rules = self.rules_by_user.get(user_id, None)
  271. if rules:
  272. ret_rules_by_user[user_id] = rules
  273. continue
  274. # If a user has left a room we remove their push rule. If they
  275. # joined then we readd it later in _update_rules_with_member_event_ids
  276. ret_rules_by_user.pop(user_id, None)
  277. missing_member_event_ids[user_id] = event_id
  278. if missing_member_event_ids:
  279. # If we have some memebr events we haven't seen, look them up
  280. # and fetch push rules for them if appropriate.
  281. logger.debug("Found new member events %r", missing_member_event_ids)
  282. yield self._update_rules_with_member_event_ids(
  283. ret_rules_by_user, missing_member_event_ids, state_group, event
  284. )
  285. else:
  286. # The push rules didn't change but lets update the cache anyway
  287. self.update_cache(
  288. self.sequence,
  289. members={}, # There were no membership changes
  290. rules_by_user=ret_rules_by_user,
  291. state_group=state_group,
  292. )
  293. if logger.isEnabledFor(logging.DEBUG):
  294. logger.debug(
  295. "Returning push rules for %r %r", self.room_id, ret_rules_by_user.keys()
  296. )
  297. return ret_rules_by_user
  298. @defer.inlineCallbacks
  299. def _update_rules_with_member_event_ids(
  300. self, ret_rules_by_user, member_event_ids, state_group, event
  301. ):
  302. """Update the partially filled rules_by_user dict by fetching rules for
  303. any newly joined users in the `member_event_ids` list.
  304. Args:
  305. ret_rules_by_user (dict): Partiallly filled dict of push rules. Gets
  306. updated with any new rules.
  307. member_event_ids (list): List of event ids for membership events that
  308. have happened since the last time we filled rules_by_user
  309. state_group: The state group we are currently computing push rules
  310. for. Used when updating the cache.
  311. """
  312. sequence = self.sequence
  313. rows = yield self.store._simple_select_many_batch(
  314. table="room_memberships",
  315. column="event_id",
  316. iterable=member_event_ids.values(),
  317. retcols=("user_id", "membership", "event_id"),
  318. keyvalues={},
  319. batch_size=500,
  320. desc="_get_rules_for_member_event_ids",
  321. )
  322. members = {row["event_id"]: (row["user_id"], row["membership"]) for row in rows}
  323. # If the event is a join event then it will be in current state evnts
  324. # map but not in the DB, so we have to explicitly insert it.
  325. if event.type == EventTypes.Member:
  326. for event_id in itervalues(member_event_ids):
  327. if event_id == event.event_id:
  328. members[event_id] = (event.state_key, event.membership)
  329. if logger.isEnabledFor(logging.DEBUG):
  330. logger.debug("Found members %r: %r", self.room_id, members.values())
  331. interested_in_user_ids = set(
  332. user_id
  333. for user_id, membership in itervalues(members)
  334. if membership == Membership.JOIN
  335. )
  336. logger.debug("Joined: %r", interested_in_user_ids)
  337. if_users_with_pushers = yield self.store.get_if_users_have_pushers(
  338. interested_in_user_ids, on_invalidate=self.invalidate_all_cb
  339. )
  340. user_ids = set(
  341. uid for uid, have_pusher in iteritems(if_users_with_pushers) if have_pusher
  342. )
  343. logger.debug("With pushers: %r", user_ids)
  344. users_with_receipts = yield self.store.get_users_with_read_receipts_in_room(
  345. self.room_id, on_invalidate=self.invalidate_all_cb
  346. )
  347. logger.debug("With receipts: %r", users_with_receipts)
  348. # any users with pushers must be ours: they have pushers
  349. for uid in users_with_receipts:
  350. if uid in interested_in_user_ids:
  351. user_ids.add(uid)
  352. rules_by_user = yield self.store.bulk_get_push_rules(
  353. user_ids, on_invalidate=self.invalidate_all_cb
  354. )
  355. ret_rules_by_user.update(
  356. item for item in iteritems(rules_by_user) if item[0] is not None
  357. )
  358. self.update_cache(sequence, members, ret_rules_by_user, state_group)
  359. def invalidate_all(self):
  360. # Note: Don't hand this function directly to an invalidation callback
  361. # as it keeps a reference to self and will stop this instance from being
  362. # GC'd if it gets dropped from the rules_to_user cache. Instead use
  363. # `self.invalidate_all_cb`
  364. logger.debug("Invalidating RulesForRoom for %r", self.room_id)
  365. self.sequence += 1
  366. self.state_group = object()
  367. self.member_map = {}
  368. self.rules_by_user = {}
  369. push_rules_invalidation_counter.inc()
  370. def update_cache(self, sequence, members, rules_by_user, state_group):
  371. if sequence == self.sequence:
  372. self.member_map.update(members)
  373. self.rules_by_user = rules_by_user
  374. self.state_group = state_group
  375. class _Invalidation(namedtuple("_Invalidation", ("cache", "room_id"))):
  376. # We rely on _CacheContext implementing __eq__ and __hash__ sensibly,
  377. # which namedtuple does for us (i.e. two _CacheContext are the same if
  378. # their caches and keys match). This is important in particular to
  379. # dedupe when we add callbacks to lru cache nodes, otherwise the number
  380. # of callbacks would grow.
  381. def __call__(self):
  382. rules = self.cache.get(self.room_id, None, update_metrics=False)
  383. if rules:
  384. rules.invalidate_all()