emailpusher.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 twisted.internet.error import AlreadyCalled, AlreadyCancelled
  17. from synapse.metrics.background_process_metrics import run_as_background_process
  18. logger = logging.getLogger(__name__)
  19. # The amount of time we always wait before ever emailing about a notification
  20. # (to give the user a chance to respond to other push or notice the window)
  21. DELAY_BEFORE_MAIL_MS = 10 * 60 * 1000
  22. # THROTTLE is the minimum time between mail notifications sent for a given room.
  23. # Each room maintains its own throttle counter, but each new mail notification
  24. # sends the pending notifications for all rooms.
  25. THROTTLE_START_MS = 10 * 60 * 1000
  26. THROTTLE_MAX_MS = 24 * 60 * 60 * 1000 # 24h
  27. # THROTTLE_MULTIPLIER = 6 # 10 mins, 1 hour, 6 hours, 24 hours
  28. THROTTLE_MULTIPLIER = 144 # 10 mins, 24 hours - i.e. jump straight to 1 day
  29. # If no event triggers a notification for this long after the previous,
  30. # the throttle is released.
  31. # 12 hours - a gap of 12 hours in conversation is surely enough to merit a new
  32. # notification when things get going again...
  33. THROTTLE_RESET_AFTER_MS = 12 * 60 * 60 * 1000
  34. # does each email include all unread notifs, or just the ones which have happened
  35. # since the last mail?
  36. # XXX: this is currently broken as it includes ones from parted rooms(!)
  37. INCLUDE_ALL_UNREAD_NOTIFS = False
  38. class EmailPusher:
  39. """
  40. A pusher that sends email notifications about events (approximately)
  41. when they happen.
  42. This shares quite a bit of code with httpusher: it would be good to
  43. factor out the common parts
  44. """
  45. def __init__(self, hs, pusherdict, mailer):
  46. self.hs = hs
  47. self.mailer = mailer
  48. self.store = self.hs.get_datastore()
  49. self.clock = self.hs.get_clock()
  50. self.pusher_id = pusherdict["id"]
  51. self.user_id = pusherdict["user_name"]
  52. self.app_id = pusherdict["app_id"]
  53. self.email = pusherdict["pushkey"]
  54. self.last_stream_ordering = pusherdict["last_stream_ordering"]
  55. self.timed_call = None
  56. self.throttle_params = None
  57. # See httppusher
  58. self.max_stream_ordering = None
  59. self._is_processing = False
  60. def on_started(self, should_check_for_notifs):
  61. """Called when this pusher has been started.
  62. Args:
  63. should_check_for_notifs (bool): 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):
  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_notifications(self, max_stream_ordering):
  77. if self.max_stream_ordering:
  78. self.max_stream_ordering = max(
  79. max_stream_ordering, self.max_stream_ordering
  80. )
  81. else:
  82. self.max_stream_ordering = max_stream_ordering
  83. self._start_processing()
  84. def on_new_receipts(self, min_stream_id, max_stream_id):
  85. # We could wake up and cancel the timer but there tend to be quite a
  86. # lot of read receipts so it's probably less work to just let the
  87. # timer fire
  88. pass
  89. def on_timer(self):
  90. self.timed_call = None
  91. self._start_processing()
  92. def _start_processing(self):
  93. if self._is_processing:
  94. return
  95. run_as_background_process("emailpush.process", self._process)
  96. def _pause_processing(self):
  97. """Used by tests to temporarily pause processing of events.
  98. Asserts that its not currently processing.
  99. """
  100. assert not self._is_processing
  101. self._is_processing = True
  102. def _resume_processing(self):
  103. """Used by tests to resume processing of events after pausing.
  104. """
  105. assert self._is_processing
  106. self._is_processing = False
  107. self._start_processing()
  108. async def _process(self):
  109. # we should never get here if we are already processing
  110. assert not self._is_processing
  111. try:
  112. self._is_processing = True
  113. if self.throttle_params is None:
  114. # this is our first loop: load up the throttle params
  115. self.throttle_params = await self.store.get_throttle_params_by_room(
  116. self.pusher_id
  117. )
  118. # if the max ordering changes while we're running _unsafe_process,
  119. # call it again, and so on until we've caught up.
  120. while True:
  121. starting_max_ordering = self.max_stream_ordering
  122. try:
  123. await self._unsafe_process()
  124. except Exception:
  125. logger.exception("Exception processing notifs")
  126. if self.max_stream_ordering == starting_max_ordering:
  127. break
  128. finally:
  129. self._is_processing = False
  130. async def _unsafe_process(self):
  131. """
  132. Main logic of the push loop without the wrapper function that sets
  133. up logging, measures and guards against multiple instances of it
  134. being run.
  135. """
  136. start = 0 if INCLUDE_ALL_UNREAD_NOTIFS else self.last_stream_ordering
  137. fn = self.store.get_unread_push_actions_for_user_in_range_for_email
  138. unprocessed = await fn(self.user_id, start, self.max_stream_ordering)
  139. soonest_due_at = 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 + 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 = {
  156. "room_id": push_action["room_id"],
  157. "now": self.clock.time_msec(),
  158. "received_at": received_at,
  159. "delay_before_mail_ms": 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(self, last_stream_ordering):
  185. if last_stream_ordering is None:
  186. # This happens if we haven't yet processed anything
  187. return
  188. self.last_stream_ordering = last_stream_ordering
  189. pusher_still_exists = 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. if not pusher_still_exists:
  197. # The pusher has been deleted while we were processing, so
  198. # lets just stop and return.
  199. self.on_stop()
  200. def seconds_until(self, ts_msec):
  201. secs = (ts_msec - self.clock.time_msec()) / 1000
  202. return max(secs, 0)
  203. def get_room_throttle_ms(self, room_id):
  204. if room_id in self.throttle_params:
  205. return self.throttle_params[room_id]["throttle_ms"]
  206. else:
  207. return 0
  208. def get_room_last_sent_ts(self, room_id):
  209. if room_id in self.throttle_params:
  210. return self.throttle_params[room_id]["last_sent_ts"]
  211. else:
  212. return 0
  213. def room_ready_to_notify_at(self, room_id):
  214. """
  215. Determines whether throttling should prevent us from sending an email
  216. for the given room
  217. Returns: The timestamp when we are next allowed to send an email notif
  218. for this room
  219. """
  220. last_sent_ts = self.get_room_last_sent_ts(room_id)
  221. throttle_ms = self.get_room_throttle_ms(room_id)
  222. may_send_at = last_sent_ts + throttle_ms
  223. return may_send_at
  224. async def sent_notif_update_throttle(self, room_id, notified_push_action):
  225. # We have sent a notification, so update the throttle accordingly.
  226. # If the event that triggered the notif happened more than
  227. # THROTTLE_RESET_AFTER_MS after the previous one that triggered a
  228. # notif, we release the throttle. Otherwise, the throttle is increased.
  229. time_of_previous_notifs = await self.store.get_time_of_last_push_action_before(
  230. notified_push_action["stream_ordering"]
  231. )
  232. time_of_this_notifs = notified_push_action["received_ts"]
  233. if time_of_previous_notifs is not None and time_of_this_notifs is not None:
  234. gap = time_of_this_notifs - time_of_previous_notifs
  235. else:
  236. # if we don't know the arrival time of one of the notifs (it was not
  237. # stored prior to email notification code) then assume a gap of
  238. # zero which will just not reset the throttle
  239. gap = 0
  240. current_throttle_ms = self.get_room_throttle_ms(room_id)
  241. if gap > THROTTLE_RESET_AFTER_MS:
  242. new_throttle_ms = THROTTLE_START_MS
  243. else:
  244. if current_throttle_ms == 0:
  245. new_throttle_ms = THROTTLE_START_MS
  246. else:
  247. new_throttle_ms = min(
  248. current_throttle_ms * THROTTLE_MULTIPLIER, THROTTLE_MAX_MS
  249. )
  250. self.throttle_params[room_id] = {
  251. "last_sent_ts": self.clock.time_msec(),
  252. "throttle_ms": new_throttle_ms,
  253. }
  254. await self.store.set_throttle_params(
  255. self.pusher_id, room_id, self.throttle_params[room_id]
  256. )
  257. async def send_notification(self, push_actions, reason):
  258. logger.info("Sending notif email for user %r", self.user_id)
  259. await self.mailer.send_notification_mail(
  260. self.app_id, self.user_id, self.email, push_actions, reason
  261. )