25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

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