emailpusher.py 12 KB

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