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.
 
 
 
 
 
 

364 lines
13 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 itertools
  16. import logging
  17. from typing import (
  18. TYPE_CHECKING,
  19. Collection,
  20. Dict,
  21. Iterable,
  22. List,
  23. Mapping,
  24. Optional,
  25. Set,
  26. Tuple,
  27. Union,
  28. )
  29. from prometheus_client import Counter
  30. from synapse.api.constants import EventTypes, Membership, RelationTypes
  31. from synapse.event_auth import auth_types_for_event, get_user_power_level
  32. from synapse.events import EventBase, relation_from_event
  33. from synapse.events.snapshot import EventContext
  34. from synapse.state import POWER_KEY
  35. from synapse.storage.databases.main.roommember import EventIdMembership
  36. from synapse.storage.state import StateFilter
  37. from synapse.synapse_rust.push import FilteredPushRules, PushRule
  38. from synapse.util.caches import register_cache
  39. from synapse.util.metrics import measure_func
  40. from synapse.visibility import filter_event_for_clients_with_state
  41. from .push_rule_evaluator import PushRuleEvaluatorForEvent
  42. if TYPE_CHECKING:
  43. from synapse.server import HomeServer
  44. logger = logging.getLogger(__name__)
  45. push_rules_invalidation_counter = Counter(
  46. "synapse_push_bulk_push_rule_evaluator_push_rules_invalidation_counter", ""
  47. )
  48. push_rules_state_size_counter = Counter(
  49. "synapse_push_bulk_push_rule_evaluator_push_rules_state_size_counter", ""
  50. )
  51. STATE_EVENT_TYPES_TO_MARK_UNREAD = {
  52. EventTypes.Topic,
  53. EventTypes.Name,
  54. EventTypes.RoomAvatar,
  55. EventTypes.Tombstone,
  56. }
  57. def _should_count_as_unread(event: EventBase, context: EventContext) -> bool:
  58. # Exclude rejected and soft-failed events.
  59. if context.rejected or event.internal_metadata.is_soft_failed():
  60. return False
  61. # Exclude notices.
  62. if (
  63. not event.is_state()
  64. and event.type == EventTypes.Message
  65. and event.content.get("msgtype") == "m.notice"
  66. ):
  67. return False
  68. # Exclude edits.
  69. relates_to = relation_from_event(event)
  70. if relates_to and relates_to.rel_type == RelationTypes.REPLACE:
  71. return False
  72. # Mark events that have a non-empty string body as unread.
  73. body = event.content.get("body")
  74. if isinstance(body, str) and body:
  75. return True
  76. # Mark some state events as unread.
  77. if event.is_state() and event.type in STATE_EVENT_TYPES_TO_MARK_UNREAD:
  78. return True
  79. # Mark encrypted events as unread.
  80. if not event.is_state() and event.type == EventTypes.Encrypted:
  81. return True
  82. return False
  83. class BulkPushRuleEvaluator:
  84. """Calculates the outcome of push rules for an event for all users in the
  85. room at once.
  86. """
  87. def __init__(self, hs: "HomeServer"):
  88. self.hs = hs
  89. self.store = hs.get_datastores().main
  90. self.clock = hs.get_clock()
  91. self._event_auth_handler = hs.get_event_auth_handler()
  92. self.room_push_rule_cache_metrics = register_cache(
  93. "cache",
  94. "room_push_rule_cache",
  95. cache=[], # Meaningless size, as this isn't a cache that stores values,
  96. resizable=False,
  97. )
  98. # Whether to support MSC3772 is supported.
  99. self._relations_match_enabled = self.hs.config.experimental.msc3772_enabled
  100. async def _get_rules_for_event(
  101. self,
  102. event: EventBase,
  103. ) -> Dict[str, FilteredPushRules]:
  104. """Get the push rules for all users who may need to be notified about
  105. the event.
  106. Note: this does not check if the user is allowed to see the event.
  107. Returns:
  108. Mapping of user ID to their push rules.
  109. """
  110. # We get the users who may need to be notified by first fetching the
  111. # local users currently in the room, finding those that have push rules,
  112. # and *then* checking which users are actually allowed to see the event.
  113. #
  114. # The alternative is to first fetch all users that were joined at the
  115. # event, but that requires fetching the full state at the event, which
  116. # may be expensive for large rooms with few local users.
  117. local_users = await self.store.get_local_users_in_room(event.room_id)
  118. # Filter out appservice users.
  119. local_users = [
  120. u
  121. for u in local_users
  122. if not self.store.get_if_app_services_interested_in_user(u)
  123. ]
  124. # if this event is an invite event, we may need to run rules for the user
  125. # who's been invited, otherwise they won't get told they've been invited
  126. if event.type == EventTypes.Member and event.membership == Membership.INVITE:
  127. invited = event.state_key
  128. if invited and self.hs.is_mine_id(invited) and invited not in local_users:
  129. local_users = list(local_users)
  130. local_users.append(invited)
  131. rules_by_user = await self.store.bulk_get_push_rules(local_users)
  132. logger.debug("Users in room: %s", local_users)
  133. if logger.isEnabledFor(logging.DEBUG):
  134. logger.debug(
  135. "Returning push rules for %r %r",
  136. event.room_id,
  137. list(rules_by_user.keys()),
  138. )
  139. return rules_by_user
  140. async def _get_power_levels_and_sender_level(
  141. self, event: EventBase, context: EventContext
  142. ) -> Tuple[dict, int]:
  143. event_types = auth_types_for_event(event.room_version, event)
  144. prev_state_ids = await context.get_prev_state_ids(
  145. StateFilter.from_types(event_types)
  146. )
  147. pl_event_id = prev_state_ids.get(POWER_KEY)
  148. if pl_event_id:
  149. # fastpath: if there's a power level event, that's all we need, and
  150. # not having a power level event is an extreme edge case
  151. auth_events = {POWER_KEY: await self.store.get_event(pl_event_id)}
  152. else:
  153. auth_events_ids = self._event_auth_handler.compute_auth_events(
  154. event, prev_state_ids, for_verification=False
  155. )
  156. auth_events_dict = await self.store.get_events(auth_events_ids)
  157. auth_events = {(e.type, e.state_key): e for e in auth_events_dict.values()}
  158. sender_level = get_user_power_level(event.sender, auth_events)
  159. pl_event = auth_events.get(POWER_KEY)
  160. return pl_event.content if pl_event else {}, sender_level
  161. async def _get_mutual_relations(
  162. self, parent_id: str, rules: Iterable[Tuple[PushRule, bool]]
  163. ) -> Dict[str, Set[Tuple[str, str]]]:
  164. """
  165. Fetch event metadata for events which related to the same event as the given event.
  166. If the given event has no relation information, returns an empty dictionary.
  167. Args:
  168. parent_id: The event ID which is targeted by relations.
  169. rules: The push rules which will be processed for this event.
  170. Returns:
  171. A dictionary of relation type to:
  172. A set of tuples of:
  173. The sender
  174. The event type
  175. """
  176. # If the experimental feature is not enabled, skip fetching relations.
  177. if not self._relations_match_enabled:
  178. return {}
  179. # Pre-filter to figure out which relation types are interesting.
  180. rel_types = set()
  181. for rule, enabled in rules:
  182. if not enabled:
  183. continue
  184. for condition in rule.conditions:
  185. if condition["kind"] != "org.matrix.msc3772.relation_match":
  186. continue
  187. # rel_type is required.
  188. rel_type = condition.get("rel_type")
  189. if rel_type:
  190. rel_types.add(rel_type)
  191. # If no valid rules were found, no mutual relations.
  192. if not rel_types:
  193. return {}
  194. # If any valid rules were found, fetch the mutual relations.
  195. return await self.store.get_mutual_event_relations(parent_id, rel_types)
  196. @measure_func("action_for_event_by_user")
  197. async def action_for_event_by_user(
  198. self, event: EventBase, context: EventContext
  199. ) -> None:
  200. """Given an event and context, evaluate the push rules, check if the message
  201. should increment the unread count, and insert the results into the
  202. event_push_actions_staging table.
  203. """
  204. if event.internal_metadata.is_outlier():
  205. # This can happen due to out of band memberships
  206. return
  207. # Disable counting as unread unless the experimental configuration is
  208. # enabled, as it can cause additional (unwanted) rows to be added to the
  209. # event_push_actions table.
  210. count_as_unread = False
  211. if self.hs.config.experimental.msc2654_enabled:
  212. count_as_unread = _should_count_as_unread(event, context)
  213. rules_by_user = await self._get_rules_for_event(event)
  214. actions_by_user: Dict[str, Collection[Union[Mapping, str]]] = {}
  215. room_member_count = await self.store.get_number_joined_users_in_room(
  216. event.room_id
  217. )
  218. (
  219. power_levels,
  220. sender_power_level,
  221. ) = await self._get_power_levels_and_sender_level(event, context)
  222. relation = relation_from_event(event)
  223. # If the event does not have a relation, then cannot have any mutual
  224. # relations or thread ID.
  225. relations = {}
  226. thread_id = "main"
  227. if relation:
  228. relations = await self._get_mutual_relations(
  229. relation.parent_id,
  230. itertools.chain(*(r.rules() for r in rules_by_user.values())),
  231. )
  232. if relation.rel_type == RelationTypes.THREAD:
  233. thread_id = relation.parent_id
  234. evaluator = PushRuleEvaluatorForEvent(
  235. event,
  236. room_member_count,
  237. sender_power_level,
  238. power_levels,
  239. relations,
  240. self._relations_match_enabled,
  241. )
  242. users = rules_by_user.keys()
  243. profiles = await self.store.get_subset_users_in_room_with_profiles(
  244. event.room_id, users
  245. )
  246. # This is a check for the case where user joins a room without being
  247. # allowed to see history, and then the server receives a delayed event
  248. # from before the user joined, which they should not be pushed for
  249. uids_with_visibility = await filter_event_for_clients_with_state(
  250. self.store, users, event, context
  251. )
  252. for uid, rules in rules_by_user.items():
  253. if event.sender == uid:
  254. continue
  255. if uid not in uids_with_visibility:
  256. continue
  257. display_name = None
  258. profile = profiles.get(uid)
  259. if profile:
  260. display_name = profile.display_name
  261. if not display_name:
  262. # Handle the case where we are pushing a membership event to
  263. # that user, as they might not be already joined.
  264. if event.type == EventTypes.Member and event.state_key == uid:
  265. display_name = event.content.get("displayname", None)
  266. if not isinstance(display_name, str):
  267. display_name = None
  268. if count_as_unread:
  269. # Add an element for the current user if the event needs to be marked as
  270. # unread, so that add_push_actions_to_staging iterates over it.
  271. # If the event shouldn't be marked as unread but should notify the
  272. # current user, it'll be added to the dict later.
  273. actions_by_user[uid] = []
  274. for rule, enabled in rules.rules():
  275. if not enabled:
  276. continue
  277. matches = evaluator.check_conditions(rule.conditions, uid, display_name)
  278. if matches:
  279. actions = [x for x in rule.actions if x != "dont_notify"]
  280. if actions and "notify" in actions:
  281. # Push rules say we should notify the user of this event
  282. actions_by_user[uid] = actions
  283. break
  284. # Mark in the DB staging area the push actions for users who should be
  285. # notified for this event. (This will then get handled when we persist
  286. # the event)
  287. await self.store.add_push_actions_to_staging(
  288. event.event_id,
  289. actions_by_user,
  290. count_as_unread,
  291. thread_id,
  292. )
  293. MemberMap = Dict[str, Optional[EventIdMembership]]
  294. Rule = Dict[str, dict]
  295. RulesByUser = Dict[str, List[Rule]]
  296. StateGroup = Union[object, int]