Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

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