__init__.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. # Copyright 2019 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import abc
  15. import logging
  16. from collections import OrderedDict
  17. from typing import TYPE_CHECKING, Dict, Hashable, Iterable, List, Optional, Set, Tuple
  18. import attr
  19. from prometheus_client import Counter
  20. from typing_extensions import Literal
  21. from twisted.internet import defer
  22. import synapse.metrics
  23. from synapse.api.presence import UserPresenceState
  24. from synapse.events import EventBase
  25. from synapse.federation.sender.per_destination_queue import PerDestinationQueue
  26. from synapse.federation.sender.transaction_manager import TransactionManager
  27. from synapse.federation.units import Edu
  28. from synapse.logging.context import make_deferred_yieldable, run_in_background
  29. from synapse.metrics import (
  30. LaterGauge,
  31. event_processing_loop_counter,
  32. event_processing_loop_room_count,
  33. events_processed_counter,
  34. )
  35. from synapse.metrics.background_process_metrics import (
  36. run_as_background_process,
  37. wrap_as_background_process,
  38. )
  39. from synapse.types import JsonDict, ReadReceipt, RoomStreamToken
  40. from synapse.util import Clock
  41. from synapse.util.metrics import Measure
  42. if TYPE_CHECKING:
  43. from synapse.events.presence_router import PresenceRouter
  44. from synapse.server import HomeServer
  45. logger = logging.getLogger(__name__)
  46. sent_pdus_destination_dist_count = Counter(
  47. "synapse_federation_client_sent_pdu_destinations:count",
  48. "Number of PDUs queued for sending to one or more destinations",
  49. )
  50. sent_pdus_destination_dist_total = Counter(
  51. "synapse_federation_client_sent_pdu_destinations:total",
  52. "Total number of PDUs queued for sending across all destinations",
  53. )
  54. # Time (in s) after Synapse's startup that we will begin to wake up destinations
  55. # that have catch-up outstanding.
  56. CATCH_UP_STARTUP_DELAY_SEC = 15
  57. # Time (in s) to wait in between waking up each destination, i.e. one destination
  58. # will be woken up every <x> seconds after Synapse's startup until we have woken
  59. # every destination has outstanding catch-up.
  60. CATCH_UP_STARTUP_INTERVAL_SEC = 5
  61. class AbstractFederationSender(metaclass=abc.ABCMeta):
  62. @abc.abstractmethod
  63. def notify_new_events(self, max_token: RoomStreamToken) -> None:
  64. """This gets called when we have some new events we might want to
  65. send out to other servers.
  66. """
  67. raise NotImplementedError()
  68. @abc.abstractmethod
  69. async def send_read_receipt(self, receipt: ReadReceipt) -> None:
  70. """Send a RR to any other servers in the room
  71. Args:
  72. receipt: receipt to be sent
  73. """
  74. raise NotImplementedError()
  75. @abc.abstractmethod
  76. def send_presence_to_destinations(
  77. self, states: Iterable[UserPresenceState], destinations: Iterable[str]
  78. ) -> None:
  79. """Send the given presence states to the given destinations.
  80. Args:
  81. destinations:
  82. """
  83. raise NotImplementedError()
  84. @abc.abstractmethod
  85. def build_and_send_edu(
  86. self,
  87. destination: str,
  88. edu_type: str,
  89. content: JsonDict,
  90. key: Optional[Hashable] = None,
  91. ) -> None:
  92. """Construct an Edu object, and queue it for sending
  93. Args:
  94. destination: name of server to send to
  95. edu_type: type of EDU to send
  96. content: content of EDU
  97. key: clobbering key for this edu
  98. """
  99. raise NotImplementedError()
  100. @abc.abstractmethod
  101. def send_device_messages(self, destination: str) -> None:
  102. raise NotImplementedError()
  103. @abc.abstractmethod
  104. def wake_destination(self, destination: str) -> None:
  105. """Called when we want to retry sending transactions to a remote.
  106. This is mainly useful if the remote server has been down and we think it
  107. might have come back.
  108. """
  109. raise NotImplementedError()
  110. @abc.abstractmethod
  111. def get_current_token(self) -> int:
  112. raise NotImplementedError()
  113. @abc.abstractmethod
  114. def federation_ack(self, instance_name: str, token: int) -> None:
  115. raise NotImplementedError()
  116. @abc.abstractmethod
  117. async def get_replication_rows(
  118. self, instance_name: str, from_token: int, to_token: int, target_row_count: int
  119. ) -> Tuple[List[Tuple[int, Tuple]], int, bool]:
  120. raise NotImplementedError()
  121. @attr.s
  122. class _PresenceQueue:
  123. """A queue of destinations that need to be woken up due to new presence
  124. updates.
  125. Staggers waking up of per destination queues to ensure that we don't attempt
  126. to start TLS connections with many hosts all at once, leading to pinned CPU.
  127. """
  128. # The maximum duration in seconds between queuing up a destination and it
  129. # being woken up.
  130. _MAX_TIME_IN_QUEUE = 30.0
  131. # The maximum duration in seconds between waking up consecutive destination
  132. # queues.
  133. _MAX_DELAY = 0.1
  134. sender: "FederationSender" = attr.ib()
  135. clock: Clock = attr.ib()
  136. queue: "OrderedDict[str, Literal[None]]" = attr.ib(factory=OrderedDict)
  137. processing: bool = attr.ib(default=False)
  138. def add_to_queue(self, destination: str) -> None:
  139. """Add a destination to the queue to be woken up."""
  140. self.queue[destination] = None
  141. if not self.processing:
  142. self._handle()
  143. @wrap_as_background_process("_PresenceQueue.handle")
  144. async def _handle(self) -> None:
  145. """Background process to drain the queue."""
  146. if not self.queue:
  147. return
  148. assert not self.processing
  149. self.processing = True
  150. try:
  151. # We start with a delay that should drain the queue quickly enough that
  152. # we process all destinations in the queue in _MAX_TIME_IN_QUEUE
  153. # seconds.
  154. #
  155. # We also add an upper bound to the delay, to gracefully handle the
  156. # case where the queue only has a few entries in it.
  157. current_sleep_seconds = min(
  158. self._MAX_DELAY, self._MAX_TIME_IN_QUEUE / len(self.queue)
  159. )
  160. while self.queue:
  161. destination, _ = self.queue.popitem(last=False)
  162. queue = self.sender._get_per_destination_queue(destination)
  163. if not queue._new_data_to_send:
  164. # The per destination queue has already been woken up.
  165. continue
  166. queue.attempt_new_transaction()
  167. await self.clock.sleep(current_sleep_seconds)
  168. if not self.queue:
  169. break
  170. # More destinations may have been added to the queue, so we may
  171. # need to reduce the delay to ensure everything gets processed
  172. # within _MAX_TIME_IN_QUEUE seconds.
  173. current_sleep_seconds = min(
  174. current_sleep_seconds, self._MAX_TIME_IN_QUEUE / len(self.queue)
  175. )
  176. finally:
  177. self.processing = False
  178. class FederationSender(AbstractFederationSender):
  179. def __init__(self, hs: "HomeServer"):
  180. self.hs = hs
  181. self.server_name = hs.hostname
  182. self.store = hs.get_datastore()
  183. self.state = hs.get_state_handler()
  184. self.clock = hs.get_clock()
  185. self.is_mine_id = hs.is_mine_id
  186. self._presence_router: Optional["PresenceRouter"] = None
  187. self._transaction_manager = TransactionManager(hs)
  188. self._instance_name = hs.get_instance_name()
  189. self._federation_shard_config = hs.config.worker.federation_shard_config
  190. # map from destination to PerDestinationQueue
  191. self._per_destination_queues: Dict[str, PerDestinationQueue] = {}
  192. LaterGauge(
  193. "synapse_federation_transaction_queue_pending_destinations",
  194. "",
  195. [],
  196. lambda: sum(
  197. 1
  198. for d in self._per_destination_queues.values()
  199. if d.transmission_loop_running
  200. ),
  201. )
  202. LaterGauge(
  203. "synapse_federation_transaction_queue_pending_pdus",
  204. "",
  205. [],
  206. lambda: sum(
  207. d.pending_pdu_count() for d in self._per_destination_queues.values()
  208. ),
  209. )
  210. LaterGauge(
  211. "synapse_federation_transaction_queue_pending_edus",
  212. "",
  213. [],
  214. lambda: sum(
  215. d.pending_edu_count() for d in self._per_destination_queues.values()
  216. ),
  217. )
  218. self._is_processing = False
  219. self._last_poked_id = -1
  220. # map from room_id to a set of PerDestinationQueues which we believe are
  221. # awaiting a call to flush_read_receipts_for_room. The presence of an entry
  222. # here for a given room means that we are rate-limiting RR flushes to that room,
  223. # and that there is a pending call to _flush_rrs_for_room in the system.
  224. self._queues_awaiting_rr_flush_by_room: Dict[str, Set[PerDestinationQueue]] = {}
  225. self._rr_txn_interval_per_room_ms = (
  226. 1000.0 / hs.config.federation_rr_transactions_per_room_per_second
  227. )
  228. # wake up destinations that have outstanding PDUs to be caught up
  229. self._catchup_after_startup_timer = self.clock.call_later(
  230. CATCH_UP_STARTUP_DELAY_SEC,
  231. run_as_background_process,
  232. "wake_destinations_needing_catchup",
  233. self._wake_destinations_needing_catchup,
  234. )
  235. self._external_cache = hs.get_external_cache()
  236. self._presence_queue = _PresenceQueue(self, self.clock)
  237. def _get_per_destination_queue(self, destination: str) -> PerDestinationQueue:
  238. """Get or create a PerDestinationQueue for the given destination
  239. Args:
  240. destination: server_name of remote server
  241. """
  242. queue = self._per_destination_queues.get(destination)
  243. if not queue:
  244. queue = PerDestinationQueue(self.hs, self._transaction_manager, destination)
  245. self._per_destination_queues[destination] = queue
  246. return queue
  247. def notify_new_events(self, max_token: RoomStreamToken) -> None:
  248. """This gets called when we have some new events we might want to
  249. send out to other servers.
  250. """
  251. # We just use the minimum stream ordering and ignore the vector clock
  252. # component. This is safe to do as long as we *always* ignore the vector
  253. # clock components.
  254. current_id = max_token.stream
  255. self._last_poked_id = max(current_id, self._last_poked_id)
  256. if self._is_processing:
  257. return
  258. # fire off a processing loop in the background
  259. run_as_background_process(
  260. "process_event_queue_for_federation", self._process_event_queue_loop
  261. )
  262. async def _process_event_queue_loop(self) -> None:
  263. try:
  264. self._is_processing = True
  265. while True:
  266. last_token = await self.store.get_federation_out_pos("events")
  267. next_token, events = await self.store.get_all_new_events_stream(
  268. last_token, self._last_poked_id, limit=100
  269. )
  270. logger.debug("Handling %s -> %s", last_token, next_token)
  271. if not events and next_token >= self._last_poked_id:
  272. break
  273. async def handle_event(event: EventBase) -> None:
  274. # Only send events for this server.
  275. send_on_behalf_of = event.internal_metadata.get_send_on_behalf_of()
  276. is_mine = self.is_mine_id(event.sender)
  277. if not is_mine and send_on_behalf_of is None:
  278. return
  279. if not event.internal_metadata.should_proactively_send():
  280. return
  281. destinations: Optional[Set[str]] = None
  282. if not event.prev_event_ids():
  283. # If there are no prev event IDs then the state is empty
  284. # and so no remote servers in the room
  285. destinations = set()
  286. else:
  287. # We check the external cache for the destinations, which is
  288. # stored per state group.
  289. sg = await self._external_cache.get(
  290. "event_to_prev_state_group", event.event_id
  291. )
  292. if sg:
  293. destinations = await self._external_cache.get(
  294. "get_joined_hosts", str(sg)
  295. )
  296. if destinations is None:
  297. try:
  298. # Get the state from before the event.
  299. # We need to make sure that this is the state from before
  300. # the event and not from after it.
  301. # Otherwise if the last member on a server in a room is
  302. # banned then it won't receive the event because it won't
  303. # be in the room after the ban.
  304. destinations = await self.state.get_hosts_in_room_at_events(
  305. event.room_id, event_ids=event.prev_event_ids()
  306. )
  307. except Exception:
  308. logger.exception(
  309. "Failed to calculate hosts in room for event: %s",
  310. event.event_id,
  311. )
  312. return
  313. destinations = {
  314. d
  315. for d in destinations
  316. if self._federation_shard_config.should_handle(
  317. self._instance_name, d
  318. )
  319. }
  320. if send_on_behalf_of is not None:
  321. # If we are sending the event on behalf of another server
  322. # then it already has the event and there is no reason to
  323. # send the event to it.
  324. destinations.discard(send_on_behalf_of)
  325. logger.debug("Sending %s to %r", event, destinations)
  326. if destinations:
  327. await self._send_pdu(event, destinations)
  328. now = self.clock.time_msec()
  329. ts = await self.store.get_received_ts(event.event_id)
  330. synapse.metrics.event_processing_lag_by_event.labels(
  331. "federation_sender"
  332. ).observe((now - ts) / 1000)
  333. async def handle_room_events(events: Iterable[EventBase]) -> None:
  334. with Measure(self.clock, "handle_room_events"):
  335. for event in events:
  336. await handle_event(event)
  337. events_by_room: Dict[str, List[EventBase]] = {}
  338. for event in events:
  339. events_by_room.setdefault(event.room_id, []).append(event)
  340. await make_deferred_yieldable(
  341. defer.gatherResults(
  342. [
  343. run_in_background(handle_room_events, evs)
  344. for evs in events_by_room.values()
  345. ],
  346. consumeErrors=True,
  347. )
  348. )
  349. await self.store.update_federation_out_pos("events", next_token)
  350. if events:
  351. now = self.clock.time_msec()
  352. ts = await self.store.get_received_ts(events[-1].event_id)
  353. synapse.metrics.event_processing_lag.labels(
  354. "federation_sender"
  355. ).set(now - ts)
  356. synapse.metrics.event_processing_last_ts.labels(
  357. "federation_sender"
  358. ).set(ts)
  359. events_processed_counter.inc(len(events))
  360. event_processing_loop_room_count.labels("federation_sender").inc(
  361. len(events_by_room)
  362. )
  363. event_processing_loop_counter.labels("federation_sender").inc()
  364. synapse.metrics.event_processing_positions.labels(
  365. "federation_sender"
  366. ).set(next_token)
  367. finally:
  368. self._is_processing = False
  369. async def _send_pdu(self, pdu: EventBase, destinations: Iterable[str]) -> None:
  370. # We loop through all destinations to see whether we already have
  371. # a transaction in progress. If we do, stick it in the pending_pdus
  372. # table and we'll get back to it later.
  373. destinations = set(destinations)
  374. destinations.discard(self.server_name)
  375. logger.debug("Sending to: %s", str(destinations))
  376. if not destinations:
  377. return
  378. sent_pdus_destination_dist_total.inc(len(destinations))
  379. sent_pdus_destination_dist_count.inc()
  380. assert pdu.internal_metadata.stream_ordering
  381. # track the fact that we have a PDU for these destinations,
  382. # to allow us to perform catch-up later on if the remote is unreachable
  383. # for a while.
  384. await self.store.store_destination_rooms_entries(
  385. destinations,
  386. pdu.room_id,
  387. pdu.internal_metadata.stream_ordering,
  388. )
  389. for destination in destinations:
  390. self._get_per_destination_queue(destination).send_pdu(pdu)
  391. async def send_read_receipt(self, receipt: ReadReceipt) -> None:
  392. """Send a RR to any other servers in the room
  393. Args:
  394. receipt: receipt to be sent
  395. """
  396. # Some background on the rate-limiting going on here.
  397. #
  398. # It turns out that if we attempt to send out RRs as soon as we get them from
  399. # a client, then we end up trying to do several hundred Hz of federation
  400. # transactions. (The number of transactions scales as O(N^2) on the size of a
  401. # room, since in a large room we have both more RRs coming in, and more servers
  402. # to send them to.)
  403. #
  404. # This leads to a lot of CPU load, and we end up getting behind. The solution
  405. # currently adopted is as follows:
  406. #
  407. # The first receipt in a given room is sent out immediately, at time T0. Any
  408. # further receipts are, in theory, batched up for N seconds, where N is calculated
  409. # based on the number of servers in the room to achieve a transaction frequency
  410. # of around 50Hz. So, for example, if there were 100 servers in the room, then
  411. # N would be 100 / 50Hz = 2 seconds.
  412. #
  413. # Then, after T+N, we flush out any receipts that have accumulated, and restart
  414. # the timer to flush out more receipts at T+2N, etc. If no receipts accumulate,
  415. # we stop the cycle and go back to the start.
  416. #
  417. # However, in practice, it is often possible to flush out receipts earlier: in
  418. # particular, if we are sending a transaction to a given server anyway (for
  419. # example, because we have a PDU or a RR in another room to send), then we may
  420. # as well send out all of the pending RRs for that server. So it may be that
  421. # by the time we get to T+N, we don't actually have any RRs left to send out.
  422. # Nevertheless we continue to buffer up RRs for the room in question until we
  423. # reach the point that no RRs arrive between timer ticks.
  424. #
  425. # For even more background, see https://github.com/matrix-org/synapse/issues/4730.
  426. room_id = receipt.room_id
  427. # Work out which remote servers should be poked and poke them.
  428. domains_set = await self.state.get_current_hosts_in_room(room_id)
  429. domains = [
  430. d
  431. for d in domains_set
  432. if d != self.server_name
  433. and self._federation_shard_config.should_handle(self._instance_name, d)
  434. ]
  435. if not domains:
  436. return
  437. queues_pending_flush = self._queues_awaiting_rr_flush_by_room.get(room_id)
  438. # if there is no flush yet scheduled, we will send out these receipts with
  439. # immediate flushes, and schedule the next flush for this room.
  440. if queues_pending_flush is not None:
  441. logger.debug("Queuing receipt for: %r", domains)
  442. else:
  443. logger.debug("Sending receipt to: %r", domains)
  444. self._schedule_rr_flush_for_room(room_id, len(domains))
  445. for domain in domains:
  446. queue = self._get_per_destination_queue(domain)
  447. queue.queue_read_receipt(receipt)
  448. # if there is already a RR flush pending for this room, then make sure this
  449. # destination is registered for the flush
  450. if queues_pending_flush is not None:
  451. queues_pending_flush.add(queue)
  452. else:
  453. queue.flush_read_receipts_for_room(room_id)
  454. def _schedule_rr_flush_for_room(self, room_id: str, n_domains: int) -> None:
  455. # that is going to cause approximately len(domains) transactions, so now back
  456. # off for that multiplied by RR_TXN_INTERVAL_PER_ROOM
  457. backoff_ms = self._rr_txn_interval_per_room_ms * n_domains
  458. logger.debug("Scheduling RR flush in %s in %d ms", room_id, backoff_ms)
  459. self.clock.call_later(backoff_ms, self._flush_rrs_for_room, room_id)
  460. self._queues_awaiting_rr_flush_by_room[room_id] = set()
  461. def _flush_rrs_for_room(self, room_id: str) -> None:
  462. queues = self._queues_awaiting_rr_flush_by_room.pop(room_id)
  463. logger.debug("Flushing RRs in %s to %s", room_id, queues)
  464. if not queues:
  465. # no more RRs arrived for this room; we are done.
  466. return
  467. # schedule the next flush
  468. self._schedule_rr_flush_for_room(room_id, len(queues))
  469. for queue in queues:
  470. queue.flush_read_receipts_for_room(room_id)
  471. def send_presence_to_destinations(
  472. self, states: Iterable[UserPresenceState], destinations: Iterable[str]
  473. ) -> None:
  474. """Send the given presence states to the given destinations.
  475. destinations (list[str])
  476. """
  477. if not states or not self.hs.config.use_presence:
  478. # No-op if presence is disabled.
  479. return
  480. # Ensure we only send out presence states for local users.
  481. for state in states:
  482. assert self.is_mine_id(state.user_id)
  483. for destination in destinations:
  484. if destination == self.server_name:
  485. continue
  486. if not self._federation_shard_config.should_handle(
  487. self._instance_name, destination
  488. ):
  489. continue
  490. self._get_per_destination_queue(destination).send_presence(
  491. states, start_loop=False
  492. )
  493. self._presence_queue.add_to_queue(destination)
  494. def build_and_send_edu(
  495. self,
  496. destination: str,
  497. edu_type: str,
  498. content: JsonDict,
  499. key: Optional[Hashable] = None,
  500. ) -> None:
  501. """Construct an Edu object, and queue it for sending
  502. Args:
  503. destination: name of server to send to
  504. edu_type: type of EDU to send
  505. content: content of EDU
  506. key: clobbering key for this edu
  507. """
  508. if destination == self.server_name:
  509. logger.info("Not sending EDU to ourselves")
  510. return
  511. if not self._federation_shard_config.should_handle(
  512. self._instance_name, destination
  513. ):
  514. return
  515. edu = Edu(
  516. origin=self.server_name,
  517. destination=destination,
  518. edu_type=edu_type,
  519. content=content,
  520. )
  521. self.send_edu(edu, key)
  522. def send_edu(self, edu: Edu, key: Optional[Hashable]) -> None:
  523. """Queue an EDU for sending
  524. Args:
  525. edu: edu to send
  526. key: clobbering key for this edu
  527. """
  528. if not self._federation_shard_config.should_handle(
  529. self._instance_name, edu.destination
  530. ):
  531. return
  532. queue = self._get_per_destination_queue(edu.destination)
  533. if key:
  534. queue.send_keyed_edu(edu, key)
  535. else:
  536. queue.send_edu(edu)
  537. def send_device_messages(self, destination: str) -> None:
  538. if destination == self.server_name:
  539. logger.warning("Not sending device update to ourselves")
  540. return
  541. if not self._federation_shard_config.should_handle(
  542. self._instance_name, destination
  543. ):
  544. return
  545. self._get_per_destination_queue(destination).attempt_new_transaction()
  546. def wake_destination(self, destination: str) -> None:
  547. """Called when we want to retry sending transactions to a remote.
  548. This is mainly useful if the remote server has been down and we think it
  549. might have come back.
  550. """
  551. if destination == self.server_name:
  552. logger.warning("Not waking up ourselves")
  553. return
  554. if not self._federation_shard_config.should_handle(
  555. self._instance_name, destination
  556. ):
  557. return
  558. self._get_per_destination_queue(destination).attempt_new_transaction()
  559. @staticmethod
  560. def get_current_token() -> int:
  561. # Dummy implementation for case where federation sender isn't offloaded
  562. # to a worker.
  563. return 0
  564. def federation_ack(self, instance_name: str, token: int) -> None:
  565. # It is not expected that this gets called on FederationSender.
  566. raise NotImplementedError()
  567. @staticmethod
  568. async def get_replication_rows(
  569. instance_name: str, from_token: int, to_token: int, target_row_count: int
  570. ) -> Tuple[List[Tuple[int, Tuple]], int, bool]:
  571. # Dummy implementation for case where federation sender isn't offloaded
  572. # to a worker.
  573. return [], 0, False
  574. async def _wake_destinations_needing_catchup(self) -> None:
  575. """
  576. Wakes up destinations that need catch-up and are not currently being
  577. backed off from.
  578. In order to reduce load spikes, adds a delay between each destination.
  579. """
  580. last_processed: Optional[str] = None
  581. while True:
  582. destinations_to_wake = (
  583. await self.store.get_catch_up_outstanding_destinations(last_processed)
  584. )
  585. if not destinations_to_wake:
  586. # finished waking all destinations!
  587. self._catchup_after_startup_timer = None
  588. break
  589. last_processed = destinations_to_wake[-1]
  590. destinations_to_wake = [
  591. d
  592. for d in destinations_to_wake
  593. if self._federation_shard_config.should_handle(self._instance_name, d)
  594. ]
  595. for destination in destinations_to_wake:
  596. logger.info(
  597. "Destination %s has outstanding catch-up, waking up.",
  598. last_processed,
  599. )
  600. self.wake_destination(destination)
  601. await self.clock.sleep(CATCH_UP_STARTUP_INTERVAL_SEC)