httppusher.py 17 KB

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