Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

325 righe
12 KiB

  1. # Copyright 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import TYPE_CHECKING, Dict, List, Optional
  16. from twisted.internet.error import AlreadyCalled, AlreadyCancelled
  17. from twisted.internet.interfaces import IDelayedCall
  18. from synapse.metrics.background_process_metrics import run_as_background_process
  19. from synapse.push import Pusher, PusherConfig, PusherConfigException, ThrottleParams
  20. from synapse.push.mailer import Mailer
  21. from synapse.push.push_types import EmailReason
  22. from synapse.storage.databases.main.event_push_actions import EmailPushAction
  23. from synapse.util.threepids import validate_email
  24. if TYPE_CHECKING:
  25. from synapse.server import HomeServer
  26. logger = logging.getLogger(__name__)
  27. # THROTTLE is the minimum time between mail notifications sent for a given room.
  28. # Each room maintains its own throttle counter, but each new mail notification
  29. # sends the pending notifications for all rooms.
  30. THROTTLE_MAX_MS = 24 * 60 * 60 * 1000 # 24h
  31. # THROTTLE_MULTIPLIER = 6 # 10 mins, 1 hour, 6 hours, 24 hours
  32. THROTTLE_MULTIPLIER = 144 # 10 mins, 24 hours - i.e. jump straight to 1 day
  33. # If no event triggers a notification for this long after the previous,
  34. # the throttle is released.
  35. # 12 hours - a gap of 12 hours in conversation is surely enough to merit a new
  36. # notification when things get going again...
  37. THROTTLE_RESET_AFTER_MS = 12 * 60 * 60 * 1000
  38. # does each email include all unread notifs, or just the ones which have happened
  39. # since the last mail?
  40. # XXX: this is currently broken as it includes ones from parted rooms(!)
  41. INCLUDE_ALL_UNREAD_NOTIFS = False
  42. class EmailPusher(Pusher):
  43. """
  44. A pusher that sends email notifications about events (approximately)
  45. when they happen.
  46. This shares quite a bit of code with httpusher: it would be good to
  47. factor out the common parts
  48. """
  49. def __init__(self, hs: "HomeServer", pusher_config: PusherConfig, mailer: Mailer):
  50. super().__init__(hs, pusher_config)
  51. self.mailer = mailer
  52. self.store = self.hs.get_datastores().main
  53. self.email = pusher_config.pushkey
  54. self.timed_call: Optional[IDelayedCall] = None
  55. self.throttle_params: Dict[str, ThrottleParams] = {}
  56. self._inited = False
  57. self._is_processing = False
  58. # Make sure that the email is valid.
  59. try:
  60. validate_email(self.email)
  61. except ValueError:
  62. raise PusherConfigException("Invalid email")
  63. self._delay_before_mail_ms = self.hs.config.email.notif_delay_before_mail_ms
  64. def on_started(self, should_check_for_notifs: bool) -> None:
  65. """Called when this pusher has been started.
  66. Args:
  67. should_check_for_notifs: Whether we should immediately
  68. check for push to send. Set to False only if it's known there
  69. is nothing to send
  70. """
  71. if should_check_for_notifs and self.mailer is not None:
  72. self._start_processing()
  73. def on_stop(self) -> None:
  74. if self.timed_call:
  75. try:
  76. self.timed_call.cancel()
  77. except (AlreadyCalled, AlreadyCancelled):
  78. pass
  79. self.timed_call = None
  80. def on_new_receipts(self) -> None:
  81. # We could wake up and cancel the timer but there tend to be quite a
  82. # lot of read receipts so it's probably less work to just let the
  83. # timer fire
  84. pass
  85. def on_timer(self) -> None:
  86. self.timed_call = None
  87. self._start_processing()
  88. def _start_processing(self) -> None:
  89. if self._is_processing:
  90. return
  91. run_as_background_process("emailpush.process", self._process)
  92. def _pause_processing(self) -> None:
  93. """Used by tests to temporarily pause processing of events.
  94. Asserts that its not currently processing.
  95. """
  96. assert not self._is_processing
  97. self._is_processing = True
  98. def _resume_processing(self) -> None:
  99. """Used by tests to resume processing of events after pausing."""
  100. assert self._is_processing
  101. self._is_processing = False
  102. self._start_processing()
  103. async def _process(self) -> None:
  104. # we should never get here if we are already processing
  105. assert not self._is_processing
  106. try:
  107. self._is_processing = True
  108. if not self._inited:
  109. # this is our first loop: load up the throttle params
  110. assert self.pusher_id is not None
  111. self.throttle_params = await self.store.get_throttle_params_by_room(
  112. self.pusher_id
  113. )
  114. self._inited = True
  115. # if the max ordering changes while we're running _unsafe_process,
  116. # call it again, and so on until we've caught up.
  117. while True:
  118. starting_max_ordering = self.max_stream_ordering
  119. try:
  120. await self._unsafe_process()
  121. except Exception:
  122. logger.exception("Exception processing notifs")
  123. if self.max_stream_ordering == starting_max_ordering:
  124. break
  125. finally:
  126. self._is_processing = False
  127. async def _unsafe_process(self) -> None:
  128. """
  129. Main logic of the push loop without the wrapper function that sets
  130. up logging, measures and guards against multiple instances of it
  131. being run.
  132. """
  133. start = 0 if INCLUDE_ALL_UNREAD_NOTIFS else self.last_stream_ordering
  134. unprocessed = (
  135. await self.store.get_unread_push_actions_for_user_in_range_for_email(
  136. self.user_id, start, self.max_stream_ordering
  137. )
  138. )
  139. soonest_due_at: Optional[int] = None
  140. if not unprocessed:
  141. await self.save_last_stream_ordering_and_success(self.max_stream_ordering)
  142. return
  143. for push_action in unprocessed:
  144. received_at = push_action.received_ts
  145. if received_at is None:
  146. received_at = 0
  147. notif_ready_at = received_at + self._delay_before_mail_ms
  148. room_ready_at = self.room_ready_to_notify_at(push_action.room_id)
  149. should_notify_at = max(notif_ready_at, room_ready_at)
  150. if should_notify_at <= self.clock.time_msec():
  151. # one of our notifications is ready for sending, so we send
  152. # *one* email updating the user on their notifications,
  153. # we then consider all previously outstanding notifications
  154. # to be delivered.
  155. reason: EmailReason = {
  156. "room_id": push_action.room_id,
  157. "now": self.clock.time_msec(),
  158. "received_at": received_at,
  159. "delay_before_mail_ms": self._delay_before_mail_ms,
  160. "last_sent_ts": self.get_room_last_sent_ts(push_action.room_id),
  161. "throttle_ms": self.get_room_throttle_ms(push_action.room_id),
  162. }
  163. await self.send_notification(unprocessed, reason)
  164. await self.save_last_stream_ordering_and_success(
  165. max(ea.stream_ordering for ea in unprocessed)
  166. )
  167. # we update the throttle on all the possible unprocessed push actions
  168. for ea in unprocessed:
  169. await self.sent_notif_update_throttle(ea.room_id, ea)
  170. break
  171. else:
  172. if soonest_due_at is None or should_notify_at < soonest_due_at:
  173. soonest_due_at = should_notify_at
  174. if self.timed_call is not None:
  175. try:
  176. self.timed_call.cancel()
  177. except (AlreadyCalled, AlreadyCancelled):
  178. pass
  179. self.timed_call = None
  180. if soonest_due_at is not None:
  181. self.timed_call = self.hs.get_reactor().callLater(
  182. self.seconds_until(soonest_due_at), self.on_timer
  183. )
  184. async def save_last_stream_ordering_and_success(
  185. self, last_stream_ordering: int
  186. ) -> None:
  187. self.last_stream_ordering = last_stream_ordering
  188. pusher_still_exists = (
  189. await self.store.update_pusher_last_stream_ordering_and_success(
  190. self.app_id,
  191. self.email,
  192. self.user_id,
  193. last_stream_ordering,
  194. self.clock.time_msec(),
  195. )
  196. )
  197. if not pusher_still_exists:
  198. # The pusher has been deleted while we were processing, so
  199. # lets just stop and return.
  200. self.on_stop()
  201. def seconds_until(self, ts_msec: int) -> float:
  202. secs = (ts_msec - self.clock.time_msec()) / 1000
  203. return max(secs, 0)
  204. def get_room_throttle_ms(self, room_id: str) -> int:
  205. if room_id in self.throttle_params:
  206. return self.throttle_params[room_id].throttle_ms
  207. else:
  208. return 0
  209. def get_room_last_sent_ts(self, room_id: str) -> int:
  210. if room_id in self.throttle_params:
  211. return self.throttle_params[room_id].last_sent_ts
  212. else:
  213. return 0
  214. def room_ready_to_notify_at(self, room_id: str) -> int:
  215. """
  216. Determines whether throttling should prevent us from sending an email
  217. for the given room
  218. Returns:
  219. The timestamp when we are next allowed to send an email notif
  220. for this room
  221. """
  222. last_sent_ts = self.get_room_last_sent_ts(room_id)
  223. throttle_ms = self.get_room_throttle_ms(room_id)
  224. may_send_at = last_sent_ts + throttle_ms
  225. return may_send_at
  226. async def sent_notif_update_throttle(
  227. self, room_id: str, notified_push_action: EmailPushAction
  228. ) -> None:
  229. # We have sent a notification, so update the throttle accordingly.
  230. # If the event that triggered the notif happened more than
  231. # THROTTLE_RESET_AFTER_MS after the previous one that triggered a
  232. # notif, we release the throttle. Otherwise, the throttle is increased.
  233. time_of_previous_notifs = await self.store.get_time_of_last_push_action_before(
  234. notified_push_action.stream_ordering
  235. )
  236. time_of_this_notifs = notified_push_action.received_ts
  237. if time_of_previous_notifs is not None and time_of_this_notifs is not None:
  238. gap = time_of_this_notifs - time_of_previous_notifs
  239. else:
  240. # if we don't know the arrival time of one of the notifs (it was not
  241. # stored prior to email notification code) then assume a gap of
  242. # zero which will just not reset the throttle
  243. gap = 0
  244. current_throttle_ms = self.get_room_throttle_ms(room_id)
  245. if gap > THROTTLE_RESET_AFTER_MS:
  246. new_throttle_ms = self._delay_before_mail_ms
  247. else:
  248. if current_throttle_ms == 0:
  249. new_throttle_ms = self._delay_before_mail_ms
  250. else:
  251. new_throttle_ms = min(
  252. current_throttle_ms * THROTTLE_MULTIPLIER, THROTTLE_MAX_MS
  253. )
  254. self.throttle_params[room_id] = ThrottleParams(
  255. self.clock.time_msec(),
  256. new_throttle_ms,
  257. )
  258. assert self.pusher_id is not None
  259. await self.store.set_throttle_params(
  260. self.pusher_id, room_id, self.throttle_params[room_id]
  261. )
  262. async def send_notification(
  263. self, push_actions: List[EmailPushAction], reason: EmailReason
  264. ) -> None:
  265. logger.info("Sending notif email for user %r", self.user_id)
  266. await self.mailer.send_notification_mail(
  267. self.app_id, self.user_id, self.email, push_actions, reason
  268. )