bulk_push_rule_evaluator.py 18 KB

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