Skip to main content

moq_net/
reconnect.rs

1//! Client connect policy: which of a peer's addresses to dial, how long each dial may
2//! take, when to back off and when to give up, and how to follow a GOAWAY.
3//!
4//! [`Reconnect`] is a poll machine that does no I/O. The caller dials each [`Attempt`]
5//! it asks for, reports the result with [`Reconnect::connected`] or
6//! [`Reconnect::failed`], and otherwise polls it with the current time. The machine
7//! watches each live session for its close and GOAWAY itself, keeps a drained
8//! predecessor serving through its handover, and drops neither on the caller's behalf
9//! until it reports [`Action::Done`]. A connected session serves only once the machine
10//! reports it [`Action::Established`], so a caller never shows a refusal as connected.
11//!
12//! The policy fails fast until a session is established: the peer accepts the connection
13//! credential (its SETUP, or on moq-lite-07-wip the AUTH_OK to the connection's own
14//! credential) or drains the session with a GOAWAY. On moq-lite 03/04, which answer the
15//! credential with nothing, staying up past [`Backoff::healthy`] establishes it too; a
16//! version with an answer waits for it however long the session stays up. A failed walk,
17//! or a session closed before then, ends the policy
18//! with [`Action::Done`] carrying that error rather than retrying, so a setup mistake
19//! surfaces at once instead of looping. That covers a peer that refuses the session right
20//! after connecting, as a relay rejecting a token on moq-lite 03 or later does. A client
21//! started before its peer is reachable therefore exits, for its supervisor or app to
22//! restart. Once a session has been established, a later failure backs off and retries
23//! under [`Backoff`], so restarts and redeploys still recover. A policy given [`Dials`] fails fast
24//! the same way; once established, the caller reads why each redial follows a failure on
25//! [`Dial::failure`] and ends the policy by failing the dial.
26//!
27//! A caller whose session landed on a fallback transport says so with
28//! [`Reconnect::fallback`]. The machine then asks for [`Action::Probe`]s of the preferred
29//! transport on a slow backoff and, once one gets through, moves to it through the same
30//! handover a GOAWAY uses: the old session drains, and on lite-07 its live tracks continue on
31//! the replacement. lite-05/06 carry no instance, so their tracks end when the old session does.
32
33mod dials;
34mod redirect;
35#[cfg(test)]
36mod tests;
37
38pub use dials::{Dial, Dials};
39pub use redirect::Redirect;
40
41use std::{collections::VecDeque, task::Poll, time::Duration};
42
43use rand::RngExt;
44use url::Url;
45
46use crate::{Error, Session, auth, goaway, time::Instant};
47use redirect::{Redirects, Shown, endpoint};
48
49/// How long one address gets before the walk moves to the peer's next one.
50///
51/// A black-holed address answers nothing rather than refusing, so without a bound the
52/// transport's idle timeout would decide how long the remaining addresses wait. Only an
53/// attempt with a later address to fall back on is worth bounding: cutting the last one
54/// short just turns a slow connect into a failed one, on every reconnect cycle.
55const ATTEMPT: Duration = Duration::from_secs(5);
56
57/// The wait before the first probe of the preferred transport, before jitter.
58///
59/// Each failed probe doubles it, up to [`PROBE_MAX`]. A brief outage thus ends within
60/// seconds to minutes of the preferred transport returning, while a target that never
61/// reaches it pays for one handshake attempt every five minutes.
62const PROBE_INITIAL: Duration = Duration::from_secs(10);
63
64/// The longest wait between probes of the preferred transport, before jitter.
65const PROBE_MAX: Duration = Duration::from_secs(300);
66
67/// When to redial after a failure, and when to give up, once a session has been established.
68///
69/// A session is established once the peer accepts the connection credential or drains the
70/// session with a GOAWAY, or, on a version with no answer to the credential (moq-lite
71/// 03/04), once it stays up past `healthy`. Before then nothing retries: a failed walk, or a session closed sooner, ends the policy.
72///
73/// `initial` and `multiplier` set the wait before each retry, `max` caps it, and
74/// `healthy` decides which sessions count as failed attempts. The delays carry jitter,
75/// so a fleet knocked offline together does not reconnect in lockstep. `timeout` bounds
76/// every failure; a settled rejection, malformed protocol input, or invalid local
77/// configuration stops retrying. A GOAWAY naming no new URI is no failure: a restarting
78/// peer sends one to each session until it goes, and each of those serves, so it
79/// restarts the timeout instead.
80///
81/// A GOAWAY off a healthy session migrates at once, unless the run of redirects, among
82/// sessions that each lived less than `max`, has looped back through an endpoint. The loop
83/// check keeps one endpoint, so it catches a cycle within a few laps rather than at the
84/// first revisit: A to B, B to C, C to B is followed once before it is caught. Peers
85/// redirecting in a loop then wait out this backoff and count against the timeout.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87#[non_exhaustive]
88pub struct Backoff {
89	/// Delay before the first redial. Later delays grow from it, so zero turns retry
90	/// waiting off entirely; an immediate close still counts as a failed attempt and
91	/// spends the timeout. Defaults to 1 s.
92	pub initial: Duration,
93	/// Growth of the delay after each failure. 0 or 1 keeps it constant. Defaults to 2.
94	pub multiplier: u32,
95	/// Cap on the delay, which caps `initial` too. `None` leaves it uncapped. Defaults to 5 s.
96	pub max: Option<Duration>,
97	/// How long a session must stay up to count as healthy. Must be nonzero. Defaults to 1 s.
98	///
99	/// Where the peer never answers the connection credential, as on moq-lite 03/04, the first
100	/// healthy session establishes the policy, so failures retry from then on. Elsewhere only
101	/// the peer's answer or a GOAWAY establishes it, however long a session stays up.
102	/// A healthy session's end resets the delay and the timeout. One that ends sooner is a
103	/// failed attempt, so a peer that accepts and then drops every session still escalates
104	/// the delay and exhausts the timeout.
105	pub healthy: Duration,
106	/// How long to keep retrying before giving up. `None` (the default) retries forever, so
107	/// an outage of any length recovers on its own; a caller that can react to a persistent
108	/// failure sets one. Zero gives up at the first failure.
109	///
110	/// No new walk of the peer's addresses starts once it has passed, but one under way
111	/// finishes: each address but the last gets up to 5 s, and the last runs to
112	/// [`Config::timeout`], so a handshake slower than this still lands. Giving up can
113	/// therefore take up to one whole walk longer. Resets after a healthy session outside a
114	/// redirect loop.
115	pub timeout: Option<Duration>,
116}
117
118impl Default for Backoff {
119	fn default() -> Self {
120		Self {
121			initial: Duration::from_secs(1),
122			multiplier: 2,
123			max: Some(Duration::from_secs(5)),
124			healthy: Duration::from_secs(1),
125			timeout: None,
126		}
127	}
128}
129
130/// How a connection hands over to a new session after a peer's GOAWAY.
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132#[non_exhaustive]
133pub struct Handover {
134	/// What to do with the URI the GOAWAY names. Defaults to [`Redirect::SameHost`].
135	pub redirect: Redirect,
136	/// The longest the old session keeps serving after a GOAWAY. Defaults to 10 s.
137	///
138	/// It closes sooner, once its replacement is up and it carries no subscription or
139	/// fetch. A GOAWAY naming a shorter deadline wins, since the peer force-closes at its
140	/// own deadline regardless, but a longer one does not extend it.
141	pub handover: Duration,
142}
143
144impl Default for Handover {
145	fn default() -> Self {
146		Self {
147			redirect: Redirect::default(),
148			handover: Duration::from_secs(10),
149		}
150	}
151}
152
153impl Handover {
154	/// The handover window for a GOAWAY naming `deadline`: whichever is sooner.
155	fn handover(&self, deadline: Option<Duration>) -> Duration {
156		deadline.map_or(self.handover, |deadline| deadline.min(self.handover))
157	}
158}
159
160/// What to do when a peer's GOAWAY names no URI, meaning it is restarting where we reached it.
161#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
162#[non_exhaustive]
163pub enum Restart {
164	/// Redial the same addresses at once while the drained session keeps serving. Right for
165	/// an address that can lead to another node, such as a fleet name a fresh resolve moves
166	/// off the drained one. The default.
167	#[default]
168	Redial,
169	/// Redial the same addresses once, as [`Self::Redial`] does, and keep serving on the
170	/// drained session meanwhile. A redial that reaches the draining process again, which
171	/// drains it before it is [healthy](Backoff::healthy), then keeps serving until the peer
172	/// closes it, and the connection reconnects as after any drop.
173	///
174	/// Right for an address that names one node which may start its replacement beside the
175	/// draining process, as a relay with `[handoff]` does: the one redial reaches the
176	/// replacement. A node that restarts in place costs a single extra session to the
177	/// draining process rather than one per backoff. The peer must close the session
178	/// itself, as a relay does at its drain deadline.
179	Handoff,
180}
181
182/// The whole connect policy for one peer.
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184#[non_exhaustive]
185pub struct Config {
186	/// When to redial, and when to give up.
187	pub backoff: Backoff,
188	/// How to follow a peer's GOAWAY.
189	pub goaway: Handover,
190	/// What a GOAWAY naming no URI does.
191	pub restart: Restart,
192	/// The deadline for one dial and its handshake, through the peer's answer to the credential
193	/// on a version that has one. `None` waits forever. Defaults to 30 s.
194	pub timeout: Option<Duration>,
195	/// End when the first session ends instead of redialing. Defaults to false.
196	///
197	/// A GOAWAY then ends it cleanly: with no replacement to dial, leaving is the answer.
198	pub once: bool,
199	/// Whether the dial pins a certificate fingerprint, which verifies only the host it
200	/// was configured for, so a GOAWAY may not move an encrypted dial to another host.
201	pub pinned: bool,
202}
203
204impl Default for Config {
205	fn default() -> Self {
206		Self {
207			backoff: Backoff::default(),
208			goaway: Handover::default(),
209			restart: Restart::default(),
210			timeout: Some(Duration::from_secs(30)),
211			once: false,
212			pinned: false,
213		}
214	}
215}
216
217/// One of a peer's addresses, as the caller dials it.
218pub trait Target: Clone + From<Url> {
219	/// The URL a dial reaches, which a GOAWAY redirect is judged against.
220	fn url(&self) -> &Url;
221
222	/// Whether the dial skips resolving the URL for fixed socket addresses, which a
223	/// GOAWAY redirect cannot carry over.
224	fn fixed(&self) -> bool;
225}
226
227impl Target for Url {
228	fn url(&self) -> &Url {
229		self
230	}
231
232	fn fixed(&self) -> bool {
233		false
234	}
235}
236
237/// What a failed dial means for the address walk, judged by the caller from the address
238/// and the peer's answer rather than the error's kind.
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240#[non_exhaustive]
241pub enum Verdict {
242	/// This address failed; try the next, then back off and retry.
243	Retry,
244	/// This address can never work, such as an unsupported scheme. Give up unless
245	/// another address fails transiently.
246	Unusable,
247	/// The peer's answer for every address, such as an HTTP 404: stop the walk, then
248	/// back off and retry.
249	Settled,
250}
251
252/// A failure the policy itself decides on.
253#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
254#[non_exhaustive]
255pub enum Failure {
256	/// An address with another to fall back on did not connect in time.
257	#[error("timed out connecting to {0}")]
258	Attempt(String),
259	/// A dial and its handshake outlasted [`Config::timeout`].
260	#[error("connect timed out after {0:?}")]
261	Timeout(Duration),
262	/// The retry window ran out; carries the last failure's message.
263	#[error("reconnect timed out after {after:?}{}", last.as_ref().map(|last| format!(": {last}")).unwrap_or_default())]
264	Exhausted {
265		/// The retry window.
266		after: Duration,
267		/// Why the last attempt failed, if one did.
268		last: Option<String>,
269	},
270	/// Peers redirected the connection around in a loop.
271	#[error("redirect loop")]
272	Loop,
273	/// The peer redirected a session elsewhere before it was healthy.
274	#[error("peer redirected immediately")]
275	Redirected,
276	/// The redirect a GOAWAY named breaks the [`Redirect`] policy; carries why.
277	#[error("refused GOAWAY redirect: {0}")]
278	Refused(&'static str),
279	/// A GOAWAY named a redirect for a target dialing fixed socket addresses.
280	#[error("a GOAWAY redirected a target dialing fixed socket addresses")]
281	Fixed,
282	/// A [`Dial`] was dropped without an answer.
283	#[error("a dial was dropped unanswered")]
284	Unanswered,
285	/// The [`Dials`] given to [`Reconnect::with_dials`] already serve another policy.
286	#[error("these dials already serve another connection")]
287	Taken,
288}
289
290/// Invalid input to [`Reconnect::new`].
291#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
292#[non_exhaustive]
293pub enum ConfigError {
294	/// There is no address to dial.
295	#[error("no target to dial")]
296	Empty,
297	/// [`Backoff::healthy`] is zero, which would count every session as healthy and reset
298	/// the timeout forever under a peer that drops each one on sight.
299	#[error("the healthy threshold must be nonzero")]
300	Healthy,
301}
302
303/// One dial the caller runs for [`Reconnect`].
304#[derive(Clone)]
305pub struct Attempt<A> {
306	target: A,
307	/// The connection credential, from [`Reconnect::with_tokens`].
308	token: Option<String>,
309	auth: Option<auth::Handle>,
310}
311
312impl<A: std::fmt::Debug> std::fmt::Debug for Attempt<A> {
313	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314		// The credential stays out of logs.
315		f.debug_struct("Attempt")
316			.field("target", &self.target)
317			.field("token", &self.token.as_ref().map(|token| token.len()))
318			.finish_non_exhaustive()
319	}
320}
321
322impl<A: Target> Attempt<A> {
323	/// The address to dial.
324	pub fn target(&self) -> &A {
325		&self.target
326	}
327
328	/// `client` set up for this dial: the target's URL, the connection credential in SETUP
329	/// and, when one of `client`'s versions cannot carry it there, the URL's query, and the
330	/// session built on the tokens' handle.
331	pub fn client(&self, client: &crate::Client) -> crate::Client {
332		let mut client = client.clone();
333		let mut url = self.target.url().clone();
334		if let Some(token) = &self.token {
335			url = auth::locate(&url, token, &client.versions);
336			client = client.with_token(crate::setup::Token {
337				kind: crate::setup::Token::OUT_OF_BAND,
338				value: token.clone().into_bytes(),
339			});
340		}
341		if let Some(auth) = &self.auth {
342			client = client.with_auth(auth.clone());
343		}
344		client.with_url(url)
345	}
346}
347
348/// What [`Reconnect::poll`] asks of the caller.
349///
350/// Exhaustive on purpose: a new action is one every driver must handle.
351#[derive(Debug)]
352pub enum Action<A, E> {
353	/// Dial this attempt and report it with [`Reconnect::connected`] or
354	/// [`Reconnect::failed`], polling meanwhile. Build each session's client with
355	/// [`Attempt::client`].
356	Dial(Attempt<A>),
357	/// The live session is established: its peer accepted the connection credential or
358	/// drained it with a GOAWAY, or, on a version with no answer (moq-lite 03/04), it stayed
359	/// up past [`Backoff::healthy`]. Until then a
360	/// connected session may still be a refusal, so report it as serving only from here.
361	/// Carries the session, which a GOAWAY may already have moved to the predecessor.
362	Established(Box<Session>),
363	/// Drop the dial or probe in flight: it ran out its deadline, which already counted as
364	/// its failure, or the predecessor's peer redirected while it headed for that peer.
365	Abandon,
366	/// The [`predecessor`](Reconnect::predecessor) serves while a replacement is dialed: the
367	/// live session got a GOAWAY and now drains as it, or the replacement closed while it
368	/// still drains.
369	Migrating,
370	/// The predecessor closed or overstayed its handover.
371	Retired,
372	/// Nothing serves anymore: the live session ended with this error, or the predecessor
373	/// retired between sessions. A redial follows.
374	Offline(Option<E>),
375	/// Why the policy is waiting to redial: a walk failed, or a session ended.
376	Retrying(E),
377	/// Poll again by this instant, or on a wake.
378	Wait(Option<Instant>),
379	/// The live session runs on a fallback, set by [`Reconnect::fallback`]. Reach this
380	/// attempt's peer over the preferred transport alone, without the MoQ handshake, and
381	/// report it with [`Reconnect::probed`]. Drop it if the live session ends first: on
382	/// [`Action::Migrating`], [`Action::Offline`], or [`Action::Done`].
383	Probe(Attempt<A>),
384	/// The policy gave up with an error, or ended cleanly. Every later poll waits forever.
385	Done(Result<(), E>),
386}
387
388/// Client connect policy as a poll machine; see the [module](self) docs.
389///
390/// `A` is the caller's address type and `E` its error type, which takes the
391/// [`Error`] a session closes with and the [`Failure`]s the policy decides on.
392pub struct Reconnect<A, E> {
393	config: Config,
394	targets: Vec<A>,
395	// The addresses the caller configured, which a failed walk to a redirect returns to.
396	// None until a GOAWAY redirect replaces `targets`.
397	configured: Option<Vec<A>>,
398	tokens: Option<auth::Tokens>,
399	/// Where each dial asks for its tokens, from [`Reconnect::with_dials`].
400	dials: Option<Dials<E>>,
401	/// Why the last attempt or session ended since one was last established, which the next
402	/// [`Dial`] reports.
403	failure: Option<E>,
404	retry: Retry<E>,
405	redirects: Redirects,
406	phase: Phase<E>,
407	/// The failures of the walk under way.
408	walk: Walk<E>,
409	/// Whether any session was established: [`Action::Established`] was reported for it. Until
410	/// then, a failed walk or a closed session ends the policy.
411	established: bool,
412	/// An old session kept serving after a GOAWAY so its in-flight groups finish.
413	predecessor: Option<Predecessor>,
414	queue: VecDeque<Action<A, E>>,
415}
416
417enum Phase<E> {
418	/// Walk the targets, unless the tokens ended.
419	Start,
420	/// Ask the caller to dial the target at `index`.
421	Next {
422		index: usize,
423	},
424	/// Waiting for the [`Dial`] answer for the target at `index`, under the dial's deadline.
425	Signing {
426		index: usize,
427		deadline: Option<(Instant, Failure)>,
428		pending: dials::Pending<E>,
429	},
430	Dialing(Dialing),
431	Live(Box<Live<E>>),
432	Backoff {
433		until: Instant,
434		/// After a restart's wait, the retry window counts from its end.
435		restart: bool,
436	},
437	/// The policy ended; every later poll waits forever.
438	Done,
439}
440
441struct Dialing {
442	index: usize,
443	deadline: Option<(Instant, Failure)>,
444	presented: Option<auth::Dial>,
445}
446
447struct Live<E> {
448	session: Session,
449	since: Instant,
450	index: usize,
451	/// Whether [`Action::Established`] was reported for this session.
452	established: bool,
453	/// The dial's deadline, which still runs until a peer that answers the credential does.
454	deadline: Option<(Instant, Failure)>,
455	/// Dropped once a restart is waited out: it is a latch, so it would keep firing.
456	goaway: Option<goaway::Consumer>,
457	/// Set while the session runs on a fallback transport.
458	probe: Option<Probe<E>>,
459}
460
461/// Probing the preferred transport while the live session runs on a fallback.
462struct Probe<E> {
463	/// The wait before the next probe, before jitter.
464	delay: Duration,
465	state: Probing<E>,
466}
467
468enum Probing<E> {
469	/// The next probe is due at this instant.
470	Due(Instant),
471	/// Waiting for the [`Dial`] answer for the probe, abandoned at its deadline.
472	Signing {
473		deadline: Option<Instant>,
474		pending: dials::Pending<E>,
475	},
476	/// A probe is in flight, abandoned at its deadline.
477	Dialing {
478		deadline: Option<Instant>,
479		presented: Option<auth::Dial>,
480	},
481}
482
483/// What a [`Probe`] asks for at an instant.
484enum ProbePoll {
485	Wait(Option<Instant>),
486	Due,
487	/// The probe in flight ran out its deadline and was scored as a failure.
488	Abandon,
489	/// The probe waits for its [`Dial`] answer until this deadline.
490	Signing(Option<Instant>),
491}
492
493impl<E> Probe<E> {
494	fn new(now: Instant) -> Self {
495		Self {
496			delay: PROBE_INITIAL,
497			state: Probing::Due(now.saturating_add(jitter(PROBE_INITIAL))),
498		}
499	}
500
501	fn poll(&mut self, now: Instant) -> ProbePoll {
502		match &self.state {
503			Probing::Due(at) if now >= *at => ProbePoll::Due,
504			Probing::Due(at) => ProbePoll::Wait(Some(*at)),
505			Probing::Dialing { deadline: Some(at), .. } if now >= *at => {
506				tracing::debug!("probe of the preferred transport timed out");
507				self.failed(now);
508				ProbePoll::Abandon
509			}
510			Probing::Dialing { deadline, .. } => ProbePoll::Wait(*deadline),
511			Probing::Signing { deadline: Some(at), .. } if now >= *at => {
512				tracing::debug!("a probe's dial went unanswered past its deadline");
513				self.failed(now);
514				self.poll(now)
515			}
516			// Polled by the policy, which holds what answers it.
517			Probing::Signing { deadline, .. } => ProbePoll::Signing(*deadline),
518		}
519	}
520
521	/// Schedule the next probe after a failed one, doubling the wait up to the cap.
522	fn failed(&mut self, now: Instant) {
523		self.delay = self.delay.saturating_mul(2).min(PROBE_MAX);
524		self.state = Probing::Due(now.saturating_add(jitter(self.delay)));
525	}
526}
527
528struct Walk<E> {
529	/// The latest failure a retry may repair.
530	transient: Option<E>,
531	/// The latest failure of any kind.
532	last: Option<E>,
533}
534
535impl<E> Default for Walk<E> {
536	fn default() -> Self {
537		Self {
538			transient: None,
539			last: None,
540		}
541	}
542}
543
544/// Why a live session stopped being the live one.
545enum Ended {
546	Closed(Error),
547	/// The peer sent a GOAWAY; the session is still up and serving.
548	Goaway(goaway::Goaway),
549}
550
551impl<A: Target, E: Clone + std::fmt::Display + From<Error> + From<Failure>> Reconnect<A, E> {
552	/// Walk `targets` in order under `config`, starting at `now`.
553	pub fn new(config: Config, targets: Vec<A>, now: Instant) -> Result<Self, ConfigError> {
554		if targets.is_empty() {
555			return Err(ConfigError::Empty);
556		}
557		if config.backoff.healthy.is_zero() {
558			return Err(ConfigError::Healthy);
559		}
560		Ok(Self {
561			retry: Retry::new(Pacing::new(&config.backoff).initial, now),
562			config,
563			targets,
564			configured: None,
565			tokens: None,
566			dials: None,
567			failure: None,
568			redirects: Redirects::default(),
569			phase: Phase::Start,
570			walk: Walk::default(),
571			established: false,
572			predecessor: None,
573			queue: VecDeque::new(),
574		})
575	}
576
577	/// Present `tokens` on every dial, through [`Attempt::client`].
578	///
579	/// An ended tokens handle ends the policy at its next walk.
580	pub fn with_tokens(mut self, tokens: auth::Tokens) -> Self {
581		self.tokens = Some(tokens);
582		self
583	}
584
585	/// Ask `dials` for the tokens of every dial, as it starts, instead of presenting fixed ones;
586	/// see [`Dials`]. Each answer replaces the tokens from [`with_tokens`](Self::with_tokens), or
587	/// from a handle of their own without one.
588	///
589	/// They serve one policy: given dials another policy took, even one that ended since, this
590	/// one ends at once with [`Failure::Taken`], leaving them to the other.
591	pub fn with_dials(mut self, dials: Dials<E>) -> Self {
592		self.tokens.get_or_insert_with(|| auth::Tokens::new(Vec::new()));
593		// Dials replaced here end as a policy's would, so their answerer stops.
594		if let Some(replaced) = self.dials.take() {
595			replaced.close();
596		}
597		match dials.claim() {
598			true => self.dials = Some(dials),
599			false => self.done(Err(Failure::Taken.into())),
600		}
601		self
602	}
603
604	/// The live session, if one is serving and has not received a GOAWAY.
605	pub fn session(&self) -> Option<&Session> {
606		match &self.phase {
607			Phase::Live(live) => Some(&live.session),
608			_ => None,
609		}
610	}
611
612	/// The addresses the next walk dials, in order: the configured ones, or the one a
613	/// GOAWAY redirected to.
614	pub fn targets(&self) -> &[A] {
615		&self.targets
616	}
617
618	/// The session draining after a GOAWAY, and the deadline its handover ends by.
619	pub fn predecessor(&self) -> Option<(&Session, Instant)> {
620		self.predecessor
621			.as_ref()
622			.map(|predecessor| (&predecessor.session, predecessor.deadline))
623	}
624
625	/// Advance to `now`, returning what the caller must do next.
626	pub fn poll(&mut self, now: Instant, waiter: &kio::Waiter) -> Action<A, E> {
627		loop {
628			if let Some(action) = self.queue.pop_front() {
629				return action;
630			}
631
632			let live = matches!(self.phase, Phase::Live(_));
633			// A replacement serves only once established: until then it may be a refusal.
634			let serving = matches!(&self.phase, Phase::Live(live) if live.established);
635			if let Some(predecessor) = self.predecessor.as_mut() {
636				// The replacement serves, so a predecessor carrying nothing closes now.
637				if serving {
638					predecessor.poll_idle(waiter);
639				}
640				if predecessor.poll(now, waiter) {
641					self.predecessor = None;
642					self.queue.push_back(Action::Retired);
643					// Nothing is serving once it retires between sessions, so a caller must
644					// stop handing out a session that is already closed.
645					if !serving {
646						self.queue.push_back(Action::Offline(None));
647					}
648					continue;
649				}
650			}
651			// Until a replacement serves, a redirect the predecessor's peer sends decides where
652			// the next dial goes.
653			if !live && let Some(action) = self.follow(waiter) {
654				return action;
655			}
656			let handover = self.predecessor.as_ref().map(|predecessor| predecessor.deadline);
657
658			match &mut self.phase {
659				Phase::Start => self.start(),
660				Phase::Next { index } => {
661					let index = *index;
662					match self.dial(now, index) {
663						Some(action) => return action,
664						None => continue,
665					}
666				}
667				Phase::Signing { deadline, pending, .. } => {
668					if let Some((at, failure)) = deadline
669						&& now >= *at
670					{
671						// Nothing is in flight for the caller, so there is nothing to abandon.
672						let failure = failure.clone();
673						self.fail(now, failure.into(), Verdict::Retry);
674						continue;
675					}
676					let at = deadline.as_ref().map(|(at, _)| *at);
677					match poll_answer(pending, waiter) {
678						Poll::Pending => return Action::Wait(earliest(at, handover)),
679						Poll::Ready(Ok(tokens)) => return self.signed(tokens),
680						Poll::Ready(Err(err)) => {
681							self.done(Err(err));
682							continue;
683						}
684					}
685				}
686				Phase::Dialing(dialing) => match &dialing.deadline {
687					Some((at, failure)) if now >= *at => {
688						let failure = failure.clone();
689						self.fail(now, failure.into(), Verdict::Retry);
690						return Action::Abandon;
691					}
692					deadline => return Action::Wait(earliest(deadline.as_ref().map(|(at, _)| *at), handover)),
693				},
694				Phase::Live(live) => {
695					// Checked before the close, which may follow the peer's acceptance in one wake:
696					// a session the peer accepted and then dropped is an outage, not a refusal.
697					// Uptime stands in for an answer only on a version that has none: a peer that
698					// can answer and has not may still refuse.
699					let healthy = live
700						.session
701						.is_silent()
702						.then(|| live.since.saturating_add(self.config.backoff.healthy));
703					let uptime = healthy.is_some_and(|healthy| now >= healthy);
704					if !live.established && (uptime || live.session.poll_accepted(waiter).is_ready()) {
705						live.established = true;
706						self.established = true;
707						self.failure = None;
708						return Action::Established(Box::new(live.session.clone()));
709					}
710					let mut ended = None;
711					// Checked before the close: a GOAWAY means the session is still up, and
712					// migrating from it is not the same as reconnecting after it died.
713					if let Some(Poll::Ready(Ok(msg))) = live.goaway.as_ref().map(|goaway| goaway.poll(waiter)) {
714						// A GOAWAY establishes the policy however soon it comes: the peer accepted
715						// the session and asked us to move, which a refusal never does. So a
716						// client started while its relay drains rides out the restart, whether it
717						// redials now or serves until the peer closes the session.
718						self.established = true;
719						if !std::mem::replace(&mut live.established, true) {
720							self.failure = None;
721							self.queue
722								.push_back(Action::Established(Box::new(live.session.clone())));
723						}
724						// Under `Handoff`, a session drained before it was healthy is a redial that
725						// reached the draining process rather than a replacement, so another would
726						// only reach it again.
727						let wait = match self.config.restart {
728							Restart::Redial => false,
729							Restart::Handoff => now.saturating_duration_since(live.since) < self.config.backoff.healthy,
730						};
731						// A one-shot policy ends on any GOAWAY instead, as `once` promises.
732						if wait && !self.config.once && msg.uri().is_empty() {
733							tracing::info!("peer is restarting; serving until it closes the session");
734							live.goaway = None;
735						} else {
736							ended = Some(Ended::Goaway(msg));
737						}
738					}
739					if ended.is_none()
740						&& let Poll::Ready(err) = live.session.poll_closed(waiter)
741					{
742						ended = Some(Ended::Closed(err));
743					}
744					if let Some(ended) = ended {
745						self.end(now, ended);
746						continue;
747					}
748					if !self.queue.is_empty() {
749						continue;
750					}
751					// A peer that answers the credential and has not yet spends the dial's deadline,
752					// so a handshake that stalls before the peer's SETUP fails like any other. Checked
753					// after the GOAWAY and the close, which settle the session first. A silent session
754					// is established by uptime instead.
755					let deadline = live
756						.deadline
757						.as_ref()
758						.filter(|_| !live.established && healthy.is_none());
759					if let Some((at, failure)) = deadline
760						&& now >= *at
761					{
762						let failure = failure.clone();
763						let index = live.index;
764						// Released now rather than when the driver runs the abort, so the next
765						// address's session can attach to the same auth handle.
766						live.session.link().close(Error::Timeout);
767						live.session.abort(Error::Timeout);
768						self.phase = Phase::Start;
769						self.attempt_failed(now, index, failure.into(), Verdict::Retry);
770						continue;
771					}
772					let deadline = deadline.map(|(at, _)| *at);
773					// An unestablished session is established by uptime or times out at the latest.
774					let handover = match live.established {
775						true => handover,
776						false => earliest(earliest(healthy, deadline), handover),
777					};
778					// Only an established session is left for the preferred transport: one that may
779					// still be a refusal is no session to hand over.
780					let probe = live.probe.as_mut().filter(|_| live.established);
781					match probe.map(|probe| probe.poll(now)) {
782						None => return Action::Wait(handover),
783						Some(ProbePoll::Wait(at)) => return Action::Wait(earliest(at, handover)),
784						Some(ProbePoll::Abandon) => return Action::Abandon,
785						Some(ProbePoll::Due) => match self.probe(now) {
786							Some(action) => return action,
787							None => continue,
788						},
789						Some(ProbePoll::Signing(at)) => match self.probe_signed(now, waiter) {
790							Poll::Pending => return Action::Wait(earliest(at, handover)),
791							Poll::Ready(Some(action)) => return action,
792							Poll::Ready(None) => continue,
793						},
794					}
795				}
796				Phase::Backoff { until, restart } => {
797					if now < *until {
798						return Action::Wait(earliest(Some(*until), handover));
799					}
800					if *restart {
801						// After the wait, so the window counts only the time after the peer
802						// stops answering.
803						self.retry.start = now;
804					} else if let Some(window) = self.config.backoff.timeout
805						&& now.saturating_duration_since(self.retry.start) >= window
806					{
807						// Checked when the wait ends, not when it began, so a late poll (a
808						// stalled runtime, a sleeping device) never dials past the window.
809						self.done(Err(self.exhausted(window)));
810						continue;
811					}
812					self.retry.delay = Pacing::new(&self.config.backoff).next(self.retry.delay);
813					self.phase = Phase::Start;
814				}
815				Phase::Done => return Action::Wait(None),
816			}
817		}
818	}
819
820	/// Report that the dial asked for connected `session`, at `now`.
821	///
822	/// Ignored unless a dial is in flight, as after [`Action::Abandon`].
823	pub fn connected(&mut self, now: Instant, session: Session) {
824		if !matches!(self.phase, Phase::Dialing(_)) {
825			return;
826		}
827		let Phase::Dialing(dialing) = std::mem::replace(&mut self.phase, Phase::Start) else {
828			unreachable!("checked above");
829		};
830		if let Some(tokens) = &self.tokens {
831			tokens.connected(&session);
832		}
833		self.walk = Walk::default();
834		self.phase = Phase::Live(Box::new(Live {
835			goaway: Some(session.draining()),
836			session,
837			since: now,
838			index: dialing.index,
839			established: false,
840			deadline: dialing.deadline,
841			probe: None,
842		}));
843	}
844
845	/// Report that the live session runs on a fallback transport, at `now`.
846	///
847	/// The policy then asks for [`Action::Probe`] dials of the preferred transport, the
848	/// first 5 to 10 s from now and the rest on a doubling backoff capped at one every 5
849	/// minutes, until one connects. Ignored unless a session is live, or when connecting once.
850	pub fn fallback(&mut self, now: Instant) {
851		if self.config.once {
852			return;
853		}
854		if let Phase::Live(live) = &mut self.phase {
855			live.probe = Some(Probe::new(now));
856		}
857	}
858
859	/// Report whether the probe asked for reached the preferred transport, at `now`.
860	///
861	/// On `Ok`, the fallback session sends its own GOAWAY and drains as the
862	/// [`predecessor`](Self::predecessor), queuing [`Action::Migrating`], and the probe becomes
863	/// the dial in flight: finish the MoQ handshake over the transport it reached and report it
864	/// with [`connected`](Self::connected) or [`failed`](Self::failed). The fallback drains
865	/// first because the tokens back one session at a time, and keeps serving until the
866	/// replacement does. Returns whether the probe became that dial: one reported with none in
867	/// flight, as after [`Action::Abandon`], is ignored, and one reported once the peer's GOAWAY
868	/// arrived yields to it.
869	pub fn probed(&mut self, now: Instant, result: Result<(), E>) -> bool {
870		let Phase::Live(live) = &mut self.phase else {
871			return false;
872		};
873		let Some(probe) = live.probe.as_mut() else {
874			return false;
875		};
876		let Probing::Dialing { presented, .. } = &mut probe.state else {
877			return false;
878		};
879		if let Err(err) = result {
880			tracing::debug!(%err, "preferred transport still unreachable");
881			probe.failed(now);
882			return false;
883		}
884		// The peer's GOAWAY wins over a probe that got through with it, so its redirect is
885		// never lost: the next poll acts on it.
886		if let Some(Poll::Ready(_)) = live.goaway.as_ref().map(|goaway| goaway.poll(&kio::Waiter::noop())) {
887			probe.failed(now);
888			return false;
889		}
890		let presented = presented.take();
891		let index = live.index;
892		tracing::info!(peer = %Shown(self.targets[index].url()), "preferred transport reachable; leaving the fallback");
893
894		let connect = self.config.timeout;
895		let Phase::Live(old) = std::mem::replace(
896			&mut self.phase,
897			Phase::Dialing(Dialing {
898				index,
899				deadline: connect.map(|connect| (now.saturating_add(connect), Failure::Timeout(connect))),
900				presented,
901			}),
902		) else {
903			unreachable!("matched above");
904		};
905		// A GOAWAY naming no URI: the peer learns we are moving, and the session stops
906		// taking new work, which frees the tokens for its replacement.
907		if old.session.goaway(goaway::Goaway::new()).is_err() {
908			tracing::debug!("the fallback session was already draining");
909		}
910		// The fallback session served all along, so a long one still earns the healthy reset.
911		// Only an established session is probed, so the policy already is.
912		self.retry.settle(
913			now,
914			now.saturating_duration_since(old.since),
915			&Pacing::new(&self.config.backoff),
916		);
917		if let Some(older) = self.predecessor.take() {
918			older.retire();
919		}
920		// Its peer may still redirect us while it drains, which `follow` acts on. A fixed
921		// target never moves, so it needs no watch.
922		let redirect = old
923			.goaway
924			.filter(|_| !self.targets[index].fixed())
925			.map(|goaway| Redirected {
926				goaway,
927				url: self.targets[index].url().clone(),
928			});
929		self.predecessor = Some(Predecessor {
930			deadline: now.saturating_add(self.config.goaway.handover),
931			session: old.session,
932			closing: false,
933			redirect,
934		});
935		// Only now, once the fallback stops taking new work: a probe that never gets through
936		// leaves the serving session's tokens and their grants alone.
937		let Phase::Dialing(dialing) = &self.phase else {
938			unreachable!("set above");
939		};
940		self.commit(dialing.presented.as_ref());
941		self.queue.push_back(Action::Migrating);
942		true
943	}
944
945	/// Report that the dial asked for failed with `err`, judged as `verdict`.
946	///
947	/// Ignored unless a dial is in flight, as after [`Action::Abandon`].
948	pub fn failed(&mut self, now: Instant, err: E, verdict: Verdict) {
949		if matches!(self.phase, Phase::Dialing(_)) {
950			self.fail(now, err, verdict);
951		}
952	}
953
954	/// Start a walk, unless the tokens ended. Only a retry's backoff checks the window, so
955	/// the first dial of a run, a healthy migration, and a restart's redial always happen,
956	/// even under a zero window.
957	fn start(&mut self) {
958		// An ended auth handle refuses every later session, so no dial can recover. A fresh
959		// watch only reports an error once its handle has ended.
960		if let Some(tokens) = &self.tokens
961			&& let Poll::Ready(Err(err)) = tokens.handle().grant().poll_changed(&kio::Waiter::noop())
962		{
963			return self.done(Err(err.into()));
964		}
965		self.phase = Phase::Next { index: 0 };
966	}
967
968	/// The attempt dialing the target at `index`, and the tokens it presents, read without
969	/// touching the live session's tokens.
970	fn attempt(&self, index: usize) -> (Attempt<A>, Option<auth::Dial>) {
971		let target = self.targets[index].clone();
972		let presented = self.tokens.as_ref().map(|tokens| tokens.preview(target.url()));
973		let token = presented.as_ref().and_then(|presented| presented.token.clone());
974		let auth = self.tokens.as_ref().map(auth::Tokens::handle);
975		(Attempt { target, token, auth }, presented)
976	}
977
978	/// Make `presented` the tokens' latest dial. Called before the dial's session driver
979	/// starts, so a request the session sends early waits on the held tokens' answers rather
980	/// than being refused outside the connection credential's grant.
981	fn commit(&self, presented: Option<&auth::Dial>) {
982		if let (Some(tokens), Some(presented)) = (&self.tokens, presented) {
983			tokens.commit(presented);
984		}
985	}
986
987	/// Ask for a probe of the live session's target over the preferred transport, or for its
988	/// [`Dial`] answer first, returning `None` while that is pending.
989	fn probe(&mut self, now: Instant) -> Option<Action<A, E>> {
990		let Phase::Live(live) = &self.phase else {
991			unreachable!("only a live session probes");
992		};
993		let index = live.index;
994		let deadline = self.config.timeout.map(|timeout| now.saturating_add(timeout));
995		if let Some(dials) = &self.dials {
996			// The serving session is fine, so the probe reports no failure.
997			let pending = dials.request(self.targets[index].url().clone(), None);
998			self.set_probe(Probing::Signing { deadline, pending });
999			return None;
1000		}
1001		let (attempt, presented) = self.attempt(index);
1002		Some(self.probing(attempt, presented, deadline))
1003	}
1004
1005	/// The probe's [`Dial`] answer: the probe with its signed tokens, `None` once it was skipped
1006	/// for a failed dial, or pending.
1007	fn probe_signed(&mut self, now: Instant, waiter: &kio::Waiter) -> Poll<Option<Action<A, E>>> {
1008		let Phase::Live(live) = &self.phase else {
1009			unreachable!("only a live session probes");
1010		};
1011		let index = live.index;
1012		let Some(Probe {
1013			state: Probing::Signing { deadline, pending },
1014			..
1015		}) = &live.probe
1016		else {
1017			unreachable!("polled while signing");
1018		};
1019		let deadline = *deadline;
1020		let answer = std::task::ready!(poll_answer(pending, waiter));
1021		match answer {
1022			Ok(tokens) => {
1023				let target = self.targets[index].clone();
1024				let presented = auth::Tokens::preview_signed(target.url(), tokens);
1025				let attempt = Attempt {
1026					token: presented.token.clone(),
1027					auth: self.tokens.as_ref().map(auth::Tokens::handle),
1028					target,
1029				};
1030				Poll::Ready(Some(self.probing(attempt, Some(presented), deadline)))
1031			}
1032			Err(err) => {
1033				tracing::warn!(%err, "a probe's dial failed; skipping it");
1034				if let Phase::Live(live) = &mut self.phase
1035					&& let Some(probe) = live.probe.as_mut()
1036				{
1037					probe.failed(now);
1038				}
1039				Poll::Ready(None)
1040			}
1041		}
1042	}
1043
1044	/// Start `attempt` as the probe in flight, which `presented` presents once it gets through.
1045	fn probing(
1046		&mut self,
1047		attempt: Attempt<A>,
1048		presented: Option<auth::Dial>,
1049		deadline: Option<Instant>,
1050	) -> Action<A, E> {
1051		tracing::debug!(peer = %Shown(attempt.target.url()), "probing the preferred transport");
1052		self.set_probe(Probing::Dialing { deadline, presented });
1053		Action::Probe(attempt)
1054	}
1055
1056	fn set_probe(&mut self, state: Probing<E>) {
1057		if let Phase::Live(live) = &mut self.phase
1058			&& let Some(probe) = live.probe.as_mut()
1059		{
1060			probe.state = state;
1061		}
1062	}
1063
1064	/// Ask the caller to dial the target at `index`, or, with [`Dials`], to answer its dial
1065	/// first, returning `None` while that is pending.
1066	fn dial(&mut self, now: Instant, index: usize) -> Option<Action<A, E>> {
1067		let url = self.targets[index].url();
1068		// The connect deadline covers the dial and the handshake, for every transport: it is
1069		// the only bound some of them have. The fixed bound applies only with a fallback.
1070		// It starts before a dial's answer, so a caller slow to sign spends it too.
1071		let connect = self.config.timeout;
1072		let attempt = (index + 1 < self.targets.len()).then_some(ATTEMPT);
1073		let deadline = match (attempt, connect) {
1074			(Some(attempt), Some(connect)) if connect <= attempt => {
1075				Some((now.saturating_add(connect), Failure::Timeout(connect)))
1076			}
1077			(Some(attempt), _) => Some((now.saturating_add(attempt), Failure::Attempt(Shown(url).to_string()))),
1078			(None, Some(connect)) => Some((now.saturating_add(connect), Failure::Timeout(connect))),
1079			(None, None) => None,
1080		};
1081
1082		if let Some(dials) = &self.dials {
1083			let pending = dials.request(url.clone(), self.failure.clone());
1084			self.phase = Phase::Signing {
1085				index,
1086				deadline,
1087				pending,
1088			};
1089			return None;
1090		}
1091
1092		let (dial, presented) = self.attempt(index);
1093		Some(self.dialing(dial, presented, index, deadline))
1094	}
1095
1096	/// The dial being signed has its answer: present `tokens` on it.
1097	fn signed(&mut self, tokens: Vec<auth::Token>) -> Action<A, E> {
1098		let Phase::Signing { index, deadline, .. } = std::mem::replace(&mut self.phase, Phase::Start) else {
1099			unreachable!("checked by the caller");
1100		};
1101		let target = self.targets[index].clone();
1102		let presented = auth::Tokens::preview_signed(target.url(), tokens);
1103		let dial = Attempt {
1104			token: presented.token.clone(),
1105			auth: self.tokens.as_ref().map(auth::Tokens::handle),
1106			target,
1107		};
1108		self.dialing(dial, Some(presented), index, deadline)
1109	}
1110
1111	/// Hand the caller `dial`, presenting `presented`, as the dial in flight.
1112	fn dialing(
1113		&mut self,
1114		dial: Attempt<A>,
1115		presented: Option<auth::Dial>,
1116		index: usize,
1117		deadline: Option<(Instant, Failure)>,
1118	) -> Action<A, E> {
1119		self.commit(presented.as_ref());
1120		tracing::info!(peer = %Shown(dial.target.url()), "connecting");
1121		self.phase = Phase::Dialing(Dialing {
1122			index,
1123			deadline,
1124			presented,
1125		});
1126		Action::Dial(dial)
1127	}
1128
1129	/// The dial in flight failed: move on to the next target, or end the walk.
1130	fn fail(&mut self, now: Instant, err: E, verdict: Verdict) {
1131		let index = match std::mem::replace(&mut self.phase, Phase::Start) {
1132			Phase::Dialing(dialing) => dialing.index,
1133			Phase::Signing { index, .. } => index,
1134			_ => unreachable!("checked by the caller"),
1135		};
1136		self.attempt_failed(now, index, err, verdict);
1137	}
1138
1139	/// The attempt at the target at `index` failed: move on to the next target, or end the walk.
1140	fn attempt_failed(&mut self, now: Instant, index: usize, err: E, verdict: Verdict) {
1141		self.failure = Some(err.clone());
1142		match verdict {
1143			// The peer's answer, not this address's, so unless it invites another attempt it
1144			// settles the whole walk. Carrying on would offer the same rejected credentials at
1145			// the peer's other addresses, and a later transport failure would overwrite the
1146			// real reason.
1147			Verdict::Settled => return self.walk_failed(now, err, verdict),
1148			Verdict::Retry => self.walk.transient = Some(err.clone()),
1149			Verdict::Unusable => {}
1150		}
1151		tracing::debug!(peer = %Shown(self.targets[index].url()), %err, "address unreachable");
1152		self.walk.last = Some(err);
1153
1154		if index + 1 < self.targets.len() {
1155			self.phase = Phase::Next { index: index + 1 };
1156			return;
1157		}
1158
1159		// One unusable target must not turn another target's transient failure terminal.
1160		let walk = std::mem::take(&mut self.walk);
1161		match walk.transient {
1162			Some(err) => self.walk_failed(now, err, Verdict::Retry),
1163			None => self.walk_failed(now, walk.last.expect("a failed walk"), Verdict::Unusable),
1164		}
1165	}
1166
1167	fn walk_failed(&mut self, now: Instant, err: E, verdict: Verdict) {
1168		self.walk = Walk::default();
1169		// Otherwise a walk fails fast until a session was established: a peer that never
1170		// accepted one is more likely misconfigured (an unknown host, an untrusted certificate,
1171		// no version in common) than restarting, and only the caller can fix that.
1172		// After that, every failure retries, whatever its kind.
1173		if verdict == Verdict::Unusable || self.config.once || !self.established {
1174			return self.done(Err(err));
1175		}
1176		self.queue.push_back(Action::Retrying(err.clone()));
1177		self.retry.last = Some(err);
1178		// A redirect target that no longer answers is dropped: the next walk dials the
1179		// configured addresses, which may still answer.
1180		if let Some(configured) = self.configured.take() {
1181			self.targets = configured;
1182		}
1183		// No URL here: with several targets there isn't one to name, and each attempt
1184		// already logged the address it tried.
1185		self.back_off(now, self.config.backoff.timeout, false, "reconnecting after backoff");
1186	}
1187
1188	/// Act on a GOAWAY the predecessor's peer sent after a probe moved us off it, the way
1189	/// [`end`](Self::end) would have: an accepted redirect becomes the only target, and a dial
1190	/// still headed for the leaving peer is dropped. Anything else leaves the targets alone,
1191	/// since the policy is already leaving that session.
1192	fn follow(&mut self, waiter: &kio::Waiter) -> Option<Action<A, E>> {
1193		let predecessor = self.predecessor.as_mut()?;
1194		let redirect = predecessor.redirect.as_ref()?;
1195		let Poll::Ready(msg) = redirect.goaway.poll(waiter) else {
1196			return None;
1197		};
1198		// No need to establish the policy here: only an established session is probed.
1199		let redirect = predecessor.redirect.take()?;
1200		let target = match msg.map(|msg| {
1201			self.config
1202				.goaway
1203				.redirect
1204				.target(msg.uri(), &redirect.url, self.config.pinned)
1205		}) {
1206			Ok(Ok(Some(target))) => target,
1207			// A closed session, a restart in place, or a refused redirect: nothing to follow.
1208			_ => return None,
1209		};
1210		tracing::info!(peer = %Shown(&target), "draining fallback peer redirected; following");
1211		// No loop scoring here: only a probe that got through leads here, and the probe's
1212		// backoff paces those. The session this dial lands on is scored when it ends.
1213		let redirected = std::mem::replace(&mut self.targets, vec![A::from(target)]);
1214		self.configured.get_or_insert(redirected);
1215		// A walk of the replaced targets gives way to one of the new target.
1216		if matches!(
1217			self.phase,
1218			Phase::Dialing(_) | Phase::Signing { .. } | Phase::Next { .. }
1219		) {
1220			self.walk = Walk::default();
1221		}
1222		match self.phase {
1223			Phase::Dialing(_) => {
1224				self.phase = Phase::Start;
1225				Some(Action::Abandon)
1226			}
1227			// An index into the replaced targets; a dial being signed for one is dropped unseen.
1228			Phase::Next { .. } | Phase::Signing { .. } => {
1229				self.phase = Phase::Start;
1230				None
1231			}
1232			// A backoff still paces the next dial, which now goes to the new target.
1233			_ => None,
1234		}
1235	}
1236
1237	/// Score how a live session ended and decide what follows.
1238	fn end(&mut self, now: Instant, ended: Ended) {
1239		let Phase::Live(live) = std::mem::replace(&mut self.phase, Phase::Start) else {
1240			unreachable!("only a live session ends");
1241		};
1242		let tenure = now.saturating_duration_since(live.since);
1243		let url = self.targets[live.index].url().clone();
1244		let pacing = Pacing::new(&self.config.backoff);
1245		// The connected target owns the policy, including when connecting once. A refused
1246		// redirect is terminal: the peer is leaving and named somewhere we won't go, so
1247		// redialing the old address or a fallback would ignore it.
1248		let assigned = match &ended {
1249			Ended::Goaway(msg) => match self.config.goaway.redirect.target(msg.uri(), &url, self.config.pinned) {
1250				Ok(assigned) => assigned,
1251				Err(failure) => return self.done(Err(failure.into())),
1252			},
1253			Ended::Closed(_) => None,
1254		};
1255		if assigned.is_some() && self.targets[live.index].fixed() {
1256			return self.done(Err(Failure::Fixed.into()));
1257		}
1258
1259		// Connecting once leaves rather than migrating: there is no replacement to dial, and
1260		// a GOAWAY naming no deadline never force-closes, so the peer stops accepting
1261		// requests and waits for us. Ignoring it is how both sides end up waiting on each
1262		// other forever.
1263		if self.config.once && matches!(ended, Ended::Goaway(_)) {
1264			return self.done(Ok(()));
1265		}
1266
1267		// Two peers that each hold a session past the healthy bar can still bounce us between
1268		// them forever. Returning to an endpoint that already sent us elsewhere in this run of
1269		// migrations skips the healthy-session reset, so the backoff escalates and the retry
1270		// window still applies. A one-way rolling restart never revisits one, and a GOAWAY
1271		// back to the same place is a restart, not a move, so it never counts. A session that
1272		// outlived the capped delay already redials no faster than the backoff would allow, so
1273		// it starts a new run: rolling restarts days apart never add up to a loop.
1274		if matches!(ended, Ended::Closed(_)) || tenure >= pacing.settled() {
1275			self.redirects.reset();
1276		}
1277		// Only an accepted redirect is a move: an empty or ignored one reconnects in place.
1278		let looped = assigned.as_ref().is_some_and(|target| {
1279			let from = endpoint(&url);
1280			let to = endpoint(target);
1281			to != from && self.redirects.depart(from, &to)
1282		});
1283
1284		// A session that stayed up past the healthy bar is healthy; one that ended sooner, or
1285		// carried on a redirect loop, counts as a failed attempt.
1286		let healthy = !looped && self.retry.settle(now, tenure, &pacing);
1287
1288		let msg = match ended {
1289			Ended::Goaway(msg) => msg,
1290			Ended::Closed(err) => return self.closed(now, err, healthy, &url),
1291		};
1292
1293		// An accepted redirect is an assignment: keep dialing it from here on, and only it,
1294		// until a walk to it fails and `walk_failed` restores the configured addresses. The
1295		// peer named exactly one place to go, which retires whatever other addresses got us
1296		// to this session.
1297		let url = match assigned {
1298			Some(target) => {
1299				let redirected = std::mem::replace(&mut self.targets, vec![A::from(target.clone())]);
1300				self.configured.get_or_insert(redirected);
1301				target
1302			}
1303			None => url,
1304		};
1305
1306		// Hand over gracefully however the backoff scores this session. The old one keeps
1307		// serving until it closes or overstays, so its routes stay attached and live tracks
1308		// splice onto the replacement at a group boundary. Only on lite-07: lite-05/06 carry no
1309		// instance, so a front stays pinned to the drained session and its tracks end with it.
1310		tracing::info!(peer = %Shown(&url), "upstream GOAWAY; migrating");
1311		if let Some(old) = self.predecessor.take() {
1312			old.retire();
1313		}
1314		self.predecessor = Some(Predecessor {
1315			deadline: now.saturating_add(self.config.goaway.handover(msg.timeout())),
1316			session: live.session,
1317			closing: false,
1318			// Its GOAWAY was just acted on.
1319			redirect: None,
1320		});
1321		self.queue.push_back(Action::Migrating);
1322
1323		// No backoff: a handover off a healthy session is not a failure.
1324		if healthy {
1325			return;
1326		}
1327
1328		// Drained almost immediately, or looped back. The backoff still escalates, so the
1329		// redials cannot hammer the peer, and the old session serves across the wait.
1330		//
1331		// An empty URI is "reconnect to me": the peer is restarting and drains each new
1332		// session until it goes, which is no failure, since every one serves. A named URI is
1333		// a redirect, scored as a failed attempt so two peers bouncing us between them
1334		// eventually give up.
1335		let restarting = msg.uri().is_empty();
1336		if !restarting {
1337			let err: E = if looped { Failure::Loop } else { Failure::Redirected }.into();
1338			self.failure = Some(err.clone());
1339			self.queue.push_back(Action::Retrying(err.clone()));
1340			self.retry.last = Some(err);
1341		}
1342		// A restart's pacing is not capped by the window: a delay longer than the window
1343		// would otherwise spend it all and end the loop without a redial.
1344		let window = if restarting { None } else { self.config.backoff.timeout };
1345		let reason = if looped {
1346			"peer redirected back in a loop; retrying after backoff"
1347		} else {
1348			"peer drained the session immediately; retrying after backoff"
1349		};
1350		self.back_off(now, window, restarting, reason);
1351	}
1352
1353	/// The live session closed with `err`.
1354	fn closed(&mut self, now: Instant, err: Error, healthy: bool, url: &Url) {
1355		let err = E::from(err);
1356		self.failure = Some(err.clone());
1357		// Connecting once, the session ending ends the policy with its close reason.
1358		if self.config.once {
1359			return self.done(Err(err));
1360		}
1361		// Until a session was established, a close ends the policy as a failed walk does. It
1362		// is how a peer refuses a session that is already live, such as a rejected credential
1363		// on moq-lite 03 or later, closed before the peer's SETUP or AUTH_OK; redialing would
1364		// offer the same credential forever. No error kind is read, and as for a refused dial,
1365		// tokens replaced since change nothing.
1366		if !self.established {
1367			return self.done(Err(err));
1368		}
1369
1370		// A predecessor still draining serves again, so this is no outage: the caller moves
1371		// back onto it. One closing gracefully already carries nothing and takes no new work.
1372		if self
1373			.predecessor
1374			.as_ref()
1375			.is_some_and(|predecessor| !predecessor.closing)
1376		{
1377			self.queue.push_back(Action::Migrating);
1378			self.queue.push_back(Action::Retrying(err.clone()));
1379		} else {
1380			self.queue.push_back(Action::Offline(Some(err.clone())));
1381		}
1382		if healthy {
1383			// The window was reset, so a one-off drop reconnects promptly.
1384			tracing::warn!(peer = %Shown(url), "session closed, reconnecting");
1385		} else {
1386			// Connected then dropped almost immediately, such as a server that accepts then
1387			// resets. Keep the reason so the give-up reports a real cause, and back off so
1388			// repeated flaps escalate instead of spinning.
1389			tracing::warn!(peer = %Shown(url), %err, "session severed immediately, retrying");
1390			self.retry.last = Some(err);
1391		}
1392		self.back_off(now, self.config.backoff.timeout, false, "reconnecting after backoff");
1393	}
1394
1395	/// Wait out the next jittered delay, capped by what remains of `window`, if any.
1396	fn back_off(&mut self, now: Instant, window: Option<Duration>, restart: bool, reason: &'static str) {
1397		let wait = self.retry.wait();
1398		let wait = match window {
1399			None => wait,
1400			Some(window) => match window.checked_sub(now.saturating_duration_since(self.retry.start)) {
1401				Some(left) => wait.min(left),
1402				None => return self.done(Err(self.exhausted(window))),
1403			},
1404		};
1405		tracing::warn!(?wait, "{reason}");
1406		self.phase = Phase::Backoff {
1407			until: now.saturating_add(wait),
1408			restart,
1409		};
1410	}
1411
1412	/// Giving up once the retry `window` ran out.
1413	fn exhausted(&self, window: Duration) -> E {
1414		Failure::Exhausted {
1415			after: window,
1416			last: self.retry.last.as_ref().map(ToString::to_string),
1417		}
1418		.into()
1419	}
1420
1421	fn done(&mut self, result: Result<(), E>) {
1422		if let Some(dials) = &self.dials {
1423			dials.close();
1424		}
1425		self.predecessor = None;
1426		self.phase = Phase::Done;
1427		self.queue.push_back(Action::Done(result));
1428	}
1429}
1430
1431impl<A, E> Drop for Reconnect<A, E> {
1432	fn drop(&mut self) {
1433		// Whoever answers the dials stops once nothing will ask again.
1434		if let Some(dials) = &self.dials {
1435			dials.close();
1436		}
1437	}
1438}
1439
1440/// The tokens a [`Dial`] was answered with, or the error ending the policy: the caller's, or
1441/// [`Failure::Unanswered`] for a dial dropped unanswered.
1442fn poll_answer<E: Clone + From<Failure>>(
1443	pending: &dials::Pending<E>,
1444	waiter: &kio::Waiter,
1445) -> Poll<Result<Vec<auth::Token>, E>> {
1446	let taken = pending.poll(waiter, |answer| match answer.is_some() {
1447		true => Poll::Ready(()),
1448		false => Poll::Pending,
1449	});
1450	match taken {
1451		Poll::Pending => Poll::Pending,
1452		Poll::Ready(Err(_)) => Poll::Ready(Err(Failure::Unanswered.into())),
1453		Poll::Ready(Ok(())) => {
1454			// Read once: the dial that answered is gone, and the policy drops this right after.
1455			let answer = pending.read();
1456			Poll::Ready(match answer.as_ref() {
1457				Some(dials::Answer::Present(tokens)) => Ok(tokens.clone()),
1458				Some(dials::Answer::Fail(err)) => Err(err.clone()),
1459				None => Err(Failure::Unanswered.into()),
1460			})
1461		}
1462	}
1463}
1464
1465/// Between half of `delay` and all of it, so a fleet knocked offline together spreads out.
1466fn jitter(delay: Duration) -> Duration {
1467	delay.mul_f64(0.5 + kio::clock::rng().random::<f64>() / 2.0)
1468}
1469
1470fn earliest(a: Option<Instant>, b: Option<Instant>) -> Option<Instant> {
1471	match (a, b) {
1472		(Some(a), Some(b)) => Some(a.min(b)),
1473		(a, b) => a.or(b),
1474	}
1475}
1476
1477/// The retry pacing resolved from [`Backoff`].
1478struct Pacing {
1479	/// The first delay, already under the cap.
1480	initial: Duration,
1481	/// The delay cap, or `None` for uncapped.
1482	max: Option<Duration>,
1483	/// At least 1: a multiplier of zero means no growth, not a delay that shrinks to nothing.
1484	multiplier: u32,
1485	/// The bar a session must clear to count as healthy.
1486	healthy: Duration,
1487}
1488
1489impl Pacing {
1490	fn new(backoff: &Backoff) -> Self {
1491		let max = backoff.max;
1492		Self {
1493			initial: max.map_or(backoff.initial, |max| backoff.initial.min(max)),
1494			max,
1495			multiplier: backoff.multiplier.max(1),
1496			healthy: backoff.healthy,
1497		}
1498	}
1499
1500	/// The delay for the attempt after one that waited `delay`.
1501	fn next(&self, delay: Duration) -> Duration {
1502		let next = delay.saturating_mul(self.multiplier);
1503		self.max.map_or(next, |max| next.min(max))
1504	}
1505
1506	/// How long a session must last to start a new run of redirects.
1507	///
1508	/// One that outlived the capped delay already redials no faster than the backoff would
1509	/// allow. Uncapped, the healthy bar is the only rate the config names.
1510	fn settled(&self) -> Duration {
1511		self.max.unwrap_or(self.healthy)
1512	}
1513}
1514
1515/// The backoff window across a run of failed attempts.
1516struct Retry<E> {
1517	/// The wait before the next attempt, before jitter.
1518	delay: Duration,
1519	/// When this run of failures began; the give-up timeout counts from here.
1520	start: Instant,
1521	/// The latest failure, so giving up reports a real cause.
1522	last: Option<E>,
1523}
1524
1525impl<E> Retry<E> {
1526	fn new(initial: Duration, now: Instant) -> Self {
1527		Self {
1528			delay: initial,
1529			start: now,
1530			last: None,
1531		}
1532	}
1533
1534	/// Score how long a session served: past the healthy bar starts a fresh retry window.
1535	fn settle(&mut self, now: Instant, tenure: Duration, pacing: &Pacing) -> bool {
1536		let healthy = tenure >= pacing.healthy;
1537		if healthy {
1538			*self = Self::new(pacing.initial, now);
1539		}
1540		healthy
1541	}
1542
1543	/// The next delay, jittered.
1544	fn wait(&self) -> Duration {
1545		jitter(self.delay)
1546	}
1547}
1548
1549/// An old session kept serving after a GOAWAY so its in-flight groups finish.
1550struct Predecessor {
1551	session: Session,
1552	/// When its handover ends.
1553	deadline: Instant,
1554	/// Whether [`Self::poll_idle`] started the graceful close.
1555	closing: bool,
1556	/// Watches for a redirect from the peer, set when a probe moved us off this session.
1557	redirect: Option<Redirected>,
1558}
1559
1560/// A drained fallback session's GOAWAY, and the URL a redirect in it is judged against.
1561struct Redirected {
1562	goaway: goaway::Consumer,
1563	url: Url,
1564}
1565
1566impl Predecessor {
1567	/// Close the old session now, whatever remains of its window.
1568	fn retire(self) {
1569		self.session.abort(Error::GoawayTimeout);
1570	}
1571
1572	/// Close the old session gracefully once it carries no subscription or fetch.
1573	///
1574	/// Only while a replacement serves: until then everything new still lands here. The
1575	/// handover window still bounds the close.
1576	fn poll_idle(&mut self, waiter: &kio::Waiter) {
1577		if self.closing || self.session.poll_idle(waiter).is_pending() {
1578			return;
1579		}
1580		tracing::debug!("old session carries nothing after GOAWAY; closing");
1581		self.closing = true;
1582		self.session.start_close();
1583	}
1584
1585	/// Poll the drain; `true` once it is over.
1586	fn poll(&mut self, now: Instant, waiter: &kio::Waiter) -> bool {
1587		if self.session.poll_closed(waiter).is_ready() {
1588			tracing::debug!("old session drained cleanly after GOAWAY");
1589			return true;
1590		}
1591		if now >= self.deadline {
1592			tracing::warn!("old session did not drain in time; closing");
1593			self.session.abort(Error::GoawayTimeout);
1594			return true;
1595		}
1596		false
1597	}
1598}