2017-03-27 11:10:55 -04:00
|
|
|
# Copyright 2017 Vector Creations 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.
|
|
|
|
"""A replication client for use by synapse workers.
|
|
|
|
"""
|
2018-07-09 02:09:20 -04:00
|
|
|
import logging
|
2023-08-22 11:11:22 -04:00
|
|
|
from typing import TYPE_CHECKING, Dict, Iterable, Optional, Set, Tuple
|
|
|
|
|
|
|
|
from sortedcontainers import SortedList
|
2018-07-09 02:09:20 -04:00
|
|
|
|
2023-01-18 14:35:29 -05:00
|
|
|
from twisted.internet import defer
|
2020-05-22 09:21:54 -04:00
|
|
|
from twisted.internet.defer import Deferred
|
2017-03-27 11:10:55 -04:00
|
|
|
|
2022-07-19 07:45:17 -04:00
|
|
|
from synapse.api.constants import EventTypes, Membership, ReceiptTypes
|
2021-04-14 12:06:06 -04:00
|
|
|
from synapse.federation import send_queue
|
|
|
|
from synapse.federation.sender import FederationSender
|
2020-05-22 09:21:54 -04:00
|
|
|
from synapse.logging.context import PreserveLoggingContext, make_deferred_yieldable
|
2021-04-14 12:06:06 -04:00
|
|
|
from synapse.metrics.background_process_metrics import run_as_background_process
|
|
|
|
from synapse.replication.tcp.streams import (
|
|
|
|
AccountDataStream,
|
|
|
|
DeviceListsStream,
|
|
|
|
PushersStream,
|
|
|
|
PushRulesStream,
|
|
|
|
ReceiptsStream,
|
|
|
|
ToDeviceStream,
|
|
|
|
TypingStream,
|
2022-12-19 09:57:51 -05:00
|
|
|
UnPartialStatedEventStream,
|
2022-12-06 10:48:42 -05:00
|
|
|
UnPartialStatedRoomStream,
|
2021-04-14 12:06:06 -04:00
|
|
|
)
|
2020-05-14 09:01:39 -04:00
|
|
|
from synapse.replication.tcp.streams.events import (
|
|
|
|
EventsStream,
|
|
|
|
EventsStreamEventRow,
|
|
|
|
EventsStreamRow,
|
|
|
|
)
|
2022-12-19 09:57:51 -05:00
|
|
|
from synapse.replication.tcp.streams.partial_state import (
|
|
|
|
UnPartialStatedEventStreamRow,
|
|
|
|
UnPartialStatedRoomStreamRow,
|
|
|
|
)
|
2022-05-16 11:35:31 -04:00
|
|
|
from synapse.types import PersistedEventPosition, ReadReceipt, StreamKeyType, UserID
|
2021-04-14 12:06:06 -04:00
|
|
|
from synapse.util.async_helpers import Linearizer, timeout_deferred
|
2020-05-22 09:21:54 -04:00
|
|
|
from synapse.util.metrics import Measure
|
2020-04-06 04:58:42 -04:00
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
2020-07-05 11:32:02 -04:00
|
|
|
from synapse.server import HomeServer
|
2017-03-27 11:10:55 -04:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2020-05-22 09:21:54 -04:00
|
|
|
# How long we allow callers to wait for replication updates before timing out.
|
2023-01-20 16:04:33 -05:00
|
|
|
_WAIT_FOR_REPLICATION_TIMEOUT_SECONDS = 5
|
2020-05-22 09:21:54 -04:00
|
|
|
|
|
|
|
|
2020-04-06 04:58:42 -04:00
|
|
|
class ReplicationDataHandler:
|
|
|
|
"""Handles incoming stream updates from replication.
|
2017-03-27 11:10:55 -04:00
|
|
|
|
2023-05-16 15:56:38 -04:00
|
|
|
This instance notifies the data store about updates. Can be subclassed
|
2020-04-06 04:58:42 -04:00
|
|
|
to handle updates in additional ways.
|
2017-03-27 11:10:55 -04:00
|
|
|
"""
|
2019-06-20 05:32:02 -04:00
|
|
|
|
2020-05-14 09:01:39 -04:00
|
|
|
def __init__(self, hs: "HomeServer"):
|
2022-02-23 06:04:02 -05:00
|
|
|
self.store = hs.get_datastores().main
|
2020-05-14 09:01:39 -04:00
|
|
|
self.notifier = hs.get_notifier()
|
2020-05-22 09:21:54 -04:00
|
|
|
self._reactor = hs.get_reactor()
|
|
|
|
self._clock = hs.get_clock()
|
|
|
|
self._streams = hs.get_replication_streams()
|
|
|
|
self._instance_name = hs.get_instance_name()
|
2020-07-27 09:10:53 -04:00
|
|
|
self._typing_handler = hs.get_typing_handler()
|
2022-12-06 10:48:42 -05:00
|
|
|
self._state_storage_controller = hs.get_storage_controllers().state
|
2020-05-22 09:21:54 -04:00
|
|
|
|
2021-10-06 10:47:41 -04:00
|
|
|
self._notify_pushers = hs.config.worker.start_pushers
|
2021-04-14 12:06:06 -04:00
|
|
|
self._pusher_pool = hs.get_pusherpool()
|
|
|
|
self._presence_handler = hs.get_presence_handler()
|
|
|
|
|
2021-07-15 06:02:43 -04:00
|
|
|
self.send_handler: Optional[FederationSenderHandler] = None
|
2021-04-14 12:06:06 -04:00
|
|
|
if hs.should_send_federation():
|
|
|
|
self.send_handler = FederationSenderHandler(hs)
|
|
|
|
|
2023-01-19 17:19:56 -05:00
|
|
|
# Map from stream and instance to list of deferreds waiting for the stream to
|
2020-05-22 09:21:54 -04:00
|
|
|
# arrive at a particular position. The lists are sorted by stream position.
|
2023-08-22 11:11:22 -04:00
|
|
|
self._streams_to_waiters: Dict[
|
|
|
|
Tuple[str, str], SortedList[Tuple[int, Deferred]]
|
|
|
|
] = {}
|
2017-03-27 11:10:55 -04:00
|
|
|
|
2020-05-01 12:19:56 -04:00
|
|
|
async def on_rdata(
|
|
|
|
self, stream_name: str, instance_name: str, token: int, rows: list
|
2022-02-08 11:03:08 -05:00
|
|
|
) -> None:
|
2019-03-27 17:12:36 -04:00
|
|
|
"""Called to handle a batch of replication data with a given stream token.
|
2017-03-27 11:10:55 -04:00
|
|
|
|
2023-05-16 15:56:38 -04:00
|
|
|
By default, this just pokes the data store. Can be overridden in subclasses to
|
2019-03-27 17:12:36 -04:00
|
|
|
handle more.
|
|
|
|
|
|
|
|
Args:
|
2020-05-01 12:19:56 -04:00
|
|
|
stream_name: name of the replication stream for this batch of rows
|
|
|
|
instance_name: the instance that wrote the rows.
|
|
|
|
token: stream token for this batch of rows
|
|
|
|
rows: a list of Stream.ROW_TYPE objects as returned by Stream.parse_row.
|
2017-03-27 11:10:55 -04:00
|
|
|
"""
|
2022-07-18 09:28:14 -04:00
|
|
|
self.store.process_replication_rows(stream_name, instance_name, token, rows)
|
2023-01-04 06:49:26 -05:00
|
|
|
# NOTE: this must be called after process_replication_rows to ensure any
|
|
|
|
# cache invalidations are first handled before any stream ID advances.
|
|
|
|
self.store.process_replication_position(stream_name, instance_name, token)
|
2017-03-27 11:10:55 -04:00
|
|
|
|
2021-04-14 12:06:06 -04:00
|
|
|
if self.send_handler:
|
|
|
|
await self.send_handler.process_replication_rows(stream_name, token, rows)
|
|
|
|
|
2020-07-27 09:10:53 -04:00
|
|
|
if stream_name == TypingStream.NAME:
|
2022-07-18 09:28:14 -04:00
|
|
|
self._typing_handler.process_replication_rows(token, rows)
|
2020-07-27 09:10:53 -04:00
|
|
|
self.notifier.on_new_event(
|
2022-05-16 11:35:31 -04:00
|
|
|
StreamKeyType.TYPING, token, rooms=[row.room_id for row in rows]
|
2020-07-27 09:10:53 -04:00
|
|
|
)
|
2021-04-14 12:06:06 -04:00
|
|
|
elif stream_name == PushRulesStream.NAME:
|
|
|
|
self.notifier.on_new_event(
|
2022-05-16 11:35:31 -04:00
|
|
|
StreamKeyType.PUSH_RULES, token, users=[row.user_id for row in rows]
|
2021-04-14 12:06:06 -04:00
|
|
|
)
|
2023-01-13 09:57:43 -05:00
|
|
|
elif stream_name in AccountDataStream.NAME:
|
2021-04-14 12:06:06 -04:00
|
|
|
self.notifier.on_new_event(
|
2022-05-16 11:35:31 -04:00
|
|
|
StreamKeyType.ACCOUNT_DATA, token, users=[row.user_id for row in rows]
|
2021-04-14 12:06:06 -04:00
|
|
|
)
|
|
|
|
elif stream_name == ReceiptsStream.NAME:
|
|
|
|
self.notifier.on_new_event(
|
2022-05-16 11:35:31 -04:00
|
|
|
StreamKeyType.RECEIPT, token, rooms=[row.room_id for row in rows]
|
2021-04-14 12:06:06 -04:00
|
|
|
)
|
|
|
|
await self._pusher_pool.on_new_receipts(
|
|
|
|
token, token, {row.room_id for row in rows}
|
|
|
|
)
|
|
|
|
elif stream_name == ToDeviceStream.NAME:
|
|
|
|
entities = [row.entity for row in rows if row.entity.startswith("@")]
|
|
|
|
if entities:
|
2022-05-16 11:35:31 -04:00
|
|
|
self.notifier.on_new_event(
|
|
|
|
StreamKeyType.TO_DEVICE, token, users=entities
|
|
|
|
)
|
2021-04-14 12:06:06 -04:00
|
|
|
elif stream_name == DeviceListsStream.NAME:
|
2021-07-15 06:02:43 -04:00
|
|
|
all_room_ids: Set[str] = set()
|
2021-04-14 12:06:06 -04:00
|
|
|
for row in rows:
|
2023-01-17 04:29:58 -05:00
|
|
|
if row.entity.startswith("@") and not row.is_signature:
|
2021-04-14 12:06:06 -04:00
|
|
|
room_ids = await self.store.get_rooms_for_user(row.entity)
|
|
|
|
all_room_ids.update(room_ids)
|
2022-05-16 11:35:31 -04:00
|
|
|
self.notifier.on_new_event(
|
|
|
|
StreamKeyType.DEVICE_LIST, token, rooms=all_room_ids
|
|
|
|
)
|
2021-04-14 12:06:06 -04:00
|
|
|
elif stream_name == PushersStream.NAME:
|
|
|
|
for row in rows:
|
|
|
|
if row.deleted:
|
|
|
|
self.stop_pusher(row.user_id, row.app_id, row.pushkey)
|
|
|
|
else:
|
2022-09-21 10:39:01 -04:00
|
|
|
await self.process_pusher_change(
|
|
|
|
row.user_id, row.app_id, row.pushkey
|
|
|
|
)
|
2021-04-14 12:06:06 -04:00
|
|
|
elif stream_name == EventsStream.NAME:
|
2020-05-14 09:01:39 -04:00
|
|
|
# We shouldn't get multiple rows per token for events stream, so
|
|
|
|
# we don't need to optimise this for multiple rows.
|
|
|
|
for row in rows:
|
|
|
|
if row.type != EventsStreamEventRow.TypeId:
|
2023-01-23 05:31:36 -05:00
|
|
|
# The row's data is an `EventsStreamCurrentStateRow`.
|
|
|
|
# When we recompute the current state of a room based on forward
|
|
|
|
# extremities (see `update_current_state`), no new events are
|
|
|
|
# persisted, so we must poke the replication callbacks ourselves.
|
|
|
|
# This functionality is used when finishing up a partial state join.
|
|
|
|
self.notifier.notify_replication()
|
2020-05-14 09:01:39 -04:00
|
|
|
continue
|
|
|
|
assert isinstance(row, EventsStreamRow)
|
2020-10-28 08:11:45 -04:00
|
|
|
assert isinstance(row.data, EventsStreamEventRow)
|
2020-05-14 09:01:39 -04:00
|
|
|
|
2020-10-28 08:11:45 -04:00
|
|
|
if row.data.rejected:
|
2020-05-14 09:01:39 -04:00
|
|
|
continue
|
|
|
|
|
2021-07-15 06:02:43 -04:00
|
|
|
extra_users: Tuple[UserID, ...] = ()
|
2020-10-28 08:11:45 -04:00
|
|
|
if row.data.type == EventTypes.Member and row.data.state_key:
|
|
|
|
extra_users = (UserID.from_string(row.data.state_key),)
|
2020-09-24 08:24:17 -04:00
|
|
|
|
2020-09-29 16:48:33 -04:00
|
|
|
max_token = self.store.get_room_max_token()
|
2020-09-24 08:24:17 -04:00
|
|
|
event_pos = PersistedEventPosition(instance_name, token)
|
2022-10-05 13:12:48 -04:00
|
|
|
event_entry = self.notifier.create_pending_room_event_entry(
|
|
|
|
event_pos,
|
|
|
|
extra_users,
|
|
|
|
row.data.room_id,
|
|
|
|
row.data.type,
|
|
|
|
row.data.state_key,
|
|
|
|
row.data.membership,
|
|
|
|
)
|
|
|
|
await self.notifier.notify_new_room_events(
|
|
|
|
[(event_entry, row.data.event_id)], max_token
|
2020-09-24 08:24:17 -04:00
|
|
|
)
|
2020-05-14 09:01:39 -04:00
|
|
|
|
2022-07-19 07:45:17 -04:00
|
|
|
# If this event is a join, make a note of it so we have an accurate
|
|
|
|
# cross-worker room rate limit.
|
|
|
|
# TODO: Erik said we should exclude rows that came from ex_outliers
|
|
|
|
# here, but I don't see how we can determine that. I guess we could
|
|
|
|
# add a flag to row.data?
|
|
|
|
if (
|
|
|
|
row.data.type == EventTypes.Member
|
|
|
|
and row.data.membership == Membership.JOIN
|
|
|
|
and not row.data.outlier
|
|
|
|
):
|
|
|
|
# TODO retrieve the previous state, and exclude join -> join transitions
|
|
|
|
self.notifier.notify_user_joined_room(
|
|
|
|
row.data.event_id, row.data.room_id
|
|
|
|
)
|
2022-12-06 10:48:42 -05:00
|
|
|
elif stream_name == UnPartialStatedRoomStream.NAME:
|
|
|
|
for row in rows:
|
|
|
|
assert isinstance(row, UnPartialStatedRoomStreamRow)
|
|
|
|
|
|
|
|
# Wake up any tasks waiting for the room to be un-partial-stated.
|
|
|
|
self._state_storage_controller.notify_room_un_partial_stated(
|
|
|
|
row.room_id
|
|
|
|
)
|
2023-01-23 10:44:39 -05:00
|
|
|
await self.notifier.on_un_partial_stated_room(row.room_id, token)
|
2022-12-19 09:57:51 -05:00
|
|
|
elif stream_name == UnPartialStatedEventStream.NAME:
|
|
|
|
for row in rows:
|
|
|
|
assert isinstance(row, UnPartialStatedEventStreamRow)
|
|
|
|
|
|
|
|
# Wake up any tasks waiting for the event to be un-partial-stated.
|
|
|
|
self._state_storage_controller.notify_event_un_partial_stated(
|
|
|
|
row.event_id
|
|
|
|
)
|
2022-07-19 07:45:17 -04:00
|
|
|
|
2021-04-20 09:11:24 -04:00
|
|
|
await self._presence_handler.process_replication_rows(
|
|
|
|
stream_name, instance_name, token, rows
|
|
|
|
)
|
|
|
|
|
2020-05-22 09:21:54 -04:00
|
|
|
# Notify any waiting deferreds. The list is ordered by position so we
|
|
|
|
# just iterate through the list until we reach a position that is
|
|
|
|
# greater than the received row position.
|
2023-08-22 11:11:22 -04:00
|
|
|
waiting_list = self._streams_to_waiters.get((stream_name, instance_name))
|
|
|
|
if not waiting_list:
|
|
|
|
return
|
2020-05-22 09:21:54 -04:00
|
|
|
|
|
|
|
# Index of first item with a position after the current token, i.e we
|
|
|
|
# have called all deferreds before this index. If not overwritten by
|
|
|
|
# loop below means either a) no items in list so no-op or b) all items
|
|
|
|
# in list were called and so the list should be cleared. Setting it to
|
|
|
|
# `len(list)` works for both cases.
|
|
|
|
index_of_first_deferred_not_called = len(waiting_list)
|
|
|
|
|
2023-01-19 17:19:56 -05:00
|
|
|
# We don't fire the deferreds until after we finish iterating over the
|
|
|
|
# list, to avoid the list changing when we fire the deferreds.
|
|
|
|
deferreds_to_callback = []
|
|
|
|
|
2020-05-22 09:21:54 -04:00
|
|
|
for idx, (position, deferred) in enumerate(waiting_list):
|
|
|
|
if position <= token:
|
2023-01-19 17:19:56 -05:00
|
|
|
deferreds_to_callback.append(deferred)
|
2020-05-22 09:21:54 -04:00
|
|
|
else:
|
|
|
|
# The list is sorted by position so we don't need to continue
|
2020-06-05 08:43:21 -04:00
|
|
|
# checking any further entries in the list.
|
2020-05-22 09:21:54 -04:00
|
|
|
index_of_first_deferred_not_called = idx
|
|
|
|
break
|
|
|
|
|
|
|
|
# Drop all entries in the waiting list that were called in the above
|
|
|
|
# loop. (This maintains the order so no need to resort)
|
2023-08-22 11:11:22 -04:00
|
|
|
del waiting_list[:index_of_first_deferred_not_called]
|
2020-05-22 09:21:54 -04:00
|
|
|
|
2023-01-19 17:19:56 -05:00
|
|
|
for deferred in deferreds_to_callback:
|
|
|
|
try:
|
|
|
|
with PreserveLoggingContext():
|
|
|
|
deferred.callback(None)
|
|
|
|
except Exception:
|
|
|
|
# The deferred has been cancelled or timed out.
|
|
|
|
pass
|
|
|
|
|
2022-02-08 11:03:08 -05:00
|
|
|
async def on_position(
|
|
|
|
self, stream_name: str, instance_name: str, token: int
|
|
|
|
) -> None:
|
2021-04-14 12:06:06 -04:00
|
|
|
await self.on_rdata(stream_name, instance_name, token, [])
|
2019-02-26 10:04:34 -05:00
|
|
|
|
2020-10-12 10:51:41 -04:00
|
|
|
# We poke the generic "replication" notifier to wake anything up that
|
|
|
|
# may be streaming.
|
|
|
|
self.notifier.notify_replication()
|
|
|
|
|
2022-02-08 11:03:08 -05:00
|
|
|
def on_remote_server_up(self, server: str) -> None:
|
2020-04-06 04:58:42 -04:00
|
|
|
"""Called when get a new REMOTE_SERVER_UP command."""
|
2020-05-22 09:21:54 -04:00
|
|
|
|
2021-04-14 12:06:06 -04:00
|
|
|
# Let's wake up the transaction queue for the server in case we have
|
|
|
|
# pending stuff to send to it.
|
|
|
|
if self.send_handler:
|
|
|
|
self.send_handler.wake_destination(server)
|
|
|
|
|
2020-05-22 09:21:54 -04:00
|
|
|
async def wait_for_stream_position(
|
2023-01-18 14:35:29 -05:00
|
|
|
self,
|
|
|
|
instance_name: str,
|
|
|
|
stream_name: str,
|
|
|
|
position: int,
|
2022-02-08 11:03:08 -05:00
|
|
|
) -> None:
|
2020-05-22 09:21:54 -04:00
|
|
|
"""Wait until this instance has received updates up to and including
|
|
|
|
the given stream position.
|
2023-01-18 14:35:29 -05:00
|
|
|
|
|
|
|
Args:
|
|
|
|
instance_name
|
|
|
|
stream_name
|
|
|
|
position
|
2020-05-22 09:21:54 -04:00
|
|
|
"""
|
|
|
|
|
|
|
|
if instance_name == self._instance_name:
|
|
|
|
# We don't get told about updates written by this process, and
|
|
|
|
# anyway in that case we don't need to wait.
|
|
|
|
return
|
|
|
|
|
2023-01-17 04:58:22 -05:00
|
|
|
current_position = self._streams[stream_name].current_token(instance_name)
|
2020-05-22 09:21:54 -04:00
|
|
|
if position <= current_position:
|
|
|
|
# We're already past the position
|
|
|
|
return
|
|
|
|
|
|
|
|
# Create a new deferred that times out after N seconds, as we don't want
|
|
|
|
# to wedge here forever.
|
2021-07-28 08:04:11 -04:00
|
|
|
deferred: "Deferred[None]" = Deferred()
|
2020-05-22 09:21:54 -04:00
|
|
|
deferred = timeout_deferred(
|
|
|
|
deferred, _WAIT_FOR_REPLICATION_TIMEOUT_SECONDS, self._reactor
|
|
|
|
)
|
|
|
|
|
2023-01-19 17:19:56 -05:00
|
|
|
waiting_list = self._streams_to_waiters.setdefault(
|
2023-08-22 11:11:22 -04:00
|
|
|
(stream_name, instance_name), SortedList(key=lambda t: t[0])
|
2023-01-19 17:19:56 -05:00
|
|
|
)
|
2020-05-22 09:21:54 -04:00
|
|
|
|
2023-08-22 11:11:22 -04:00
|
|
|
waiting_list.add((position, deferred))
|
2020-05-22 09:21:54 -04:00
|
|
|
|
|
|
|
# We measure here to get in flight counts and average waiting time.
|
|
|
|
with Measure(self._clock, "repl.wait_for_stream_position"):
|
2023-01-20 16:04:33 -05:00
|
|
|
logger.info(
|
2023-02-21 07:26:00 -05:00
|
|
|
"Waiting for repl stream %r to reach %s (%s); currently at: %s",
|
2023-01-20 16:04:33 -05:00
|
|
|
stream_name,
|
|
|
|
position,
|
|
|
|
instance_name,
|
2023-02-21 07:26:00 -05:00
|
|
|
current_position,
|
2023-01-20 16:04:33 -05:00
|
|
|
)
|
2023-01-18 14:35:29 -05:00
|
|
|
try:
|
|
|
|
await make_deferred_yieldable(deferred)
|
|
|
|
except defer.TimeoutError:
|
2023-02-21 07:26:00 -05:00
|
|
|
logger.error(
|
|
|
|
"Timed out waiting for repl stream %r to reach %s (%s)"
|
|
|
|
"; currently at: %s",
|
|
|
|
stream_name,
|
|
|
|
position,
|
|
|
|
instance_name,
|
|
|
|
self._streams[stream_name].current_token(instance_name),
|
|
|
|
)
|
2023-01-18 14:35:29 -05:00
|
|
|
return
|
|
|
|
|
2020-05-22 09:21:54 -04:00
|
|
|
logger.info(
|
2023-01-20 16:04:33 -05:00
|
|
|
"Finished waiting for repl stream %r to reach %s (%s)",
|
|
|
|
stream_name,
|
|
|
|
position,
|
|
|
|
instance_name,
|
2020-05-22 09:21:54 -04:00
|
|
|
)
|
2021-04-14 12:06:06 -04:00
|
|
|
|
2022-02-08 11:03:08 -05:00
|
|
|
def stop_pusher(self, user_id: str, app_id: str, pushkey: str) -> None:
|
2021-04-14 12:06:06 -04:00
|
|
|
if not self._notify_pushers:
|
|
|
|
return
|
|
|
|
|
|
|
|
key = "%s:%s" % (app_id, pushkey)
|
|
|
|
pushers_for_user = self._pusher_pool.pushers.get(user_id, {})
|
|
|
|
pusher = pushers_for_user.pop(key, None)
|
|
|
|
if pusher is None:
|
|
|
|
return
|
|
|
|
logger.info("Stopping pusher %r / %r", user_id, key)
|
|
|
|
pusher.on_stop()
|
|
|
|
|
2022-09-21 10:39:01 -04:00
|
|
|
async def process_pusher_change(
|
|
|
|
self, user_id: str, app_id: str, pushkey: str
|
|
|
|
) -> None:
|
2021-04-14 12:06:06 -04:00
|
|
|
if not self._notify_pushers:
|
|
|
|
return
|
|
|
|
|
|
|
|
key = "%s:%s" % (app_id, pushkey)
|
|
|
|
logger.info("Starting pusher %r / %r", user_id, key)
|
2022-09-21 10:39:01 -04:00
|
|
|
await self._pusher_pool.process_pusher_change_by_id(app_id, pushkey, user_id)
|
2021-04-14 12:06:06 -04:00
|
|
|
|
|
|
|
|
|
|
|
class FederationSenderHandler:
|
|
|
|
"""Processes the fedration replication stream
|
|
|
|
|
|
|
|
This class is only instantiate on the worker responsible for sending outbound
|
|
|
|
federation transactions. It receives rows from the replication stream and forwards
|
|
|
|
the appropriate entries to the FederationSender class.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, hs: "HomeServer"):
|
|
|
|
assert hs.should_send_federation()
|
|
|
|
|
2022-02-23 06:04:02 -05:00
|
|
|
self.store = hs.get_datastores().main
|
2021-04-14 12:06:06 -04:00
|
|
|
self._is_mine_id = hs.is_mine_id
|
|
|
|
self._hs = hs
|
|
|
|
|
|
|
|
# We need to make a temporary value to ensure that mypy picks up the
|
|
|
|
# right type. We know we should have a federation sender instance since
|
|
|
|
# `should_send_federation` is True.
|
|
|
|
sender = hs.get_federation_sender()
|
|
|
|
assert isinstance(sender, FederationSender)
|
|
|
|
self.federation_sender = sender
|
|
|
|
|
|
|
|
# Stores the latest position in the federation stream we've gotten up
|
|
|
|
# to. This is always set before we use it.
|
2021-07-15 06:02:43 -04:00
|
|
|
self.federation_position: Optional[int] = None
|
2021-04-14 12:06:06 -04:00
|
|
|
|
|
|
|
self._fed_position_linearizer = Linearizer(name="_fed_position_linearizer")
|
|
|
|
|
2022-02-08 11:03:08 -05:00
|
|
|
def wake_destination(self, server: str) -> None:
|
2021-04-14 12:06:06 -04:00
|
|
|
self.federation_sender.wake_destination(server)
|
|
|
|
|
2022-02-08 11:03:08 -05:00
|
|
|
async def process_replication_rows(
|
|
|
|
self, stream_name: str, token: int, rows: list
|
|
|
|
) -> None:
|
2021-04-14 12:06:06 -04:00
|
|
|
# The federation stream contains things that we want to send out, e.g.
|
|
|
|
# presence, typing, etc.
|
|
|
|
if stream_name == "federation":
|
2023-09-04 12:14:09 -04:00
|
|
|
await send_queue.process_rows_for_federation(self.federation_sender, rows)
|
2021-04-14 12:06:06 -04:00
|
|
|
await self.update_token(token)
|
|
|
|
|
|
|
|
# ... and when new receipts happen
|
|
|
|
elif stream_name == ReceiptsStream.NAME:
|
|
|
|
await self._on_new_receipts(rows)
|
|
|
|
|
|
|
|
# ... as well as device updates and messages
|
|
|
|
elif stream_name == DeviceListsStream.NAME:
|
|
|
|
# The entities are either user IDs (starting with '@') whose devices
|
|
|
|
# have changed, or remote servers that we need to tell about
|
|
|
|
# changes.
|
2023-01-17 04:29:58 -05:00
|
|
|
hosts = {
|
|
|
|
row.entity
|
|
|
|
for row in rows
|
|
|
|
if not row.entity.startswith("@") and not row.is_signature
|
|
|
|
}
|
2023-09-04 12:14:09 -04:00
|
|
|
await self.federation_sender.send_device_messages(hosts, immediate=False)
|
2021-04-14 12:06:06 -04:00
|
|
|
|
|
|
|
elif stream_name == ToDeviceStream.NAME:
|
|
|
|
# The to_device stream includes stuff to be pushed to both local
|
|
|
|
# clients and remote servers, so we ignore entities that start with
|
|
|
|
# '@' (since they'll be local users rather than destinations).
|
|
|
|
hosts = {row.entity for row in rows if not row.entity.startswith("@")}
|
2023-09-04 12:14:09 -04:00
|
|
|
await self.federation_sender.send_device_messages(hosts)
|
2021-04-14 12:06:06 -04:00
|
|
|
|
2022-02-08 11:03:08 -05:00
|
|
|
async def _on_new_receipts(
|
|
|
|
self, rows: Iterable[ReceiptsStream.ReceiptsStreamRow]
|
|
|
|
) -> None:
|
2021-04-14 12:06:06 -04:00
|
|
|
"""
|
|
|
|
Args:
|
2022-02-08 11:03:08 -05:00
|
|
|
rows: new receipts to be processed
|
2021-04-14 12:06:06 -04:00
|
|
|
"""
|
|
|
|
for receipt in rows:
|
|
|
|
# we only want to send on receipts for our own users
|
|
|
|
if not self._is_mine_id(receipt.user_id):
|
|
|
|
continue
|
2022-05-05 09:25:51 -04:00
|
|
|
# Private read receipts never get sent over federation.
|
2022-09-01 08:31:54 -04:00
|
|
|
if receipt.receipt_type == ReceiptTypes.READ_PRIVATE:
|
2021-07-28 04:05:11 -04:00
|
|
|
continue
|
2021-04-14 12:06:06 -04:00
|
|
|
receipt_info = ReadReceipt(
|
|
|
|
receipt.room_id,
|
|
|
|
receipt.receipt_type,
|
|
|
|
receipt.user_id,
|
|
|
|
[receipt.event_id],
|
2022-09-23 10:33:28 -04:00
|
|
|
thread_id=receipt.thread_id,
|
|
|
|
data=receipt.data,
|
2021-04-14 12:06:06 -04:00
|
|
|
)
|
|
|
|
await self.federation_sender.send_read_receipt(receipt_info)
|
|
|
|
|
2022-02-08 11:03:08 -05:00
|
|
|
async def update_token(self, token: int) -> None:
|
2021-04-14 12:06:06 -04:00
|
|
|
"""Update the record of where we have processed to in the federation stream.
|
|
|
|
|
|
|
|
Called after we have processed a an update received over replication. Sends
|
|
|
|
a FEDERATION_ACK back to the master, and stores the token that we have processed
|
|
|
|
in `federation_stream_position` so that we can restart where we left off.
|
|
|
|
"""
|
|
|
|
self.federation_position = token
|
|
|
|
|
|
|
|
# We save and send the ACK to master asynchronously, so we don't block
|
|
|
|
# processing on persistence. We don't need to do this operation for
|
|
|
|
# every single RDATA we receive, we just need to do it periodically.
|
|
|
|
|
|
|
|
if self._fed_position_linearizer.is_queued(None):
|
|
|
|
# There is already a task queued up to save and send the token, so
|
|
|
|
# no need to queue up another task.
|
|
|
|
return
|
|
|
|
|
|
|
|
run_as_background_process("_save_and_send_ack", self._save_and_send_ack)
|
|
|
|
|
2022-02-08 11:03:08 -05:00
|
|
|
async def _save_and_send_ack(self) -> None:
|
2021-04-14 12:06:06 -04:00
|
|
|
"""Save the current federation position in the database and send an ACK
|
|
|
|
to master with where we're up to.
|
|
|
|
"""
|
|
|
|
# We should only be calling this once we've got a token.
|
|
|
|
assert self.federation_position is not None
|
|
|
|
|
|
|
|
try:
|
|
|
|
# We linearize here to ensure we don't have races updating the token
|
|
|
|
#
|
|
|
|
# XXX this appears to be redundant, since the ReplicationCommandHandler
|
|
|
|
# has a linearizer which ensures that we only process one line of
|
|
|
|
# replication data at a time. Should we remove it, or is it doing useful
|
|
|
|
# service for robustness? Or could we replace it with an assertion that
|
|
|
|
# we're not being re-entered?
|
|
|
|
|
2022-04-05 10:43:52 -04:00
|
|
|
async with self._fed_position_linearizer.queue(None):
|
2021-04-14 12:06:06 -04:00
|
|
|
# We persist and ack the same position, so we take a copy of it
|
|
|
|
# here as otherwise it can get modified from underneath us.
|
|
|
|
current_position = self.federation_position
|
|
|
|
|
|
|
|
await self.store.update_federation_out_pos(
|
|
|
|
"federation", current_position
|
|
|
|
)
|
|
|
|
|
|
|
|
# We ACK this token over replication so that the master can drop
|
|
|
|
# its in memory queues
|
2022-03-10 08:01:56 -05:00
|
|
|
self._hs.get_replication_command_handler().send_federation_ack(
|
|
|
|
current_position
|
|
|
|
)
|
2021-04-14 12:06:06 -04:00
|
|
|
except Exception:
|
|
|
|
logger.exception("Error updating federation stream position")
|