emailpusher.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 OpenMarket 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. from typing import TYPE_CHECKING, Dict, List, Optional
  17. from twisted.internet.base import DelayedCall
  18. from twisted.internet.error import AlreadyCalled, AlreadyCancelled
  19. from synapse.metrics.background_process_metrics import run_as_background_process
  20. from synapse.push import Pusher, PusherConfig, ThrottleParams
  21. from synapse.push.mailer import Mailer
  22. if TYPE_CHECKING:
  23. from synapse.app.homeserver 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[DelayedCall]
  57. self.throttle_params = {} # type: Dict[str, ThrottleParams]
  58. self._inited = False
  59. self._is_processing = False
  60. def on_started(self, should_check_for_notifs: bool) -> None:
  61. """Called when this pusher has been started.
  62. Args:
  63. should_check_for_notifs: Whether we should immediately
  64. check for push to send. Set to False only if it's known there
  65. is nothing to send
  66. """
  67. if should_check_for_notifs and self.mailer is not None:
  68. self._start_processing()
  69. def on_stop(self) -> None:
  70. if self.timed_call:
  71. try:
  72. self.timed_call.cancel()
  73. except (AlreadyCalled, AlreadyCancelled):
  74. pass
  75. self.timed_call = None
  76. def on_new_receipts(self, min_stream_id: int, max_stream_id: int) -> None:
  77. # We could wake up and cancel the timer but there tend to be quite a
  78. # lot of read receipts so it's probably less work to just let the
  79. # timer fire
  80. pass
  81. def on_timer(self) -> None:
  82. self.timed_call = None
  83. self._start_processing()
  84. def _start_processing(self) -> None:
  85. if self._is_processing:
  86. return
  87. run_as_background_process("emailpush.process", self._process)
  88. def _pause_processing(self) -> None:
  89. """Used by tests to temporarily pause processing of events.
  90. Asserts that its not currently processing.
  91. """
  92. assert not self._is_processing
  93. self._is_processing = True
  94. def _resume_processing(self) -> None:
  95. """Used by tests to resume processing of events after pausing.
  96. """
  97. assert self._is_processing
  98. self._is_processing = False
  99. self._start_processing()
  100. async def _process(self) -> None:
  101. # we should never get here if we are already processing
  102. assert not self._is_processing
  103. try:
  104. self._is_processing = True
  105. if not self._inited:
  106. # this is our first loop: load up the throttle params
  107. assert self.pusher_id is not None
  108. self.throttle_params = await self.store.get_throttle_params_by_room(
  109. self.pusher_id
  110. )
  111. self._inited = True
  112. # if the max ordering changes while we're running _unsafe_process,
  113. # call it again, and so on until we've caught up.
  114. while True:
  115. starting_max_ordering = self.max_stream_ordering
  116. try:
  117. await self._unsafe_process()
  118. except Exception:
  119. logger.exception("Exception processing notifs")
  120. if self.max_stream_ordering == starting_max_ordering:
  121. break
  122. finally:
  123. self._is_processing = False
  124. async def _unsafe_process(self) -> None:
  125. """
  126. Main logic of the push loop without the wrapper function that sets
  127. up logging, measures and guards against multiple instances of it
  128. being run.
  129. """
  130. start = 0 if INCLUDE_ALL_UNREAD_NOTIFS else self.last_stream_ordering
  131. assert start is not None
  132. unprocessed = await self.store.get_unread_push_actions_for_user_in_range_for_email(
  133. self.user_id, start, self.max_stream_ordering
  134. )
  135. soonest_due_at = None # type: Optional[int]
  136. if not unprocessed:
  137. await self.save_last_stream_ordering_and_success(self.max_stream_ordering)
  138. return
  139. for push_action in unprocessed:
  140. received_at = push_action["received_ts"]
  141. if received_at is None:
  142. received_at = 0
  143. notif_ready_at = received_at + DELAY_BEFORE_MAIL_MS
  144. room_ready_at = self.room_ready_to_notify_at(push_action["room_id"])
  145. should_notify_at = max(notif_ready_at, room_ready_at)
  146. if should_notify_at < self.clock.time_msec():
  147. # one of our notifications is ready for sending, so we send
  148. # *one* email updating the user on their notifications,
  149. # we then consider all previously outstanding notifications
  150. # to be delivered.
  151. reason = {
  152. "room_id": push_action["room_id"],
  153. "now": self.clock.time_msec(),
  154. "received_at": received_at,
  155. "delay_before_mail_ms": DELAY_BEFORE_MAIL_MS,
  156. "last_sent_ts": self.get_room_last_sent_ts(push_action["room_id"]),
  157. "throttle_ms": self.get_room_throttle_ms(push_action["room_id"]),
  158. }
  159. await self.send_notification(unprocessed, reason)
  160. await self.save_last_stream_ordering_and_success(
  161. max(ea["stream_ordering"] for ea in unprocessed)
  162. )
  163. # we update the throttle on all the possible unprocessed push actions
  164. for ea in unprocessed:
  165. await self.sent_notif_update_throttle(ea["room_id"], ea)
  166. break
  167. else:
  168. if soonest_due_at is None or should_notify_at < soonest_due_at:
  169. soonest_due_at = should_notify_at
  170. if self.timed_call is not None:
  171. try:
  172. self.timed_call.cancel()
  173. except (AlreadyCalled, AlreadyCancelled):
  174. pass
  175. self.timed_call = None
  176. if soonest_due_at is not None:
  177. self.timed_call = self.hs.get_reactor().callLater(
  178. self.seconds_until(soonest_due_at), self.on_timer
  179. )
  180. async def save_last_stream_ordering_and_success(
  181. self, last_stream_ordering: Optional[int]
  182. ) -> None:
  183. if last_stream_ordering is None:
  184. # This happens if we haven't yet processed anything
  185. return
  186. self.last_stream_ordering = last_stream_ordering
  187. pusher_still_exists = await self.store.update_pusher_last_stream_ordering_and_success(
  188. self.app_id,
  189. self.email,
  190. self.user_id,
  191. last_stream_ordering,
  192. self.clock.time_msec(),
  193. )
  194. if not pusher_still_exists:
  195. # The pusher has been deleted while we were processing, so
  196. # lets just stop and return.
  197. self.on_stop()
  198. def seconds_until(self, ts_msec: int) -> float:
  199. secs = (ts_msec - self.clock.time_msec()) / 1000
  200. return max(secs, 0)
  201. def get_room_throttle_ms(self, room_id: str) -> int:
  202. if room_id in self.throttle_params:
  203. return self.throttle_params[room_id].throttle_ms
  204. else:
  205. return 0
  206. def get_room_last_sent_ts(self, room_id: str) -> int:
  207. if room_id in self.throttle_params:
  208. return self.throttle_params[room_id].last_sent_ts
  209. else:
  210. return 0
  211. def room_ready_to_notify_at(self, room_id: str) -> int:
  212. """
  213. Determines whether throttling should prevent us from sending an email
  214. for the given room
  215. Returns:
  216. The timestamp when we are next allowed to send an email notif
  217. for this room
  218. """
  219. last_sent_ts = self.get_room_last_sent_ts(room_id)
  220. throttle_ms = self.get_room_throttle_ms(room_id)
  221. may_send_at = last_sent_ts + throttle_ms
  222. return may_send_at
  223. async def sent_notif_update_throttle(
  224. self, room_id: str, notified_push_action: dict
  225. ) -> None:
  226. # We have sent a notification, so update the throttle accordingly.
  227. # If the event that triggered the notif happened more than
  228. # THROTTLE_RESET_AFTER_MS after the previous one that triggered a
  229. # notif, we release the throttle. Otherwise, the throttle is increased.
  230. time_of_previous_notifs = await self.store.get_time_of_last_push_action_before(
  231. notified_push_action["stream_ordering"]
  232. )
  233. time_of_this_notifs = notified_push_action["received_ts"]
  234. if time_of_previous_notifs is not None and time_of_this_notifs is not None:
  235. gap = time_of_this_notifs - time_of_previous_notifs
  236. else:
  237. # if we don't know the arrival time of one of the notifs (it was not
  238. # stored prior to email notification code) then assume a gap of
  239. # zero which will just not reset the throttle
  240. gap = 0
  241. current_throttle_ms = self.get_room_throttle_ms(room_id)
  242. if gap > THROTTLE_RESET_AFTER_MS:
  243. new_throttle_ms = THROTTLE_START_MS
  244. else:
  245. if current_throttle_ms == 0:
  246. new_throttle_ms = THROTTLE_START_MS
  247. else:
  248. new_throttle_ms = min(
  249. current_throttle_ms * THROTTLE_MULTIPLIER, THROTTLE_MAX_MS
  250. )
  251. self.throttle_params[room_id] = ThrottleParams(
  252. self.clock.time_msec(), new_throttle_ms,
  253. )
  254. assert self.pusher_id is not None
  255. await self.store.set_throttle_params(
  256. self.pusher_id, room_id, self.throttle_params[room_id]
  257. )
  258. async def send_notification(self, push_actions: List[dict], reason: dict) -> None:
  259. logger.info("Sending notif email for user %r", self.user_id)
  260. await self.mailer.send_notification_mail(
  261. self.app_id, self.user_id, self.email, push_actions, reason
  262. )