httppusher.py 16 KB

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