bulk_push_rule_evaluator.py 19 KB

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