2016-04-19 07:24:36 -06:00
|
|
|
# Copyright 2016 OpenMarket Ltd
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
2018-07-09 00:09:20 -06:00
|
|
|
import logging
|
2020-12-16 09:25:30 -07:00
|
|
|
from typing import TYPE_CHECKING, Dict, List, Optional
|
2018-07-09 00:09:20 -06:00
|
|
|
|
2016-07-31 08:30:13 -06:00
|
|
|
from twisted.internet.error import AlreadyCalled, AlreadyCancelled
|
2021-03-12 09:37:57 -07:00
|
|
|
from twisted.internet.interfaces import IDelayedCall
|
2016-04-19 07:24:36 -06:00
|
|
|
|
2018-10-22 09:12:11 -06:00
|
|
|
from synapse.metrics.background_process_metrics import run_as_background_process
|
2021-04-22 10:49:11 -06:00
|
|
|
from synapse.push import Pusher, PusherConfig, PusherConfigException, ThrottleParams
|
2020-12-07 07:59:38 -07:00
|
|
|
from synapse.push.mailer import Mailer
|
2021-11-30 04:49:20 -07:00
|
|
|
from synapse.push.push_types import EmailReason
|
|
|
|
from synapse.storage.databases.main.event_push_actions import EmailPushAction
|
2021-04-22 10:49:11 -06:00
|
|
|
from synapse.util.threepids import validate_email
|
2016-04-20 06:02:01 -06:00
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
if TYPE_CHECKING:
|
2021-03-23 05:12:48 -06:00
|
|
|
from synapse.server import HomeServer
|
2020-12-07 07:59:38 -07:00
|
|
|
|
2016-04-19 07:24:36 -06:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
# The amount of time we always wait before ever emailing about a notification
|
|
|
|
# (to give the user a chance to respond to other push or notice the window)
|
2016-05-16 11:58:38 -06:00
|
|
|
DELAY_BEFORE_MAIL_MS = 10 * 60 * 1000
|
2016-04-19 07:24:36 -06:00
|
|
|
|
2016-05-16 11:58:38 -06:00
|
|
|
# THROTTLE is the minimum time between mail notifications sent for a given room.
|
|
|
|
# Each room maintains its own throttle counter, but each new mail notification
|
|
|
|
# sends the pending notifications for all rooms.
|
|
|
|
THROTTLE_START_MS = 10 * 60 * 1000
|
2016-05-23 12:24:11 -06:00
|
|
|
THROTTLE_MAX_MS = 24 * 60 * 60 * 1000 # 24h
|
|
|
|
# THROTTLE_MULTIPLIER = 6 # 10 mins, 1 hour, 6 hours, 24 hours
|
|
|
|
THROTTLE_MULTIPLIER = 144 # 10 mins, 24 hours - i.e. jump straight to 1 day
|
2016-04-19 07:24:36 -06:00
|
|
|
|
|
|
|
# If no event triggers a notification for this long after the previous,
|
|
|
|
# the throttle is released.
|
2016-05-23 12:24:11 -06:00
|
|
|
# 12 hours - a gap of 12 hours in conversation is surely enough to merit a new
|
|
|
|
# notification when things get going again...
|
|
|
|
THROTTLE_RESET_AFTER_MS = 12 * 60 * 60 * 1000
|
|
|
|
|
|
|
|
# does each email include all unread notifs, or just the ones which have happened
|
|
|
|
# since the last mail?
|
2016-06-02 07:07:38 -06:00
|
|
|
# XXX: this is currently broken as it includes ones from parted rooms(!)
|
|
|
|
INCLUDE_ALL_UNREAD_NOTIFS = False
|
2016-04-19 07:24:36 -06:00
|
|
|
|
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
class EmailPusher(Pusher):
|
2016-04-19 07:24:36 -06:00
|
|
|
"""
|
|
|
|
A pusher that sends email notifications about events (approximately)
|
|
|
|
when they happen.
|
|
|
|
This shares quite a bit of code with httpusher: it would be good to
|
|
|
|
factor out the common parts
|
|
|
|
"""
|
2019-06-20 03:32:02 -06:00
|
|
|
|
2020-12-16 09:25:30 -07:00
|
|
|
def __init__(self, hs: "HomeServer", pusher_config: PusherConfig, mailer: Mailer):
|
|
|
|
super().__init__(hs, pusher_config)
|
2017-05-22 10:48:53 -06:00
|
|
|
self.mailer = mailer
|
|
|
|
|
2022-02-23 04:04:02 -07:00
|
|
|
self.store = self.hs.get_datastores().main
|
2020-12-16 09:25:30 -07:00
|
|
|
self.email = pusher_config.pushkey
|
2021-07-15 04:02:43 -06:00
|
|
|
self.timed_call: Optional[IDelayedCall] = None
|
|
|
|
self.throttle_params: Dict[str, ThrottleParams] = {}
|
2020-12-07 07:59:38 -07:00
|
|
|
self._inited = False
|
2016-04-19 07:24:36 -06:00
|
|
|
|
2018-10-24 02:23:33 -06:00
|
|
|
self._is_processing = False
|
2016-04-19 07:52:58 -06:00
|
|
|
|
2021-04-22 10:49:11 -06:00
|
|
|
# Make sure that the email is valid.
|
|
|
|
try:
|
|
|
|
validate_email(self.email)
|
|
|
|
except ValueError:
|
|
|
|
raise PusherConfigException("Invalid email")
|
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
def on_started(self, should_check_for_notifs: bool) -> None:
|
2019-04-02 09:45:33 -06:00
|
|
|
"""Called when this pusher has been started.
|
|
|
|
|
|
|
|
Args:
|
2020-12-07 07:59:38 -07:00
|
|
|
should_check_for_notifs: Whether we should immediately
|
2019-04-02 09:45:33 -06:00
|
|
|
check for push to send. Set to False only if it's known there
|
|
|
|
is nothing to send
|
|
|
|
"""
|
|
|
|
if should_check_for_notifs and self.mailer is not None:
|
2018-10-22 09:12:11 -06:00
|
|
|
self._start_processing()
|
2016-04-19 07:24:36 -06:00
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
def on_stop(self) -> None:
|
2016-04-19 07:52:58 -06:00
|
|
|
if self.timed_call:
|
2016-07-31 08:30:13 -06:00
|
|
|
try:
|
|
|
|
self.timed_call.cancel()
|
|
|
|
except (AlreadyCalled, AlreadyCancelled):
|
|
|
|
pass
|
|
|
|
self.timed_call = None
|
2016-04-19 07:52:58 -06:00
|
|
|
|
2023-10-04 09:28:40 -06:00
|
|
|
def on_new_receipts(self) -> None:
|
2016-04-21 12:19:07 -06:00
|
|
|
# We could wake up and cancel the timer but there tend to be quite a
|
|
|
|
# lot of read receipts so it's probably less work to just let the
|
|
|
|
# timer fire
|
2018-10-22 09:12:11 -06:00
|
|
|
pass
|
2016-04-21 12:19:07 -06:00
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
def on_timer(self) -> None:
|
2016-04-19 07:24:36 -06:00
|
|
|
self.timed_call = None
|
2018-10-22 09:12:11 -06:00
|
|
|
self._start_processing()
|
2016-04-19 07:24:36 -06:00
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
def _start_processing(self) -> None:
|
2018-10-24 02:23:33 -06:00
|
|
|
if self._is_processing:
|
2016-04-19 07:52:58 -06:00
|
|
|
return
|
|
|
|
|
2018-10-22 09:12:11 -06:00
|
|
|
run_as_background_process("emailpush.process", self._process)
|
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
def _pause_processing(self) -> None:
|
2019-06-07 05:10:23 -06:00
|
|
|
"""Used by tests to temporarily pause processing of events.
|
|
|
|
|
|
|
|
Asserts that its not currently processing.
|
|
|
|
"""
|
|
|
|
assert not self._is_processing
|
|
|
|
self._is_processing = True
|
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
def _resume_processing(self) -> None:
|
2019-06-07 05:10:23 -06:00
|
|
|
"""Used by tests to resume processing of events after pausing."""
|
|
|
|
assert self._is_processing
|
|
|
|
self._is_processing = False
|
|
|
|
self._start_processing()
|
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
async def _process(self) -> None:
|
2018-10-24 02:23:33 -06:00
|
|
|
# we should never get here if we are already processing
|
|
|
|
assert not self._is_processing
|
|
|
|
|
2018-10-22 09:12:11 -06:00
|
|
|
try:
|
2018-10-24 02:23:33 -06:00
|
|
|
self._is_processing = True
|
2018-10-22 09:12:11 -06:00
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
if not self._inited:
|
2018-10-22 09:12:11 -06:00
|
|
|
# this is our first loop: load up the throttle params
|
2020-12-16 09:25:30 -07:00
|
|
|
assert self.pusher_id is not None
|
2020-05-22 06:41:11 -06:00
|
|
|
self.throttle_params = await self.store.get_throttle_params_by_room(
|
2018-10-22 09:12:11 -06:00
|
|
|
self.pusher_id
|
|
|
|
)
|
2020-12-07 07:59:38 -07:00
|
|
|
self._inited = True
|
2018-10-22 09:12:11 -06:00
|
|
|
|
2018-10-22 09:12:11 -06:00
|
|
|
# if the max ordering changes while we're running _unsafe_process,
|
|
|
|
# call it again, and so on until we've caught up.
|
|
|
|
while True:
|
|
|
|
starting_max_ordering = self.max_stream_ordering
|
2016-04-19 07:52:58 -06:00
|
|
|
try:
|
2020-05-22 06:41:11 -06:00
|
|
|
await self._unsafe_process()
|
2018-10-22 09:12:11 -06:00
|
|
|
except Exception:
|
|
|
|
logger.exception("Exception processing notifs")
|
|
|
|
if self.max_stream_ordering == starting_max_ordering:
|
|
|
|
break
|
|
|
|
finally:
|
2018-10-24 02:23:33 -06:00
|
|
|
self._is_processing = False
|
2016-04-19 07:52:58 -06:00
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
async def _unsafe_process(self) -> None:
|
2016-04-19 07:52:58 -06:00
|
|
|
"""
|
|
|
|
Main logic of the push loop without the wrapper function that sets
|
|
|
|
up logging, measures and guards against multiple instances of it
|
|
|
|
being run.
|
|
|
|
"""
|
2016-05-23 12:24:11 -06:00
|
|
|
start = 0 if INCLUDE_ALL_UNREAD_NOTIFS else self.last_stream_ordering
|
2020-12-07 07:59:38 -07:00
|
|
|
unprocessed = (
|
|
|
|
await self.store.get_unread_push_actions_for_user_in_range_for_email(
|
|
|
|
self.user_id, start, self.max_stream_ordering
|
2021-02-16 15:32:34 -07:00
|
|
|
)
|
2020-12-07 07:59:38 -07:00
|
|
|
)
|
2016-04-19 07:24:36 -06:00
|
|
|
|
2021-07-15 04:02:43 -06:00
|
|
|
soonest_due_at: Optional[int] = None
|
2016-04-19 07:24:36 -06:00
|
|
|
|
2016-10-18 03:52:47 -06:00
|
|
|
if not unprocessed:
|
2020-05-22 06:41:11 -06:00
|
|
|
await self.save_last_stream_ordering_and_success(self.max_stream_ordering)
|
2016-10-18 03:52:47 -06:00
|
|
|
return
|
|
|
|
|
2016-04-19 07:24:36 -06:00
|
|
|
for push_action in unprocessed:
|
2021-12-21 06:25:34 -07:00
|
|
|
received_at = push_action.received_ts
|
2016-04-19 07:24:36 -06:00
|
|
|
if received_at is None:
|
|
|
|
received_at = 0
|
|
|
|
notif_ready_at = received_at + DELAY_BEFORE_MAIL_MS
|
|
|
|
|
2021-12-21 06:25:34 -07:00
|
|
|
room_ready_at = self.room_ready_to_notify_at(push_action.room_id)
|
2016-04-19 07:24:36 -06:00
|
|
|
|
|
|
|
should_notify_at = max(notif_ready_at, room_ready_at)
|
|
|
|
|
Encode JSON responses on a thread in C, mk2 (#10905)
Currently we use `JsonEncoder.iterencode` to write JSON responses, which ensures that we don't block the main reactor thread when encoding huge objects. The downside to this is that `iterencode` falls back to using a pure Python encoder that is *much* less efficient and can easily burn a lot of CPU for huge responses. To fix this, while still ensuring we don't block the reactor loop, we encode the JSON on a threadpool using the standard `JsonEncoder.encode` functions, which is backed by a C library.
Doing so, however, requires `respond_with_json` to have access to the reactor, which it previously didn't. There are two ways of doing this:
1. threading through the reactor object, which is a bit fiddly as e.g. `DirectServeJsonResource` doesn't currently take a reactor, but is exposed to modules and so is a PITA to change; or
2. expose the reactor in `SynapseRequest`, which requires updating a bunch of servlet types.
I went with the latter as that is just a mechanical change, and I think makes sense as a request already has a reactor associated with it (via its http channel).
2021-09-28 03:37:58 -06:00
|
|
|
if should_notify_at <= self.clock.time_msec():
|
2016-04-19 07:24:36 -06:00
|
|
|
# one of our notifications is ready for sending, so we send
|
|
|
|
# *one* email updating the user on their notifications,
|
|
|
|
# we then consider all previously outstanding notifications
|
|
|
|
# to be delivered.
|
2016-05-16 11:58:38 -06:00
|
|
|
|
2021-11-30 04:49:20 -07:00
|
|
|
reason: EmailReason = {
|
2021-12-21 06:25:34 -07:00
|
|
|
"room_id": push_action.room_id,
|
2016-05-16 11:58:38 -06:00
|
|
|
"now": self.clock.time_msec(),
|
|
|
|
"received_at": received_at,
|
|
|
|
"delay_before_mail_ms": DELAY_BEFORE_MAIL_MS,
|
2021-12-21 06:25:34 -07:00
|
|
|
"last_sent_ts": self.get_room_last_sent_ts(push_action.room_id),
|
|
|
|
"throttle_ms": self.get_room_throttle_ms(push_action.room_id),
|
2016-05-16 11:58:38 -06:00
|
|
|
}
|
|
|
|
|
2020-05-22 06:41:11 -06:00
|
|
|
await self.send_notification(unprocessed, reason)
|
2016-04-19 07:24:36 -06:00
|
|
|
|
2020-05-22 06:41:11 -06:00
|
|
|
await self.save_last_stream_ordering_and_success(
|
2021-12-21 06:25:34 -07:00
|
|
|
max(ea.stream_ordering for ea in unprocessed)
|
2016-04-19 07:24:36 -06:00
|
|
|
)
|
2016-05-23 12:24:11 -06:00
|
|
|
|
|
|
|
# we update the throttle on all the possible unprocessed push actions
|
|
|
|
for ea in unprocessed:
|
2021-12-21 06:25:34 -07:00
|
|
|
await self.sent_notif_update_throttle(ea.room_id, ea)
|
2016-04-29 07:31:27 -06:00
|
|
|
break
|
2016-04-19 07:24:36 -06:00
|
|
|
else:
|
|
|
|
if soonest_due_at is None or should_notify_at < soonest_due_at:
|
|
|
|
soonest_due_at = should_notify_at
|
|
|
|
|
2016-04-19 07:52:58 -06:00
|
|
|
if self.timed_call is not None:
|
2016-07-31 08:30:13 -06:00
|
|
|
try:
|
|
|
|
self.timed_call.cancel()
|
|
|
|
except (AlreadyCalled, AlreadyCancelled):
|
|
|
|
pass
|
2016-04-19 07:52:58 -06:00
|
|
|
self.timed_call = None
|
2016-04-19 07:24:36 -06:00
|
|
|
|
|
|
|
if soonest_due_at is not None:
|
2018-06-25 07:08:28 -06:00
|
|
|
self.timed_call = self.hs.get_reactor().callLater(
|
2016-04-19 07:24:36 -06:00
|
|
|
self.seconds_until(soonest_due_at), self.on_timer
|
|
|
|
)
|
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
async def save_last_stream_ordering_and_success(
|
2021-01-05 08:53:15 -07:00
|
|
|
self, last_stream_ordering: int
|
2020-12-07 07:59:38 -07:00
|
|
|
) -> None:
|
2016-04-19 07:24:36 -06:00
|
|
|
self.last_stream_ordering = last_stream_ordering
|
2020-05-22 06:41:11 -06:00
|
|
|
pusher_still_exists = (
|
|
|
|
await self.store.update_pusher_last_stream_ordering_and_success(
|
2019-10-31 09:43:24 -06:00
|
|
|
self.app_id,
|
|
|
|
self.email,
|
|
|
|
self.user_id,
|
|
|
|
last_stream_ordering,
|
|
|
|
self.clock.time_msec(),
|
2021-02-16 15:32:34 -07:00
|
|
|
)
|
2016-04-19 07:24:36 -06:00
|
|
|
)
|
2019-08-01 06:41:27 -06:00
|
|
|
if not pusher_still_exists:
|
|
|
|
# The pusher has been deleted while we were processing, so
|
|
|
|
# lets just stop and return.
|
|
|
|
self.on_stop()
|
2016-04-19 07:24:36 -06:00
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
def seconds_until(self, ts_msec: int) -> float:
|
2017-02-22 05:08:14 -07:00
|
|
|
secs = (ts_msec - self.clock.time_msec()) / 1000
|
|
|
|
return max(secs, 0)
|
2016-04-19 07:24:36 -06:00
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
def get_room_throttle_ms(self, room_id: str) -> int:
|
2016-04-19 07:24:36 -06:00
|
|
|
if room_id in self.throttle_params:
|
2020-12-16 09:25:30 -07:00
|
|
|
return self.throttle_params[room_id].throttle_ms
|
2016-04-19 07:24:36 -06:00
|
|
|
else:
|
|
|
|
return 0
|
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
def get_room_last_sent_ts(self, room_id: str) -> int:
|
2016-04-19 07:24:36 -06:00
|
|
|
if room_id in self.throttle_params:
|
2020-12-16 09:25:30 -07:00
|
|
|
return self.throttle_params[room_id].last_sent_ts
|
2016-04-19 07:24:36 -06:00
|
|
|
else:
|
|
|
|
return 0
|
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
def room_ready_to_notify_at(self, room_id: str) -> int:
|
2016-04-19 07:24:36 -06:00
|
|
|
"""
|
|
|
|
Determines whether throttling should prevent us from sending an email
|
|
|
|
for the given room
|
2020-12-07 07:59:38 -07:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
The timestamp when we are next allowed to send an email notif
|
|
|
|
for this room
|
2016-04-19 07:24:36 -06:00
|
|
|
"""
|
|
|
|
last_sent_ts = self.get_room_last_sent_ts(room_id)
|
|
|
|
throttle_ms = self.get_room_throttle_ms(room_id)
|
|
|
|
|
|
|
|
may_send_at = last_sent_ts + throttle_ms
|
|
|
|
return may_send_at
|
|
|
|
|
2020-12-07 07:59:38 -07:00
|
|
|
async def sent_notif_update_throttle(
|
2021-11-30 04:49:20 -07:00
|
|
|
self, room_id: str, notified_push_action: EmailPushAction
|
2020-12-07 07:59:38 -07:00
|
|
|
) -> None:
|
2016-04-19 07:24:36 -06:00
|
|
|
# We have sent a notification, so update the throttle accordingly.
|
|
|
|
# If the event that triggered the notif happened more than
|
|
|
|
# THROTTLE_RESET_AFTER_MS after the previous one that triggered a
|
|
|
|
# notif, we release the throttle. Otherwise, the throttle is increased.
|
2020-05-22 06:41:11 -06:00
|
|
|
time_of_previous_notifs = await self.store.get_time_of_last_push_action_before(
|
2021-12-21 06:25:34 -07:00
|
|
|
notified_push_action.stream_ordering
|
2016-04-19 07:24:36 -06:00
|
|
|
)
|
|
|
|
|
2021-12-21 06:25:34 -07:00
|
|
|
time_of_this_notifs = notified_push_action.received_ts
|
2016-04-19 07:24:36 -06:00
|
|
|
|
|
|
|
if time_of_previous_notifs is not None and time_of_this_notifs is not None:
|
|
|
|
gap = time_of_this_notifs - time_of_previous_notifs
|
|
|
|
else:
|
|
|
|
# if we don't know the arrival time of one of the notifs (it was not
|
|
|
|
# stored prior to email notification code) then assume a gap of
|
|
|
|
# zero which will just not reset the throttle
|
|
|
|
gap = 0
|
|
|
|
|
|
|
|
current_throttle_ms = self.get_room_throttle_ms(room_id)
|
|
|
|
|
|
|
|
if gap > THROTTLE_RESET_AFTER_MS:
|
|
|
|
new_throttle_ms = THROTTLE_START_MS
|
|
|
|
else:
|
|
|
|
if current_throttle_ms == 0:
|
|
|
|
new_throttle_ms = THROTTLE_START_MS
|
|
|
|
else:
|
|
|
|
new_throttle_ms = min(
|
2016-04-29 13:14:55 -06:00
|
|
|
current_throttle_ms * THROTTLE_MULTIPLIER, THROTTLE_MAX_MS
|
2016-04-19 07:24:36 -06:00
|
|
|
)
|
2020-12-16 09:25:30 -07:00
|
|
|
self.throttle_params[room_id] = ThrottleParams(
|
|
|
|
self.clock.time_msec(),
|
|
|
|
new_throttle_ms,
|
|
|
|
)
|
|
|
|
assert self.pusher_id is not None
|
2020-05-22 06:41:11 -06:00
|
|
|
await self.store.set_throttle_params(
|
2016-04-19 07:24:36 -06:00
|
|
|
self.pusher_id, room_id, self.throttle_params[room_id]
|
|
|
|
)
|
|
|
|
|
2021-11-30 04:49:20 -07:00
|
|
|
async def send_notification(
|
|
|
|
self, push_actions: List[EmailPushAction], reason: EmailReason
|
|
|
|
) -> None:
|
2016-04-20 06:02:01 -06:00
|
|
|
logger.info("Sending notif email for user %r", self.user_id)
|
2016-05-16 11:58:38 -06:00
|
|
|
|
2020-05-22 06:41:11 -06:00
|
|
|
await self.mailer.send_notification_mail(
|
2016-06-02 04:44:15 -06:00
|
|
|
self.app_id, self.user_id, self.email, push_actions, reason
|
2016-04-20 06:02:01 -06:00
|
|
|
)
|