You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

492 lines
19 KiB

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