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.
 
 
 
 
 
 

477 lines
18 KiB

  1. # Copyright 2015, 2016 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. import urllib.parse
  17. from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
  18. from prometheus_client import Counter
  19. from twisted.internet.error import AlreadyCalled, AlreadyCancelled
  20. from twisted.internet.interfaces import IDelayedCall
  21. from synapse.api.constants import EventTypes
  22. from synapse.events import EventBase
  23. from synapse.logging import opentracing
  24. from synapse.metrics.background_process_metrics import run_as_background_process
  25. from synapse.push import Pusher, PusherConfig, PusherConfigException
  26. from synapse.storage.databases.main.event_push_actions import HttpPushAction
  27. from . import push_tools
  28. if TYPE_CHECKING:
  29. from synapse.server import HomeServer
  30. logger = logging.getLogger(__name__)
  31. http_push_processed_counter = Counter(
  32. "synapse_http_httppusher_http_pushes_processed",
  33. "Number of push notifications successfully sent",
  34. )
  35. http_push_failed_counter = Counter(
  36. "synapse_http_httppusher_http_pushes_failed",
  37. "Number of push notifications which failed",
  38. )
  39. http_badges_processed_counter = Counter(
  40. "synapse_http_httppusher_badge_updates_processed",
  41. "Number of badge updates successfully sent",
  42. )
  43. http_badges_failed_counter = Counter(
  44. "synapse_http_httppusher_badge_updates_failed",
  45. "Number of badge updates which failed",
  46. )
  47. def tweaks_for_actions(actions: List[Union[str, Dict]]) -> Dict[str, Any]:
  48. """
  49. Converts a list of actions into a `tweaks` dict (which can then be passed to
  50. the push gateway).
  51. This function ignores all actions other than `set_tweak` actions, and treats
  52. absent `value`s as `True`, which agrees with the only spec-defined treatment
  53. of absent `value`s (namely, for `highlight` tweaks).
  54. Args:
  55. actions: list of actions
  56. e.g. [
  57. {"set_tweak": "a", "value": "AAA"},
  58. {"set_tweak": "b", "value": "BBB"},
  59. {"set_tweak": "highlight"},
  60. "notify"
  61. ]
  62. Returns:
  63. dictionary of tweaks for those actions
  64. e.g. {"a": "AAA", "b": "BBB", "highlight": True}
  65. """
  66. tweaks = {}
  67. for a in actions:
  68. if not isinstance(a, dict):
  69. continue
  70. if "set_tweak" in a:
  71. # value is allowed to be absent in which case the value assumed
  72. # should be True.
  73. tweaks[a["set_tweak"]] = a.get("value", True)
  74. return tweaks
  75. class HttpPusher(Pusher):
  76. INITIAL_BACKOFF_SEC = 1 # in seconds because that's what Twisted takes
  77. MAX_BACKOFF_SEC = 60 * 60
  78. # This one's in ms because we compare it against the clock
  79. GIVE_UP_AFTER_MS = 24 * 60 * 60 * 1000
  80. def __init__(self, hs: "HomeServer", pusher_config: PusherConfig):
  81. super().__init__(hs, pusher_config)
  82. self._storage_controllers = self.hs.get_storage_controllers()
  83. self.app_display_name = pusher_config.app_display_name
  84. self.device_display_name = pusher_config.device_display_name
  85. self.pushkey_ts = pusher_config.ts
  86. self.data = pusher_config.data
  87. self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC
  88. self.failing_since = pusher_config.failing_since
  89. self.timed_call: Optional[IDelayedCall] = None
  90. self._is_processing = False
  91. self._group_unread_count_by_room = (
  92. hs.config.push.push_group_unread_count_by_room
  93. )
  94. self._pusherpool = hs.get_pusherpool()
  95. self.data = pusher_config.data
  96. if self.data is None:
  97. raise PusherConfigException("'data' key can not be null for HTTP pusher")
  98. self.name = "%s/%s/%s" % (
  99. pusher_config.user_name,
  100. pusher_config.app_id,
  101. pusher_config.pushkey,
  102. )
  103. # Validate that there's a URL and it is of the proper form.
  104. if "url" not in self.data:
  105. raise PusherConfigException("'url' required in data for HTTP pusher")
  106. url = self.data["url"]
  107. if not isinstance(url, str):
  108. raise PusherConfigException("'url' must be a string")
  109. url_parts = urllib.parse.urlparse(url)
  110. # Note that the specification also says the scheme must be HTTPS, but
  111. # it isn't up to the homeserver to verify that.
  112. if url_parts.path != "/_matrix/push/v1/notify":
  113. raise PusherConfigException(
  114. "'url' must have a path of '/_matrix/push/v1/notify'"
  115. )
  116. self.url = url
  117. self.http_client = hs.get_proxied_blacklisted_http_client()
  118. self.data_minus_url = {}
  119. self.data_minus_url.update(self.data)
  120. del self.data_minus_url["url"]
  121. self.badge_count_last_call: Optional[int] = None
  122. def on_started(self, should_check_for_notifs: bool) -> None:
  123. """Called when this pusher has been started.
  124. Args:
  125. should_check_for_notifs: Whether we should immediately
  126. check for push to send. Set to False only if it's known there
  127. is nothing to send
  128. """
  129. if should_check_for_notifs:
  130. self._start_processing()
  131. def on_new_receipts(self, min_stream_id: int, max_stream_id: int) -> None:
  132. # Note that the min here shouldn't be relied upon to be accurate.
  133. # We could check the receipts are actually m.read receipts here,
  134. # but currently that's the only type of receipt anyway...
  135. run_as_background_process("http_pusher.on_new_receipts", self._update_badge)
  136. async def _update_badge(self) -> None:
  137. # XXX as per https://github.com/matrix-org/matrix-doc/issues/2627, this seems
  138. # to be largely redundant. perhaps we can remove it.
  139. badge = await push_tools.get_badge_count(
  140. self.hs.get_datastores().main,
  141. self.user_id,
  142. group_by_room=self._group_unread_count_by_room,
  143. )
  144. if self.badge_count_last_call is None or self.badge_count_last_call != badge:
  145. self.badge_count_last_call = badge
  146. await self._send_badge(badge)
  147. def on_timer(self) -> None:
  148. self._start_processing()
  149. def on_stop(self) -> None:
  150. if self.timed_call:
  151. try:
  152. self.timed_call.cancel()
  153. except (AlreadyCalled, AlreadyCancelled):
  154. pass
  155. self.timed_call = None
  156. def _start_processing(self) -> None:
  157. if self._is_processing:
  158. return
  159. run_as_background_process("httppush.process", self._process)
  160. async def _process(self) -> None:
  161. # we should never get here if we are already processing
  162. assert not self._is_processing
  163. try:
  164. self._is_processing = True
  165. # if the max ordering changes while we're running _unsafe_process,
  166. # call it again, and so on until we've caught up.
  167. while True:
  168. starting_max_ordering = self.max_stream_ordering
  169. try:
  170. await self._unsafe_process()
  171. except Exception:
  172. logger.exception("Exception processing notifs")
  173. if self.max_stream_ordering == starting_max_ordering:
  174. break
  175. finally:
  176. self._is_processing = False
  177. async def _unsafe_process(self) -> None:
  178. """
  179. Looks for unset notifications and dispatch them, in order
  180. Never call this directly: use _process which will only allow this to
  181. run once per pusher.
  182. """
  183. unprocessed = (
  184. await self.store.get_unread_push_actions_for_user_in_range_for_http(
  185. self.user_id, self.last_stream_ordering, self.max_stream_ordering
  186. )
  187. )
  188. logger.info(
  189. "Processing %i unprocessed push actions for %s starting at "
  190. "stream_ordering %s",
  191. len(unprocessed),
  192. self.name,
  193. self.last_stream_ordering,
  194. )
  195. for push_action in unprocessed:
  196. with opentracing.start_active_span(
  197. "http-push",
  198. tags={
  199. "authenticated_entity": self.user_id,
  200. "event_id": push_action.event_id,
  201. "app_id": self.app_id,
  202. "app_display_name": self.app_display_name,
  203. },
  204. ):
  205. processed = await self._process_one(push_action)
  206. if processed:
  207. http_push_processed_counter.inc()
  208. self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC
  209. self.last_stream_ordering = push_action.stream_ordering
  210. pusher_still_exists = (
  211. await self.store.update_pusher_last_stream_ordering_and_success(
  212. self.app_id,
  213. self.pushkey,
  214. self.user_id,
  215. self.last_stream_ordering,
  216. self.clock.time_msec(),
  217. )
  218. )
  219. if not pusher_still_exists:
  220. # The pusher has been deleted while we were processing, so
  221. # lets just stop and return.
  222. self.on_stop()
  223. return
  224. if self.failing_since:
  225. self.failing_since = None
  226. await self.store.update_pusher_failing_since(
  227. self.app_id, self.pushkey, self.user_id, self.failing_since
  228. )
  229. else:
  230. http_push_failed_counter.inc()
  231. if not self.failing_since:
  232. self.failing_since = self.clock.time_msec()
  233. await self.store.update_pusher_failing_since(
  234. self.app_id, self.pushkey, self.user_id, self.failing_since
  235. )
  236. if (
  237. self.failing_since
  238. and self.failing_since
  239. < self.clock.time_msec() - HttpPusher.GIVE_UP_AFTER_MS
  240. ):
  241. # we really only give up so that if the URL gets
  242. # fixed, we don't suddenly deliver a load
  243. # of old notifications.
  244. logger.warning(
  245. "Giving up on a notification to user %s, pushkey %s",
  246. self.user_id,
  247. self.pushkey,
  248. )
  249. self.backoff_delay = HttpPusher.INITIAL_BACKOFF_SEC
  250. self.last_stream_ordering = push_action.stream_ordering
  251. await self.store.update_pusher_last_stream_ordering(
  252. self.app_id,
  253. self.pushkey,
  254. self.user_id,
  255. self.last_stream_ordering,
  256. )
  257. self.failing_since = None
  258. await self.store.update_pusher_failing_since(
  259. self.app_id, self.pushkey, self.user_id, self.failing_since
  260. )
  261. else:
  262. logger.info("Push failed: delaying for %ds", self.backoff_delay)
  263. self.timed_call = self.hs.get_reactor().callLater(
  264. self.backoff_delay, self.on_timer
  265. )
  266. self.backoff_delay = min(
  267. self.backoff_delay * 2, self.MAX_BACKOFF_SEC
  268. )
  269. break
  270. async def _process_one(self, push_action: HttpPushAction) -> bool:
  271. if "notify" not in push_action.actions:
  272. return True
  273. tweaks = tweaks_for_actions(push_action.actions)
  274. badge = await push_tools.get_badge_count(
  275. self.hs.get_datastores().main,
  276. self.user_id,
  277. group_by_room=self._group_unread_count_by_room,
  278. )
  279. event = await self.store.get_event(push_action.event_id, allow_none=True)
  280. if event is None:
  281. return True # It's been redacted
  282. rejected = await self.dispatch_push(event, tweaks, badge)
  283. if rejected is False:
  284. return False
  285. if isinstance(rejected, (list, tuple)):
  286. for pk in rejected:
  287. if pk != self.pushkey:
  288. # for sanity, we only remove the pushkey if it
  289. # was the one we actually sent...
  290. logger.warning(
  291. ("Ignoring rejected pushkey %s because we didn't send it"),
  292. pk,
  293. )
  294. else:
  295. logger.info("Pushkey %s was rejected: removing", pk)
  296. await self._pusherpool.remove_pusher(self.app_id, pk, self.user_id)
  297. return True
  298. async def _build_notification_dict(
  299. self, event: EventBase, tweaks: Dict[str, bool], badge: int
  300. ) -> Dict[str, Any]:
  301. priority = "low"
  302. if (
  303. event.type == EventTypes.Encrypted
  304. or tweaks.get("highlight")
  305. or tweaks.get("sound")
  306. ):
  307. # HACK send our push as high priority only if it generates a sound, highlight
  308. # or may do so (i.e. is encrypted so has unknown effects).
  309. priority = "high"
  310. # This was checked in the __init__, but mypy doesn't seem to know that.
  311. assert self.data is not None
  312. if self.data.get("format") == "event_id_only":
  313. d: Dict[str, Any] = {
  314. "notification": {
  315. "event_id": event.event_id,
  316. "room_id": event.room_id,
  317. "counts": {"unread": badge},
  318. "prio": priority,
  319. "devices": [
  320. {
  321. "app_id": self.app_id,
  322. "pushkey": self.pushkey,
  323. "pushkey_ts": int(self.pushkey_ts / 1000),
  324. "data": self.data_minus_url,
  325. }
  326. ],
  327. }
  328. }
  329. return d
  330. ctx = await push_tools.get_context_for_event(
  331. self._storage_controllers, event, self.user_id
  332. )
  333. d = {
  334. "notification": {
  335. "id": event.event_id, # deprecated: remove soon
  336. "event_id": event.event_id,
  337. "room_id": event.room_id,
  338. "type": event.type,
  339. "sender": event.user_id,
  340. "prio": priority,
  341. "counts": {
  342. "unread": badge,
  343. # 'missed_calls': 2
  344. },
  345. "devices": [
  346. {
  347. "app_id": self.app_id,
  348. "pushkey": self.pushkey,
  349. "pushkey_ts": int(self.pushkey_ts / 1000),
  350. "data": self.data_minus_url,
  351. "tweaks": tweaks,
  352. }
  353. ],
  354. }
  355. }
  356. if event.type == "m.room.member" and event.is_state():
  357. d["notification"]["membership"] = event.content["membership"]
  358. d["notification"]["user_is_target"] = event.state_key == self.user_id
  359. if self.hs.config.push.push_include_content and event.content:
  360. d["notification"]["content"] = event.content
  361. # We no longer send aliases separately, instead, we send the human
  362. # readable name of the room, which may be an alias.
  363. if "sender_display_name" in ctx and len(ctx["sender_display_name"]) > 0:
  364. d["notification"]["sender_display_name"] = ctx["sender_display_name"]
  365. if "name" in ctx and len(ctx["name"]) > 0:
  366. d["notification"]["room_name"] = ctx["name"]
  367. return d
  368. async def dispatch_push(
  369. self, event: EventBase, tweaks: Dict[str, bool], badge: int
  370. ) -> Union[bool, Iterable[str]]:
  371. notification_dict = await self._build_notification_dict(event, tweaks, badge)
  372. if not notification_dict:
  373. return []
  374. try:
  375. resp = await self.http_client.post_json_get_json(
  376. self.url, notification_dict
  377. )
  378. except Exception as e:
  379. logger.warning(
  380. "Failed to push event %s to %s: %s %s",
  381. event.event_id,
  382. self.name,
  383. type(e),
  384. e,
  385. )
  386. return False
  387. rejected = []
  388. if "rejected" in resp:
  389. rejected = resp["rejected"]
  390. if not rejected:
  391. self.badge_count_last_call = badge
  392. return rejected
  393. async def _send_badge(self, badge: int) -> None:
  394. """
  395. Args:
  396. badge: number of unread messages
  397. """
  398. logger.debug("Sending updated badge count %d to %s", badge, self.name)
  399. d = {
  400. "notification": {
  401. "id": "",
  402. "type": None,
  403. "sender": "",
  404. "counts": {"unread": badge},
  405. "devices": [
  406. {
  407. "app_id": self.app_id,
  408. "pushkey": self.pushkey,
  409. "pushkey_ts": int(self.pushkey_ts / 1000),
  410. "data": self.data_minus_url,
  411. }
  412. ],
  413. }
  414. }
  415. try:
  416. await self.http_client.post_json_get_json(self.url, d)
  417. http_badges_processed_counter.inc()
  418. except Exception as e:
  419. logger.warning(
  420. "Failed to send badge count to %s: %s %s", self.name, type(e), e
  421. )
  422. http_badges_failed_counter.inc()