bulk_push_rule_evaluator.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. # Copyright 2015 OpenMarket Ltd
  2. # Copyright 2017 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import (
  17. TYPE_CHECKING,
  18. Any,
  19. Collection,
  20. Dict,
  21. List,
  22. Mapping,
  23. Optional,
  24. Tuple,
  25. Union,
  26. )
  27. from prometheus_client import Counter
  28. from synapse.api.constants import MAIN_TIMELINE, EventTypes, Membership, RelationTypes
  29. from synapse.api.room_versions import PushRuleRoomFlag, RoomVersion
  30. from synapse.event_auth import auth_types_for_event, get_user_power_level
  31. from synapse.events import EventBase, relation_from_event
  32. from synapse.events.snapshot import EventContext
  33. from synapse.state import POWER_KEY
  34. from synapse.storage.databases.main.roommember import EventIdMembership
  35. from synapse.storage.state import StateFilter
  36. from synapse.synapse_rust.push import FilteredPushRules, PushRuleEvaluator
  37. from synapse.util.caches import register_cache
  38. from synapse.util.metrics import measure_func
  39. from synapse.visibility import filter_event_for_clients_with_state
  40. if TYPE_CHECKING:
  41. from synapse.server import HomeServer
  42. logger = logging.getLogger(__name__)
  43. push_rules_invalidation_counter = Counter(
  44. "synapse_push_bulk_push_rule_evaluator_push_rules_invalidation_counter", ""
  45. )
  46. push_rules_state_size_counter = Counter(
  47. "synapse_push_bulk_push_rule_evaluator_push_rules_state_size_counter", ""
  48. )
  49. STATE_EVENT_TYPES_TO_MARK_UNREAD = {
  50. EventTypes.Topic,
  51. EventTypes.Name,
  52. EventTypes.RoomAvatar,
  53. EventTypes.Tombstone,
  54. }
  55. def _should_count_as_unread(event: EventBase, context: EventContext) -> bool:
  56. # Exclude rejected and soft-failed events.
  57. if context.rejected or event.internal_metadata.is_soft_failed():
  58. return False
  59. # Exclude notices.
  60. if (
  61. not event.is_state()
  62. and event.type == EventTypes.Message
  63. and event.content.get("msgtype") == "m.notice"
  64. ):
  65. return False
  66. # Exclude edits.
  67. relates_to = relation_from_event(event)
  68. if relates_to and relates_to.rel_type == RelationTypes.REPLACE:
  69. return False
  70. # Mark events that have a non-empty string body as unread.
  71. body = event.content.get("body")
  72. if isinstance(body, str) and body:
  73. return True
  74. # Mark some state events as unread.
  75. if event.is_state() and event.type in STATE_EVENT_TYPES_TO_MARK_UNREAD:
  76. return True
  77. # Mark encrypted events as unread.
  78. if not event.is_state() and event.type == EventTypes.Encrypted:
  79. return True
  80. return False
  81. class BulkPushRuleEvaluator:
  82. """Calculates the outcome of push rules for an event for all users in the
  83. room at once.
  84. """
  85. def __init__(self, hs: "HomeServer"):
  86. self.hs = hs
  87. self.store = hs.get_datastores().main
  88. self.clock = hs.get_clock()
  89. self._event_auth_handler = hs.get_event_auth_handler()
  90. self._related_event_match_enabled = self.hs.config.experimental.msc3664_enabled
  91. self.room_push_rule_cache_metrics = register_cache(
  92. "cache",
  93. "room_push_rule_cache",
  94. cache=[], # Meaningless size, as this isn't a cache that stores values,
  95. resizable=False,
  96. )
  97. async def _get_rules_for_event(
  98. self,
  99. event: EventBase,
  100. ) -> Dict[str, FilteredPushRules]:
  101. """Get the push rules for all users who may need to be notified about
  102. the event.
  103. Note: this does not check if the user is allowed to see the event.
  104. Returns:
  105. Mapping of user ID to their push rules.
  106. """
  107. # We get the users who may need to be notified by first fetching the
  108. # local users currently in the room, finding those that have push rules,
  109. # and *then* checking which users are actually allowed to see the event.
  110. #
  111. # The alternative is to first fetch all users that were joined at the
  112. # event, but that requires fetching the full state at the event, which
  113. # may be expensive for large rooms with few local users.
  114. local_users = await self.store.get_local_users_in_room(event.room_id)
  115. # Filter out appservice users.
  116. local_users = [
  117. u
  118. for u in local_users
  119. if not self.store.get_if_app_services_interested_in_user(u)
  120. ]
  121. # if this event is an invite event, we may need to run rules for the user
  122. # who's been invited, otherwise they won't get told they've been invited
  123. if event.type == EventTypes.Member and event.membership == Membership.INVITE:
  124. invited = event.state_key
  125. if invited and self.hs.is_mine_id(invited) and invited not in local_users:
  126. local_users = list(local_users)
  127. local_users.append(invited)
  128. rules_by_user = await self.store.bulk_get_push_rules(local_users)
  129. logger.debug("Users in room: %s", local_users)
  130. if logger.isEnabledFor(logging.DEBUG):
  131. logger.debug(
  132. "Returning push rules for %r %r",
  133. event.room_id,
  134. list(rules_by_user.keys()),
  135. )
  136. return rules_by_user
  137. async def _get_power_levels_and_sender_level(
  138. self,
  139. event: EventBase,
  140. context: EventContext,
  141. event_id_to_event: Mapping[str, EventBase],
  142. ) -> Tuple[dict, Optional[int]]:
  143. """
  144. Given an event and an event context, get the power level event relevant to the event
  145. and the power level of the sender of the event.
  146. Args:
  147. event: event to check
  148. context: context of event to check
  149. event_id_to_event: a mapping of event_id to event for a set of events being
  150. batch persisted. This is needed as the sought-after power level event may
  151. be in this batch rather than the DB
  152. """
  153. # There are no power levels and sender levels possible to get from outlier
  154. if event.internal_metadata.is_outlier():
  155. return {}, None
  156. event_types = auth_types_for_event(event.room_version, event)
  157. prev_state_ids = await context.get_prev_state_ids(
  158. StateFilter.from_types(event_types)
  159. )
  160. pl_event_id = prev_state_ids.get(POWER_KEY)
  161. # fastpath: if there's a power level event, that's all we need, and
  162. # not having a power level event is an extreme edge case
  163. if pl_event_id:
  164. # Get the power level event from the batch, or fall back to the database.
  165. pl_event = event_id_to_event.get(pl_event_id)
  166. if pl_event:
  167. auth_events = {POWER_KEY: pl_event}
  168. else:
  169. auth_events = {POWER_KEY: await self.store.get_event(pl_event_id)}
  170. else:
  171. auth_events_ids = self._event_auth_handler.compute_auth_events(
  172. event, prev_state_ids, for_verification=False
  173. )
  174. auth_events_dict = await self.store.get_events(auth_events_ids)
  175. # Some needed auth events might be in the batch, combine them with those
  176. # fetched from the database.
  177. for auth_event_id in auth_events_ids:
  178. auth_event = event_id_to_event.get(auth_event_id)
  179. if auth_event:
  180. auth_events_dict[auth_event_id] = auth_event
  181. auth_events = {(e.type, e.state_key): e for e in auth_events_dict.values()}
  182. sender_level = get_user_power_level(event.sender, auth_events)
  183. pl_event = auth_events.get(POWER_KEY)
  184. return pl_event.content if pl_event else {}, sender_level
  185. async def _related_events(self, event: EventBase) -> Dict[str, Dict[str, str]]:
  186. """Fetches the related events for 'event'. Sets the im.vector.is_falling_back key if the event is from a fallback relation
  187. Returns:
  188. Mapping of relation type to flattened events.
  189. """
  190. related_events: Dict[str, Dict[str, str]] = {}
  191. if self._related_event_match_enabled:
  192. related_event_id = event.content.get("m.relates_to", {}).get("event_id")
  193. relation_type = event.content.get("m.relates_to", {}).get("rel_type")
  194. if related_event_id is not None and relation_type is not None:
  195. related_event = await self.store.get_event(
  196. related_event_id, allow_none=True
  197. )
  198. if related_event is not None:
  199. related_events[relation_type] = _flatten_dict(related_event)
  200. reply_event_id = (
  201. event.content.get("m.relates_to", {})
  202. .get("m.in_reply_to", {})
  203. .get("event_id")
  204. )
  205. # convert replies to pseudo relations
  206. if reply_event_id is not None:
  207. related_event = await self.store.get_event(
  208. reply_event_id, allow_none=True
  209. )
  210. if related_event is not None:
  211. related_events["m.in_reply_to"] = _flatten_dict(related_event)
  212. # indicate that this is from a fallback relation.
  213. if relation_type == "m.thread" and event.content.get(
  214. "m.relates_to", {}
  215. ).get("is_falling_back", False):
  216. related_events["m.in_reply_to"][
  217. "im.vector.is_falling_back"
  218. ] = ""
  219. return related_events
  220. async def action_for_events_by_user(
  221. self, events_and_context: List[Tuple[EventBase, EventContext]]
  222. ) -> None:
  223. """Given a list of events and their associated contexts, evaluate the push rules
  224. for each event, check if the message should increment the unread count, and
  225. insert the results into the event_push_actions_staging table.
  226. """
  227. # For batched events the power level events may not have been persisted yet,
  228. # so we pass in the batched events. Thus if the event cannot be found in the
  229. # database we can check in the batch.
  230. event_id_to_event = {e.event_id: e for e, _ in events_and_context}
  231. for event, context in events_and_context:
  232. await self._action_for_event_by_user(event, context, event_id_to_event)
  233. @measure_func("action_for_event_by_user")
  234. async def _action_for_event_by_user(
  235. self,
  236. event: EventBase,
  237. context: EventContext,
  238. event_id_to_event: Mapping[str, EventBase],
  239. ) -> None:
  240. if (
  241. not event.internal_metadata.is_notifiable()
  242. or event.internal_metadata.is_historical()
  243. ):
  244. # Push rules for events that aren't notifiable can't be processed by this and
  245. # we want to skip push notification actions for historical messages
  246. # because we don't want to notify people about old history back in time.
  247. # The historical messages also do not have the proper `context.current_state_ids`
  248. # and `state_groups` because they have `prev_events` that aren't persisted yet
  249. # (historical messages persisted in reverse-chronological order).
  250. return
  251. # Disable counting as unread unless the experimental configuration is
  252. # enabled, as it can cause additional (unwanted) rows to be added to the
  253. # event_push_actions table.
  254. count_as_unread = False
  255. if self.hs.config.experimental.msc2654_enabled:
  256. count_as_unread = _should_count_as_unread(event, context)
  257. rules_by_user = await self._get_rules_for_event(event)
  258. actions_by_user: Dict[str, Collection[Union[Mapping, str]]] = {}
  259. room_member_count = await self.store.get_number_joined_users_in_room(
  260. event.room_id
  261. )
  262. (
  263. power_levels,
  264. sender_power_level,
  265. ) = await self._get_power_levels_and_sender_level(
  266. event, context, event_id_to_event
  267. )
  268. # Find the event's thread ID.
  269. relation = relation_from_event(event)
  270. # If the event does not have a relation, then it cannot have a thread ID.
  271. thread_id = MAIN_TIMELINE
  272. if relation:
  273. # Recursively attempt to find the thread this event relates to.
  274. if relation.rel_type == RelationTypes.THREAD:
  275. thread_id = relation.parent_id
  276. else:
  277. # Since the event has not yet been persisted we check whether
  278. # the parent is part of a thread.
  279. thread_id = await self.store.get_thread_id(relation.parent_id)
  280. related_events = await self._related_events(event)
  281. # It's possible that old room versions have non-integer power levels (floats or
  282. # strings). Workaround this by explicitly converting to int.
  283. notification_levels = power_levels.get("notifications", {})
  284. if not event.room_version.msc3667_int_only_power_levels:
  285. for user_id, level in notification_levels.items():
  286. notification_levels[user_id] = int(level)
  287. room_version_features = event.room_version.msc3931_push_features
  288. if not room_version_features:
  289. room_version_features = []
  290. evaluator = PushRuleEvaluator(
  291. _flatten_dict(event, room_version=event.room_version),
  292. room_member_count,
  293. sender_power_level,
  294. notification_levels,
  295. related_events,
  296. self._related_event_match_enabled,
  297. room_version_features,
  298. self.hs.config.experimental.msc1767_enabled, # MSC3931 flag
  299. )
  300. users = rules_by_user.keys()
  301. profiles = await self.store.get_subset_users_in_room_with_profiles(
  302. event.room_id, users
  303. )
  304. for uid, rules in rules_by_user.items():
  305. if event.sender == uid:
  306. continue
  307. display_name = None
  308. profile = profiles.get(uid)
  309. if profile:
  310. display_name = profile.display_name
  311. if not display_name:
  312. # Handle the case where we are pushing a membership event to
  313. # that user, as they might not be already joined.
  314. if event.type == EventTypes.Member and event.state_key == uid:
  315. display_name = event.content.get("displayname", None)
  316. if not isinstance(display_name, str):
  317. display_name = None
  318. if count_as_unread:
  319. # Add an element for the current user if the event needs to be marked as
  320. # unread, so that add_push_actions_to_staging iterates over it.
  321. # If the event shouldn't be marked as unread but should notify the
  322. # current user, it'll be added to the dict later.
  323. actions_by_user[uid] = []
  324. actions = evaluator.run(rules, uid, display_name)
  325. if "notify" in actions:
  326. # Push rules say we should notify the user of this event
  327. actions_by_user[uid] = actions
  328. # If there aren't any actions then we can skip the rest of the
  329. # processing.
  330. if not actions_by_user:
  331. return
  332. # This is a check for the case where user joins a room without being
  333. # allowed to see history, and then the server receives a delayed event
  334. # from before the user joined, which they should not be pushed for
  335. #
  336. # We do this *after* calculating the push actions as a) its unlikely
  337. # that we'll filter anyone out and b) for large rooms its likely that
  338. # most users will have push disabled and so the set of users to check is
  339. # much smaller.
  340. uids_with_visibility = await filter_event_for_clients_with_state(
  341. self.store, actions_by_user.keys(), event, context
  342. )
  343. for user_id in set(actions_by_user).difference(uids_with_visibility):
  344. actions_by_user.pop(user_id, None)
  345. # Mark in the DB staging area the push actions for users who should be
  346. # notified for this event. (This will then get handled when we persist
  347. # the event)
  348. await self.store.add_push_actions_to_staging(
  349. event.event_id,
  350. actions_by_user,
  351. count_as_unread,
  352. thread_id,
  353. )
  354. MemberMap = Dict[str, Optional[EventIdMembership]]
  355. Rule = Dict[str, dict]
  356. RulesByUser = Dict[str, List[Rule]]
  357. StateGroup = Union[object, int]
  358. def _flatten_dict(
  359. d: Union[EventBase, Mapping[str, Any]],
  360. room_version: Optional[RoomVersion] = None,
  361. prefix: Optional[List[str]] = None,
  362. result: Optional[Dict[str, str]] = None,
  363. ) -> Dict[str, str]:
  364. if prefix is None:
  365. prefix = []
  366. if result is None:
  367. result = {}
  368. for key, value in d.items():
  369. if isinstance(value, str):
  370. result[".".join(prefix + [key])] = value.lower()
  371. elif isinstance(value, Mapping):
  372. # do not set `room_version` due to recursion considerations below
  373. _flatten_dict(value, prefix=(prefix + [key]), result=result)
  374. # `room_version` should only ever be set when looking at the top level of an event
  375. if (
  376. room_version is not None
  377. and PushRuleRoomFlag.EXTENSIBLE_EVENTS in room_version.msc3931_push_features
  378. and isinstance(d, EventBase)
  379. ):
  380. # Room supports extensible events: replace `content.body` with the plain text
  381. # representation from `m.markup`, as per MSC1767.
  382. markup = d.get("content").get("m.markup")
  383. if room_version.identifier.startswith("org.matrix.msc1767."):
  384. markup = d.get("content").get("org.matrix.msc1767.markup")
  385. if markup is not None and isinstance(markup, list):
  386. text = ""
  387. for rep in markup:
  388. if not isinstance(rep, dict):
  389. # invalid markup - skip all processing
  390. break
  391. if rep.get("mimetype", "text/plain") == "text/plain":
  392. rep_text = rep.get("body")
  393. if rep_text is not None and isinstance(rep_text, str):
  394. text = rep_text.lower()
  395. break
  396. result["content.body"] = text
  397. return result