__init__.py 27 KB

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