2016-01-06 21:26:29 -07:00
|
|
|
# Copyright 2015, 2016 OpenMarket Ltd
|
2015-03-05 09:30:33 -07:00
|
|
|
#
|
|
|
|
# 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.
|
|
|
|
"""
|
|
|
|
This module controls the reliability for application service transactions.
|
|
|
|
|
|
|
|
The nominal flow through this module looks like:
|
2015-03-16 07:15:40 -06:00
|
|
|
__________
|
|
|
|
1---ASa[e]-->| Service |--> Queue ASa[f]
|
|
|
|
2----ASb[e]->| Queuer |
|
|
|
|
3--ASa[f]--->|__________|-----------+ ASa[e], ASb[e]
|
|
|
|
V
|
2015-03-05 09:30:33 -07:00
|
|
|
-````````- +------------+
|
|
|
|
|````````|<--StoreTxn-|Transaction |
|
2015-03-05 10:35:07 -07:00
|
|
|
|Database| | Controller |---> SEND TO AS
|
2015-03-05 09:30:33 -07:00
|
|
|
`--------` +------------+
|
|
|
|
What happens on SEND TO AS depends on the state of the Application Service:
|
|
|
|
- If the AS is marked as DOWN, do nothing.
|
|
|
|
- If the AS is marked as UP, send the transaction.
|
|
|
|
* SUCCESS : Increment where the AS is up to txn-wise and nuke the txn
|
|
|
|
contents from the db.
|
|
|
|
* FAILURE : Marked AS as DOWN and start Recoverer.
|
|
|
|
|
|
|
|
Recoverer attempts to recover ASes who have died. The flow for this looks like:
|
|
|
|
,--------------------- backoff++ --------------.
|
|
|
|
V |
|
|
|
|
START ---> Wait exp ------> Get oldest txn ID from ----> FAILURE
|
|
|
|
backoff DB and try to send it
|
2015-03-06 03:25:50 -07:00
|
|
|
^ |___________
|
|
|
|
Mark AS as | V
|
|
|
|
UP & quit +---------- YES SUCCESS
|
|
|
|
| | |
|
|
|
|
NO <--- Have more txns? <------ Mark txn success & nuke <-+
|
2015-03-05 09:30:33 -07:00
|
|
|
from db; incr AS pos.
|
2015-03-05 10:45:52 -07:00
|
|
|
Reset backoff.
|
2015-03-05 10:35:07 -07:00
|
|
|
|
|
|
|
This is all tied together by the AppServiceScheduler which DIs the required
|
|
|
|
components.
|
2015-03-05 09:30:33 -07:00
|
|
|
"""
|
2018-07-09 00:09:20 -06:00
|
|
|
import logging
|
2022-02-01 07:13:38 -07:00
|
|
|
from typing import (
|
|
|
|
TYPE_CHECKING,
|
|
|
|
Awaitable,
|
|
|
|
Callable,
|
|
|
|
Collection,
|
|
|
|
Dict,
|
2022-02-24 10:55:45 -07:00
|
|
|
Iterable,
|
2022-02-01 07:13:38 -07:00
|
|
|
List,
|
|
|
|
Optional,
|
|
|
|
Set,
|
2022-02-24 10:55:45 -07:00
|
|
|
Tuple,
|
2022-02-01 07:13:38 -07:00
|
|
|
)
|
2018-07-09 00:09:20 -06:00
|
|
|
|
2022-02-24 10:55:45 -07:00
|
|
|
from synapse.appservice import (
|
|
|
|
ApplicationService,
|
|
|
|
ApplicationServiceState,
|
2022-11-28 09:17:29 -07:00
|
|
|
TransactionOneTimeKeysCount,
|
2022-02-24 10:55:45 -07:00
|
|
|
TransactionUnusedFallbackKeys,
|
|
|
|
)
|
2021-12-14 10:02:46 -07:00
|
|
|
from synapse.appservice.api import ApplicationServiceApi
|
2020-10-15 10:33:28 -06:00
|
|
|
from synapse.events import EventBase
|
2019-07-03 08:07:04 -06:00
|
|
|
from synapse.logging.context import run_in_background
|
2018-12-04 02:53:49 -07:00
|
|
|
from synapse.metrics.background_process_metrics import run_as_background_process
|
2021-12-14 10:02:46 -07:00
|
|
|
from synapse.storage.databases.main import DataStore
|
2022-03-30 07:39:27 -06:00
|
|
|
from synapse.types import DeviceListUpdates, JsonDict
|
2021-12-14 10:02:46 -07:00
|
|
|
from synapse.util import Clock
|
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
from synapse.server import HomeServer
|
2016-08-17 05:03:04 -06:00
|
|
|
|
2015-03-06 08:12:24 -07:00
|
|
|
logger = logging.getLogger(__name__)
|
2015-03-06 04:50:27 -07:00
|
|
|
|
2015-03-05 09:30:33 -07:00
|
|
|
|
2020-10-21 08:36:53 -06:00
|
|
|
# Maximum number of events to provide in an AS transaction.
|
|
|
|
MAX_PERSISTENT_EVENTS_PER_TRANSACTION = 100
|
|
|
|
|
|
|
|
# Maximum number of ephemeral events to provide in an AS transaction.
|
|
|
|
MAX_EPHEMERAL_EVENTS_PER_TRANSACTION = 100
|
|
|
|
|
2022-02-01 07:13:38 -07:00
|
|
|
# Maximum number of to-device messages to provide in an AS transaction.
|
|
|
|
MAX_TO_DEVICE_MESSAGES_PER_TRANSACTION = 100
|
|
|
|
|
2020-10-21 08:36:53 -06:00
|
|
|
|
2020-09-04 04:54:56 -06:00
|
|
|
class ApplicationServiceScheduler:
|
2015-03-05 10:35:07 -07:00
|
|
|
"""Public facing API for this module. Does the required DI to tie the
|
|
|
|
components together. This also serves as the "event_pool", which in this
|
|
|
|
case is a simple array.
|
|
|
|
"""
|
|
|
|
|
2021-12-14 10:02:46 -07:00
|
|
|
def __init__(self, hs: "HomeServer"):
|
2016-05-31 06:53:48 -06:00
|
|
|
self.clock = hs.get_clock()
|
2022-02-23 04:04:02 -07:00
|
|
|
self.store = hs.get_datastores().main
|
2016-05-31 06:53:48 -06:00
|
|
|
self.as_api = hs.get_application_service_api()
|
2015-03-05 10:35:07 -07:00
|
|
|
|
2019-08-20 04:20:10 -06:00
|
|
|
self.txn_ctrl = _TransactionController(self.clock, self.store, self.as_api)
|
2022-02-24 10:55:45 -07:00
|
|
|
self.queuer = _ServiceQueuer(self.txn_ctrl, self.clock, hs)
|
2015-03-05 10:35:07 -07:00
|
|
|
|
2021-12-14 10:02:46 -07:00
|
|
|
async def start(self) -> None:
|
2015-03-10 04:04:20 -06:00
|
|
|
logger.info("Starting appservice scheduler")
|
2019-08-20 04:20:10 -06:00
|
|
|
|
2015-03-06 03:25:50 -07:00
|
|
|
# check for any DOWN ASes and start recoverers for them.
|
2020-07-30 05:27:39 -06:00
|
|
|
services = await self.store.get_appservices_by_state(
|
2019-08-20 04:20:10 -06:00
|
|
|
ApplicationServiceState.DOWN
|
2015-03-06 03:25:50 -07:00
|
|
|
)
|
2019-08-20 04:20:10 -06:00
|
|
|
|
|
|
|
for service in services:
|
|
|
|
self.txn_ctrl.start_recoverer(service)
|
2015-03-05 10:35:07 -07:00
|
|
|
|
2022-02-01 07:13:38 -07:00
|
|
|
def enqueue_for_appservice(
|
|
|
|
self,
|
|
|
|
appservice: ApplicationService,
|
|
|
|
events: Optional[Collection[EventBase]] = None,
|
|
|
|
ephemeral: Optional[Collection[JsonDict]] = None,
|
|
|
|
to_device_messages: Optional[Collection[JsonDict]] = None,
|
2022-03-30 07:39:27 -06:00
|
|
|
device_list_summary: Optional[DeviceListUpdates] = None,
|
2021-12-14 10:02:46 -07:00
|
|
|
) -> None:
|
2022-02-01 07:13:38 -07:00
|
|
|
"""
|
|
|
|
Enqueue some data to be sent off to an application service.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
appservice: The application service to create and send a transaction to.
|
|
|
|
events: The persistent room events to send.
|
|
|
|
ephemeral: The ephemeral events to send.
|
|
|
|
to_device_messages: The to-device messages to send. These differ from normal
|
|
|
|
to-device messages sent to clients, as they have 'to_device_id' and
|
|
|
|
'to_user_id' fields.
|
2022-03-30 07:39:27 -06:00
|
|
|
device_list_summary: A summary of users that the application service either needs
|
|
|
|
to refresh the device lists of, or those that the application service need no
|
|
|
|
longer track the device lists of.
|
2022-02-01 07:13:38 -07:00
|
|
|
"""
|
|
|
|
# We purposefully allow this method to run with empty events/ephemeral
|
|
|
|
# collections, so that callers do not need to check iterable size themselves.
|
2022-03-30 07:39:27 -06:00
|
|
|
if (
|
|
|
|
not events
|
|
|
|
and not ephemeral
|
|
|
|
and not to_device_messages
|
|
|
|
and not device_list_summary
|
|
|
|
):
|
2022-02-01 07:13:38 -07:00
|
|
|
return
|
2020-10-15 10:33:28 -06:00
|
|
|
|
2022-02-01 07:13:38 -07:00
|
|
|
if events:
|
|
|
|
self.queuer.queued_events.setdefault(appservice.id, []).extend(events)
|
|
|
|
if ephemeral:
|
|
|
|
self.queuer.queued_ephemeral.setdefault(appservice.id, []).extend(ephemeral)
|
|
|
|
if to_device_messages:
|
|
|
|
self.queuer.queued_to_device_messages.setdefault(appservice.id, []).extend(
|
|
|
|
to_device_messages
|
|
|
|
)
|
2022-03-30 07:39:27 -06:00
|
|
|
if device_list_summary:
|
|
|
|
self.queuer.queued_device_list_summaries.setdefault(
|
|
|
|
appservice.id, []
|
|
|
|
).append(device_list_summary)
|
2022-02-01 07:13:38 -07:00
|
|
|
|
|
|
|
# Kick off a new application service transaction
|
|
|
|
self.queuer.start_background_request(appservice)
|
2015-03-05 10:35:07 -07:00
|
|
|
|
|
|
|
|
2020-09-04 04:54:56 -06:00
|
|
|
class _ServiceQueuer:
|
2019-08-20 04:20:10 -06:00
|
|
|
"""Queue of events waiting to be sent to appservices.
|
|
|
|
|
|
|
|
Groups events into transactions per-appservice, and sends them on to the
|
|
|
|
TransactionController. Makes sure that we only have one transaction in flight per
|
|
|
|
appservice at a given time.
|
2015-03-06 03:25:50 -07:00
|
|
|
"""
|
2015-03-05 10:35:07 -07:00
|
|
|
|
2022-02-24 10:55:45 -07:00
|
|
|
def __init__(
|
|
|
|
self, txn_ctrl: "_TransactionController", clock: Clock, hs: "HomeServer"
|
|
|
|
):
|
2021-12-14 10:02:46 -07:00
|
|
|
# dict of {service_id: [events]}
|
|
|
|
self.queued_events: Dict[str, List[EventBase]] = {}
|
|
|
|
# dict of {service_id: [events]}
|
|
|
|
self.queued_ephemeral: Dict[str, List[JsonDict]] = {}
|
2022-02-01 07:13:38 -07:00
|
|
|
# dict of {service_id: [to_device_message_json]}
|
|
|
|
self.queued_to_device_messages: Dict[str, List[JsonDict]] = {}
|
2022-03-30 07:39:27 -06:00
|
|
|
# dict of {service_id: [device_list_summary]}
|
|
|
|
self.queued_device_list_summaries: Dict[str, List[DeviceListUpdates]] = {}
|
2019-08-20 04:20:10 -06:00
|
|
|
|
|
|
|
# the appservices which currently have a transaction in flight
|
2021-12-14 10:02:46 -07:00
|
|
|
self.requests_in_flight: Set[str] = set()
|
2015-03-16 07:15:40 -06:00
|
|
|
self.txn_ctrl = txn_ctrl
|
2016-08-17 05:03:04 -06:00
|
|
|
self.clock = clock
|
2022-02-24 10:55:45 -07:00
|
|
|
self._msc3202_transaction_extensions_enabled: bool = (
|
|
|
|
hs.config.experimental.msc3202_transaction_extensions
|
|
|
|
)
|
|
|
|
self._store = hs.get_datastores().main
|
2015-03-05 10:35:07 -07:00
|
|
|
|
2022-02-01 07:13:38 -07:00
|
|
|
def start_background_request(self, service: ApplicationService) -> None:
|
2018-12-04 02:53:49 -07:00
|
|
|
# start a sender for this appservice if we don't already have one
|
2016-08-17 05:03:04 -06:00
|
|
|
if service.id in self.requests_in_flight:
|
|
|
|
return
|
|
|
|
|
2018-12-04 02:53:49 -07:00
|
|
|
run_as_background_process(
|
|
|
|
"as-sender-%s" % (service.id,), self._send_request, service
|
|
|
|
)
|
|
|
|
|
2021-12-14 10:02:46 -07:00
|
|
|
async def _send_request(self, service: ApplicationService) -> None:
|
2018-12-04 02:53:49 -07:00
|
|
|
# sanity-check: we shouldn't get here if this service already has a sender
|
|
|
|
# running.
|
|
|
|
assert service.id not in self.requests_in_flight
|
|
|
|
|
2016-08-17 07:52:26 -06:00
|
|
|
self.requests_in_flight.add(service.id)
|
|
|
|
try:
|
|
|
|
while True:
|
2020-10-21 08:36:53 -06:00
|
|
|
all_events = self.queued_events.get(service.id, [])
|
|
|
|
events = all_events[:MAX_PERSISTENT_EVENTS_PER_TRANSACTION]
|
|
|
|
del all_events[:MAX_PERSISTENT_EVENTS_PER_TRANSACTION]
|
|
|
|
|
|
|
|
all_events_ephemeral = self.queued_ephemeral.get(service.id, [])
|
|
|
|
ephemeral = all_events_ephemeral[:MAX_EPHEMERAL_EVENTS_PER_TRANSACTION]
|
|
|
|
del all_events_ephemeral[:MAX_EPHEMERAL_EVENTS_PER_TRANSACTION]
|
|
|
|
|
2022-02-01 07:13:38 -07:00
|
|
|
all_to_device_messages = self.queued_to_device_messages.get(
|
|
|
|
service.id, []
|
|
|
|
)
|
|
|
|
to_device_messages_to_send = all_to_device_messages[
|
|
|
|
:MAX_TO_DEVICE_MESSAGES_PER_TRANSACTION
|
|
|
|
]
|
|
|
|
del all_to_device_messages[:MAX_TO_DEVICE_MESSAGES_PER_TRANSACTION]
|
|
|
|
|
2022-03-30 07:39:27 -06:00
|
|
|
# Consolidate any pending device list summaries into a single, up-to-date
|
|
|
|
# summary.
|
|
|
|
# Note: this code assumes that in a single DeviceListUpdates, a user will
|
|
|
|
# never be in both "changed" and "left" sets.
|
|
|
|
device_list_summary = DeviceListUpdates()
|
|
|
|
for summary in self.queued_device_list_summaries.get(service.id, []):
|
|
|
|
# For every user in the incoming "changed" set:
|
|
|
|
# * Remove them from the existing "left" set if necessary
|
|
|
|
# (as we need to start tracking them again)
|
|
|
|
# * Add them to the existing "changed" set if necessary.
|
|
|
|
device_list_summary.left.difference_update(summary.changed)
|
|
|
|
device_list_summary.changed.update(summary.changed)
|
|
|
|
|
|
|
|
# For every user in the incoming "left" set:
|
|
|
|
# * Remove them from the existing "changed" set if necessary
|
|
|
|
# (we no longer need to track them)
|
|
|
|
# * Add them to the existing "left" set if necessary.
|
|
|
|
device_list_summary.changed.difference_update(summary.left)
|
|
|
|
device_list_summary.left.update(summary.left)
|
|
|
|
self.queued_device_list_summaries.clear()
|
|
|
|
|
|
|
|
if (
|
|
|
|
not events
|
|
|
|
and not ephemeral
|
|
|
|
and not to_device_messages_to_send
|
|
|
|
# DeviceListUpdates is True if either the 'changed' or 'left' sets have
|
|
|
|
# at least one entry, otherwise False
|
|
|
|
and not device_list_summary
|
|
|
|
):
|
2016-08-17 07:52:26 -06:00
|
|
|
return
|
2020-10-21 08:36:53 -06:00
|
|
|
|
2022-11-28 09:17:29 -07:00
|
|
|
one_time_keys_count: Optional[TransactionOneTimeKeysCount] = None
|
2022-02-24 10:55:45 -07:00
|
|
|
unused_fallback_keys: Optional[TransactionUnusedFallbackKeys] = None
|
|
|
|
|
|
|
|
if (
|
|
|
|
self._msc3202_transaction_extensions_enabled
|
|
|
|
and service.msc3202_transaction_extensions
|
|
|
|
):
|
|
|
|
# Compute the one-time key counts and fallback key usage states
|
|
|
|
# for the users which are mentioned in this transaction,
|
|
|
|
# as well as the appservice's sender.
|
|
|
|
(
|
2022-11-28 09:17:29 -07:00
|
|
|
one_time_keys_count,
|
2022-02-24 10:55:45 -07:00
|
|
|
unused_fallback_keys,
|
|
|
|
) = await self._compute_msc3202_otk_counts_and_fallback_keys(
|
|
|
|
service, events, ephemeral, to_device_messages_to_send
|
|
|
|
)
|
|
|
|
|
2018-12-04 02:53:49 -07:00
|
|
|
try:
|
2022-02-01 07:13:38 -07:00
|
|
|
await self.txn_ctrl.send(
|
2022-02-24 10:55:45 -07:00
|
|
|
service,
|
|
|
|
events,
|
|
|
|
ephemeral,
|
|
|
|
to_device_messages_to_send,
|
2022-11-28 09:17:29 -07:00
|
|
|
one_time_keys_count,
|
2022-02-24 10:55:45 -07:00
|
|
|
unused_fallback_keys,
|
2022-03-30 07:39:27 -06:00
|
|
|
device_list_summary,
|
2022-02-01 07:13:38 -07:00
|
|
|
)
|
2018-12-04 02:53:49 -07:00
|
|
|
except Exception:
|
|
|
|
logger.exception("AS request failed")
|
2016-08-17 07:52:26 -06:00
|
|
|
finally:
|
|
|
|
self.requests_in_flight.discard(service.id)
|
2015-03-06 03:25:50 -07:00
|
|
|
|
2022-02-24 10:55:45 -07:00
|
|
|
async def _compute_msc3202_otk_counts_and_fallback_keys(
|
|
|
|
self,
|
|
|
|
service: ApplicationService,
|
|
|
|
events: Iterable[EventBase],
|
|
|
|
ephemerals: Iterable[JsonDict],
|
|
|
|
to_device_messages: Iterable[JsonDict],
|
2022-11-28 09:17:29 -07:00
|
|
|
) -> Tuple[TransactionOneTimeKeysCount, TransactionUnusedFallbackKeys]:
|
2022-02-24 10:55:45 -07:00
|
|
|
"""
|
|
|
|
Given a list of the events, ephemeral messages and to-device messages,
|
|
|
|
- first computes a list of application services users that may have
|
|
|
|
interesting updates to the one-time key counts or fallback key usage.
|
|
|
|
- then computes one-time key counts and fallback key usages for those users.
|
|
|
|
Given a list of application service users that are interesting,
|
|
|
|
compute one-time key counts and fallback key usages for the users.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Set of 'interesting' users who may have updates
|
|
|
|
users: Set[str] = set()
|
|
|
|
|
|
|
|
# The sender is always included
|
|
|
|
users.add(service.sender)
|
|
|
|
|
|
|
|
# All AS users that would receive the PDUs or EDUs sent to these rooms
|
|
|
|
# are classed as 'interesting'.
|
|
|
|
rooms_of_interesting_users: Set[str] = set()
|
|
|
|
# PDUs
|
|
|
|
rooms_of_interesting_users.update(event.room_id for event in events)
|
|
|
|
# EDUs
|
|
|
|
rooms_of_interesting_users.update(
|
2022-07-11 07:12:28 -06:00
|
|
|
ephemeral["room_id"]
|
|
|
|
for ephemeral in ephemerals
|
|
|
|
if ephemeral.get("room_id") is not None
|
2022-02-24 10:55:45 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
# Look up the AS users in those rooms
|
|
|
|
for room_id in rooms_of_interesting_users:
|
|
|
|
users.update(
|
|
|
|
await self._store.get_app_service_users_in_room(room_id, service)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Add recipients of to-device messages.
|
2022-07-11 10:22:17 -06:00
|
|
|
users.update(
|
|
|
|
device_message["to_user_id"] for device_message in to_device_messages
|
|
|
|
)
|
2022-02-24 10:55:45 -07:00
|
|
|
|
|
|
|
# Compute and return the counts / fallback key usage states
|
|
|
|
otk_counts = await self._store.count_bulk_e2e_one_time_keys_for_as(users)
|
|
|
|
unused_fbks = await self._store.get_e2e_bulk_unused_fallback_key_types(users)
|
|
|
|
return otk_counts, unused_fbks
|
|
|
|
|
2015-03-05 10:35:07 -07:00
|
|
|
|
2020-09-04 04:54:56 -06:00
|
|
|
class _TransactionController:
|
2019-08-20 04:20:10 -06:00
|
|
|
"""Transaction manager.
|
|
|
|
|
|
|
|
Builds AppServiceTransactions and runs their lifecycle. Also starts a Recoverer
|
|
|
|
if a transaction fails.
|
|
|
|
|
|
|
|
(Note we have only have one of these in the homeserver.)
|
|
|
|
"""
|
|
|
|
|
2021-12-14 10:02:46 -07:00
|
|
|
def __init__(self, clock: Clock, store: DataStore, as_api: ApplicationServiceApi):
|
2015-03-06 03:25:50 -07:00
|
|
|
self.clock = clock
|
2015-03-05 10:35:07 -07:00
|
|
|
self.store = store
|
|
|
|
self.as_api = as_api
|
2019-08-20 04:20:10 -06:00
|
|
|
|
|
|
|
# map from service id to recoverer instance
|
2021-12-14 10:02:46 -07:00
|
|
|
self.recoverers: Dict[str, "_Recoverer"] = {}
|
2019-08-20 04:20:10 -06:00
|
|
|
|
|
|
|
# for UTs
|
|
|
|
self.RECOVERER_CLASS = _Recoverer
|
2015-03-05 10:35:07 -07:00
|
|
|
|
2020-10-15 10:33:28 -06:00
|
|
|
async def send(
|
|
|
|
self,
|
|
|
|
service: ApplicationService,
|
|
|
|
events: List[EventBase],
|
2021-04-08 15:38:54 -06:00
|
|
|
ephemeral: Optional[List[JsonDict]] = None,
|
2022-02-01 07:13:38 -07:00
|
|
|
to_device_messages: Optional[List[JsonDict]] = None,
|
2022-11-28 09:17:29 -07:00
|
|
|
one_time_keys_count: Optional[TransactionOneTimeKeysCount] = None,
|
2022-02-24 10:55:45 -07:00
|
|
|
unused_fallback_keys: Optional[TransactionUnusedFallbackKeys] = None,
|
2022-03-30 07:39:27 -06:00
|
|
|
device_list_summary: Optional[DeviceListUpdates] = None,
|
2021-12-14 10:02:46 -07:00
|
|
|
) -> None:
|
2022-02-01 07:13:38 -07:00
|
|
|
"""
|
|
|
|
Create a transaction with the given data and send to the provided
|
|
|
|
application service.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
service: The application service to send the transaction to.
|
|
|
|
events: The persistent events to include in the transaction.
|
|
|
|
ephemeral: The ephemeral events to include in the transaction.
|
|
|
|
to_device_messages: The to-device messages to include in the transaction.
|
2022-11-28 09:17:29 -07:00
|
|
|
one_time_keys_count: Counts of remaining one-time keys for relevant
|
2022-02-24 10:55:45 -07:00
|
|
|
appservice devices in the transaction.
|
|
|
|
unused_fallback_keys: Lists of unused fallback keys for relevant
|
|
|
|
appservice devices in the transaction.
|
2022-03-30 07:39:27 -06:00
|
|
|
device_list_summary: The device list summary to include in the transaction.
|
2022-02-01 07:13:38 -07:00
|
|
|
"""
|
2015-03-16 04:38:02 -06:00
|
|
|
try:
|
2022-05-25 03:46:05 -06:00
|
|
|
service_is_up = await self._is_service_up(service)
|
|
|
|
# Don't create empty txns when in recovery mode (ephemeral events are dropped)
|
|
|
|
if not service_is_up and not events:
|
|
|
|
return
|
|
|
|
|
2020-10-15 10:33:28 -06:00
|
|
|
txn = await self.store.create_appservice_txn(
|
2022-02-01 07:13:38 -07:00
|
|
|
service=service,
|
|
|
|
events=events,
|
|
|
|
ephemeral=ephemeral or [],
|
|
|
|
to_device_messages=to_device_messages or [],
|
2022-11-28 09:17:29 -07:00
|
|
|
one_time_keys_count=one_time_keys_count or {},
|
2022-02-24 10:55:45 -07:00
|
|
|
unused_fallback_keys=unused_fallback_keys or {},
|
2022-03-30 07:39:27 -06:00
|
|
|
device_list_summary=device_list_summary or DeviceListUpdates(),
|
2020-10-15 10:33:28 -06:00
|
|
|
)
|
2015-03-16 07:15:40 -06:00
|
|
|
if service_is_up:
|
2020-07-30 05:27:39 -06:00
|
|
|
sent = await txn.send(self.as_api)
|
2015-03-16 07:15:40 -06:00
|
|
|
if sent:
|
2020-07-30 05:27:39 -06:00
|
|
|
await txn.complete(self.store)
|
2015-03-16 07:15:40 -06:00
|
|
|
else:
|
2019-08-20 04:20:10 -06:00
|
|
|
run_in_background(self._on_txn_fail, service)
|
2018-04-27 04:29:27 -06:00
|
|
|
except Exception:
|
|
|
|
logger.exception("Error creating appservice transaction")
|
2019-08-20 04:20:10 -06:00
|
|
|
run_in_background(self._on_txn_fail, service)
|
2015-03-06 03:25:50 -07:00
|
|
|
|
2021-12-14 10:02:46 -07:00
|
|
|
async def on_recovered(self, recoverer: "_Recoverer") -> None:
|
2015-03-10 04:04:20 -06:00
|
|
|
logger.info(
|
|
|
|
"Successfully recovered application service AS ID %s", recoverer.service.id
|
|
|
|
)
|
2019-08-20 04:20:10 -06:00
|
|
|
self.recoverers.pop(recoverer.service.id)
|
2015-03-10 04:04:20 -06:00
|
|
|
logger.info("Remaining active recoverers: %s", len(self.recoverers))
|
2020-07-30 05:27:39 -06:00
|
|
|
await self.store.set_appservice_state(
|
2015-03-06 08:12:24 -07:00
|
|
|
recoverer.service, ApplicationServiceState.UP
|
|
|
|
)
|
2015-03-05 10:35:07 -07:00
|
|
|
|
2021-12-14 10:02:46 -07:00
|
|
|
async def _on_txn_fail(self, service: ApplicationService) -> None:
|
2018-04-27 04:07:40 -06:00
|
|
|
try:
|
2020-07-30 05:27:39 -06:00
|
|
|
await self.store.set_appservice_state(service, ApplicationServiceState.DOWN)
|
2019-08-20 04:20:10 -06:00
|
|
|
self.start_recoverer(service)
|
2018-04-27 04:07:40 -06:00
|
|
|
except Exception:
|
|
|
|
logger.exception("Error starting AS recoverer")
|
2015-03-05 10:35:07 -07:00
|
|
|
|
2021-12-14 10:02:46 -07:00
|
|
|
def start_recoverer(self, service: ApplicationService) -> None:
|
2019-08-20 04:20:10 -06:00
|
|
|
"""Start a Recoverer for the given service
|
|
|
|
|
|
|
|
Args:
|
2021-12-14 10:02:46 -07:00
|
|
|
service:
|
2019-08-20 04:20:10 -06:00
|
|
|
"""
|
|
|
|
logger.info("Starting recoverer for AS ID %s", service.id)
|
|
|
|
assert service.id not in self.recoverers
|
|
|
|
recoverer = self.RECOVERER_CLASS(
|
|
|
|
self.clock, self.store, self.as_api, service, self.on_recovered
|
|
|
|
)
|
|
|
|
self.recoverers[service.id] = recoverer
|
|
|
|
recoverer.recover()
|
|
|
|
logger.info("Now %i active recoverers", len(self.recoverers))
|
|
|
|
|
2020-10-15 10:33:28 -06:00
|
|
|
async def _is_service_up(self, service: ApplicationService) -> bool:
|
2020-07-30 05:27:39 -06:00
|
|
|
state = await self.store.get_appservice_state(service)
|
2019-07-23 07:00:55 -06:00
|
|
|
return state == ApplicationServiceState.UP or state is None
|
2015-03-05 10:35:07 -07:00
|
|
|
|
|
|
|
|
2020-09-04 04:54:56 -06:00
|
|
|
class _Recoverer:
|
2019-08-20 04:20:10 -06:00
|
|
|
"""Manages retries and backoff for a DOWN appservice.
|
|
|
|
|
|
|
|
We have one of these for each appservice which is currently considered DOWN.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
clock (synapse.util.Clock):
|
|
|
|
store (synapse.storage.DataStore):
|
|
|
|
as_api (synapse.appservice.api.ApplicationServiceApi):
|
|
|
|
service (synapse.appservice.ApplicationService): the service we are managing
|
|
|
|
callback (callable[_Recoverer]): called once the service recovers.
|
|
|
|
"""
|
2015-03-06 03:25:50 -07:00
|
|
|
|
2021-12-14 10:02:46 -07:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
clock: Clock,
|
|
|
|
store: DataStore,
|
|
|
|
as_api: ApplicationServiceApi,
|
|
|
|
service: ApplicationService,
|
|
|
|
callback: Callable[["_Recoverer"], Awaitable[None]],
|
|
|
|
):
|
2015-03-06 03:25:50 -07:00
|
|
|
self.clock = clock
|
2015-03-05 10:35:07 -07:00
|
|
|
self.store = store
|
|
|
|
self.as_api = as_api
|
|
|
|
self.service = service
|
2015-03-06 03:25:50 -07:00
|
|
|
self.callback = callback
|
2015-03-05 10:35:07 -07:00
|
|
|
self.backoff_counter = 1
|
2015-03-05 09:30:33 -07:00
|
|
|
|
2021-12-14 10:02:46 -07:00
|
|
|
def recover(self) -> None:
|
|
|
|
def _retry() -> None:
|
2018-12-04 02:53:49 -07:00
|
|
|
run_as_background_process(
|
|
|
|
"as-recoverer-%s" % (self.service.id,), self.retry
|
|
|
|
)
|
2019-06-20 03:32:02 -06:00
|
|
|
|
2022-03-29 04:41:19 -06:00
|
|
|
delay = 2**self.backoff_counter
|
2019-08-20 10:39:38 -06:00
|
|
|
logger.info("Scheduling retries on %s in %fs", self.service.id, delay)
|
|
|
|
self.clock.call_later(delay, _retry)
|
2015-03-06 03:25:50 -07:00
|
|
|
|
2021-12-14 10:02:46 -07:00
|
|
|
def _backoff(self) -> None:
|
2015-10-21 03:10:55 -06:00
|
|
|
# cap the backoff to be around 8.5min => (2^9) = 512 secs
|
|
|
|
if self.backoff_counter < 9:
|
2015-03-16 04:38:02 -06:00
|
|
|
self.backoff_counter += 1
|
|
|
|
self.recover()
|
|
|
|
|
2021-12-14 10:02:46 -07:00
|
|
|
async def retry(self) -> None:
|
2019-08-20 10:39:38 -06:00
|
|
|
logger.info("Starting retries on %s", self.service.id)
|
2015-03-16 04:38:02 -06:00
|
|
|
try:
|
2019-08-20 10:39:38 -06:00
|
|
|
while True:
|
2020-07-30 05:27:39 -06:00
|
|
|
txn = await self.store.get_oldest_unsent_txn(self.service)
|
2019-08-20 10:39:38 -06:00
|
|
|
if not txn:
|
|
|
|
# nothing left: we're done!
|
2020-07-30 05:27:39 -06:00
|
|
|
await self.callback(self)
|
2019-08-20 10:39:38 -06:00
|
|
|
return
|
|
|
|
|
2015-03-16 04:38:02 -06:00
|
|
|
logger.info(
|
|
|
|
"Retrying transaction %s for AS ID %s", txn.id, txn.service.id
|
|
|
|
)
|
2020-07-30 05:27:39 -06:00
|
|
|
sent = await txn.send(self.as_api)
|
2019-08-20 10:39:38 -06:00
|
|
|
if not sent:
|
|
|
|
break
|
|
|
|
|
2020-07-30 05:27:39 -06:00
|
|
|
await txn.complete(self.store)
|
2019-08-20 10:39:38 -06:00
|
|
|
|
|
|
|
# reset the backoff counter and then process the next transaction
|
|
|
|
self.backoff_counter = 1
|
|
|
|
|
|
|
|
except Exception:
|
|
|
|
logger.exception("Unexpected error running retries")
|
|
|
|
|
|
|
|
# we didn't manage to send all of the transactions before we got an error of
|
|
|
|
# some flavour: reschedule the next retry.
|
|
|
|
self._backoff()
|