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.
 
 
 
 
 
 

378 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. Any,
  20. Collection,
  21. Dict,
  22. Iterable,
  23. List,
  24. Mapping,
  25. Optional,
  26. Set,
  27. Tuple,
  28. Union,
  29. )
  30. from prometheus_client import Counter
  31. from synapse.api.constants import EventTypes, Membership, RelationTypes
  32. from synapse.event_auth import auth_types_for_event, get_user_power_level
  33. from synapse.events import EventBase, relation_from_event
  34. from synapse.events.snapshot import EventContext
  35. from synapse.state import POWER_KEY
  36. from synapse.storage.databases.main.roommember import EventIdMembership
  37. from synapse.storage.state import StateFilter
  38. from synapse.synapse_rust.push import FilteredPushRules, PushRule, PushRuleEvaluator
  39. from synapse.util.caches import register_cache
  40. from synapse.util.metrics import measure_func
  41. from synapse.visibility import filter_event_for_clients_with_state
  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, Optional[int]]:
  143. # There are no power levels and sender levels possible to get from outlier
  144. if event.internal_metadata.is_outlier():
  145. return {}, None
  146. event_types = auth_types_for_event(event.room_version, event)
  147. prev_state_ids = await context.get_prev_state_ids(
  148. StateFilter.from_types(event_types)
  149. )
  150. pl_event_id = prev_state_ids.get(POWER_KEY)
  151. if pl_event_id:
  152. # fastpath: if there's a power level event, that's all we need, and
  153. # not having a power level event is an extreme edge case
  154. auth_events = {POWER_KEY: await self.store.get_event(pl_event_id)}
  155. else:
  156. auth_events_ids = self._event_auth_handler.compute_auth_events(
  157. event, prev_state_ids, for_verification=False
  158. )
  159. auth_events_dict = await self.store.get_events(auth_events_ids)
  160. auth_events = {(e.type, e.state_key): e for e in auth_events_dict.values()}
  161. sender_level = get_user_power_level(event.sender, auth_events)
  162. pl_event = auth_events.get(POWER_KEY)
  163. return pl_event.content if pl_event else {}, sender_level
  164. async def _get_mutual_relations(
  165. self, parent_id: str, rules: Iterable[Tuple[PushRule, bool]]
  166. ) -> Dict[str, Set[Tuple[str, str]]]:
  167. """
  168. Fetch event metadata for events which related to the same event as the given event.
  169. If the given event has no relation information, returns an empty dictionary.
  170. Args:
  171. parent_id: The event ID which is targeted by relations.
  172. rules: The push rules which will be processed for this event.
  173. Returns:
  174. A dictionary of relation type to:
  175. A set of tuples of:
  176. The sender
  177. The event type
  178. """
  179. # If the experimental feature is not enabled, skip fetching relations.
  180. if not self._relations_match_enabled:
  181. return {}
  182. # Pre-filter to figure out which relation types are interesting.
  183. rel_types = set()
  184. for rule, enabled in rules:
  185. if not enabled:
  186. continue
  187. for condition in rule.conditions:
  188. if condition["kind"] != "org.matrix.msc3772.relation_match":
  189. continue
  190. # rel_type is required.
  191. rel_type = condition.get("rel_type")
  192. if rel_type:
  193. rel_types.add(rel_type)
  194. # If no valid rules were found, no mutual relations.
  195. if not rel_types:
  196. return {}
  197. # If any valid rules were found, fetch the mutual relations.
  198. return await self.store.get_mutual_event_relations(parent_id, rel_types)
  199. @measure_func("action_for_event_by_user")
  200. async def action_for_event_by_user(
  201. self, event: EventBase, context: EventContext
  202. ) -> None:
  203. """Given an event and context, evaluate the push rules, check if the message
  204. should increment the unread count, and insert the results into the
  205. event_push_actions_staging table.
  206. """
  207. if not event.internal_metadata.is_notifiable():
  208. # Push rules for events that aren't notifiable can't be processed by this
  209. return
  210. # Disable counting as unread unless the experimental configuration is
  211. # enabled, as it can cause additional (unwanted) rows to be added to the
  212. # event_push_actions table.
  213. count_as_unread = False
  214. if self.hs.config.experimental.msc2654_enabled:
  215. count_as_unread = _should_count_as_unread(event, context)
  216. rules_by_user = await self._get_rules_for_event(event)
  217. actions_by_user: Dict[str, Collection[Union[Mapping, str]]] = {}
  218. room_member_count = await self.store.get_number_joined_users_in_room(
  219. event.room_id
  220. )
  221. (
  222. power_levels,
  223. sender_power_level,
  224. ) = await self._get_power_levels_and_sender_level(event, context)
  225. relation = relation_from_event(event)
  226. # If the event does not have a relation, then cannot have any mutual
  227. # relations or thread ID.
  228. relations = {}
  229. thread_id = "main"
  230. if relation:
  231. relations = await self._get_mutual_relations(
  232. relation.parent_id,
  233. itertools.chain(*(r.rules() for r in rules_by_user.values())),
  234. )
  235. if relation.rel_type == RelationTypes.THREAD:
  236. thread_id = relation.parent_id
  237. evaluator = PushRuleEvaluator(
  238. _flatten_dict(event),
  239. room_member_count,
  240. sender_power_level,
  241. power_levels.get("notifications", {}),
  242. relations,
  243. self._relations_match_enabled,
  244. )
  245. users = rules_by_user.keys()
  246. profiles = await self.store.get_subset_users_in_room_with_profiles(
  247. event.room_id, users
  248. )
  249. # This is a check for the case where user joins a room without being
  250. # allowed to see history, and then the server receives a delayed event
  251. # from before the user joined, which they should not be pushed for
  252. uids_with_visibility = await filter_event_for_clients_with_state(
  253. self.store, users, event, context
  254. )
  255. for uid, rules in rules_by_user.items():
  256. if event.sender == uid:
  257. continue
  258. if uid not in uids_with_visibility:
  259. continue
  260. display_name = None
  261. profile = profiles.get(uid)
  262. if profile:
  263. display_name = profile.display_name
  264. if not display_name:
  265. # Handle the case where we are pushing a membership event to
  266. # that user, as they might not be already joined.
  267. if event.type == EventTypes.Member and event.state_key == uid:
  268. display_name = event.content.get("displayname", None)
  269. if not isinstance(display_name, str):
  270. display_name = None
  271. if count_as_unread:
  272. # Add an element for the current user if the event needs to be marked as
  273. # unread, so that add_push_actions_to_staging iterates over it.
  274. # If the event shouldn't be marked as unread but should notify the
  275. # current user, it'll be added to the dict later.
  276. actions_by_user[uid] = []
  277. actions = evaluator.run(rules, uid, display_name)
  278. if "notify" in actions:
  279. # Push rules say we should notify the user of this event
  280. actions_by_user[uid] = actions
  281. # Mark in the DB staging area the push actions for users who should be
  282. # notified for this event. (This will then get handled when we persist
  283. # the event)
  284. await self.store.add_push_actions_to_staging(
  285. event.event_id,
  286. actions_by_user,
  287. count_as_unread,
  288. thread_id,
  289. )
  290. MemberMap = Dict[str, Optional[EventIdMembership]]
  291. Rule = Dict[str, dict]
  292. RulesByUser = Dict[str, List[Rule]]
  293. StateGroup = Union[object, int]
  294. def _flatten_dict(
  295. d: Union[EventBase, Mapping[str, Any]],
  296. prefix: Optional[List[str]] = None,
  297. result: Optional[Dict[str, str]] = None,
  298. ) -> Dict[str, str]:
  299. if prefix is None:
  300. prefix = []
  301. if result is None:
  302. result = {}
  303. for key, value in d.items():
  304. if isinstance(value, str):
  305. result[".".join(prefix + [key])] = value.lower()
  306. elif isinstance(value, Mapping):
  307. _flatten_dict(value, prefix=(prefix + [key]), result=result)
  308. return result