1mod 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
49const ATTEMPT: Duration = Duration::from_secs(5);
56
57const PROBE_INITIAL: Duration = Duration::from_secs(10);
63
64const PROBE_MAX: Duration = Duration::from_secs(300);
66
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87#[non_exhaustive]
88pub struct Backoff {
89 pub initial: Duration,
93 pub multiplier: u32,
95 pub max: Option<Duration>,
97 pub healthy: Duration,
106 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132#[non_exhaustive]
133pub struct Handover {
134 pub redirect: Redirect,
136 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 fn handover(&self, deadline: Option<Duration>) -> Duration {
156 deadline.map_or(self.handover, |deadline| deadline.min(self.handover))
157 }
158}
159
160#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
162#[non_exhaustive]
163pub enum Restart {
164 #[default]
168 Redial,
169 Handoff,
180}
181
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184#[non_exhaustive]
185pub struct Config {
186 pub backoff: Backoff,
188 pub goaway: Handover,
190 pub restart: Restart,
192 pub timeout: Option<Duration>,
195 pub once: bool,
199 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
217pub trait Target: Clone + From<Url> {
219 fn url(&self) -> &Url;
221
222 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240#[non_exhaustive]
241pub enum Verdict {
242 Retry,
244 Unusable,
247 Settled,
250}
251
252#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
254#[non_exhaustive]
255pub enum Failure {
256 #[error("timed out connecting to {0}")]
258 Attempt(String),
259 #[error("connect timed out after {0:?}")]
261 Timeout(Duration),
262 #[error("reconnect timed out after {after:?}{}", last.as_ref().map(|last| format!(": {last}")).unwrap_or_default())]
264 Exhausted {
265 after: Duration,
267 last: Option<String>,
269 },
270 #[error("redirect loop")]
272 Loop,
273 #[error("peer redirected immediately")]
275 Redirected,
276 #[error("refused GOAWAY redirect: {0}")]
278 Refused(&'static str),
279 #[error("a GOAWAY redirected a target dialing fixed socket addresses")]
281 Fixed,
282 #[error("a dial was dropped unanswered")]
284 Unanswered,
285 #[error("these dials already serve another connection")]
287 Taken,
288}
289
290#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
292#[non_exhaustive]
293pub enum ConfigError {
294 #[error("no target to dial")]
296 Empty,
297 #[error("the healthy threshold must be nonzero")]
300 Healthy,
301}
302
303#[derive(Clone)]
305pub struct Attempt<A> {
306 target: A,
307 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 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 pub fn target(&self) -> &A {
325 &self.target
326 }
327
328 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#[derive(Debug)]
352pub enum Action<A, E> {
353 Dial(Attempt<A>),
357 Established(Box<Session>),
363 Abandon,
366 Migrating,
370 Retired,
372 Offline(Option<E>),
375 Retrying(E),
377 Wait(Option<Instant>),
379 Probe(Attempt<A>),
384 Done(Result<(), E>),
386}
387
388pub struct Reconnect<A, E> {
393 config: Config,
394 targets: Vec<A>,
395 configured: Option<Vec<A>>,
398 tokens: Option<auth::Tokens>,
399 dials: Option<Dials<E>>,
401 failure: Option<E>,
404 retry: Retry<E>,
405 redirects: Redirects,
406 phase: Phase<E>,
407 walk: Walk<E>,
409 established: bool,
412 predecessor: Option<Predecessor>,
414 queue: VecDeque<Action<A, E>>,
415}
416
417enum Phase<E> {
418 Start,
420 Next {
422 index: usize,
423 },
424 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 restart: bool,
436 },
437 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 established: bool,
453 deadline: Option<(Instant, Failure)>,
455 goaway: Option<goaway::Consumer>,
457 probe: Option<Probe<E>>,
459}
460
461struct Probe<E> {
463 delay: Duration,
465 state: Probing<E>,
466}
467
468enum Probing<E> {
469 Due(Instant),
471 Signing {
473 deadline: Option<Instant>,
474 pending: dials::Pending<E>,
475 },
476 Dialing {
478 deadline: Option<Instant>,
479 presented: Option<auth::Dial>,
480 },
481}
482
483enum ProbePoll {
485 Wait(Option<Instant>),
486 Due,
487 Abandon,
489 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 Probing::Signing { deadline, .. } => ProbePoll::Signing(*deadline),
518 }
519 }
520
521 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 transient: Option<E>,
531 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
544enum Ended {
546 Closed(Error),
547 Goaway(goaway::Goaway),
549}
550
551impl<A: Target, E: Clone + std::fmt::Display + From<Error> + From<Failure>> Reconnect<A, E> {
552 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 pub fn with_tokens(mut self, tokens: auth::Tokens) -> Self {
581 self.tokens = Some(tokens);
582 self
583 }
584
585 pub fn with_dials(mut self, dials: Dials<E>) -> Self {
592 self.tokens.get_or_insert_with(|| auth::Tokens::new(Vec::new()));
593 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 pub fn session(&self) -> Option<&Session> {
606 match &self.phase {
607 Phase::Live(live) => Some(&live.session),
608 _ => None,
609 }
610 }
611
612 pub fn targets(&self) -> &[A] {
615 &self.targets
616 }
617
618 pub fn predecessor(&self) -> Option<(&Session, Instant)> {
620 self.predecessor
621 .as_ref()
622 .map(|predecessor| (&predecessor.session, predecessor.deadline))
623 }
624
625 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 let serving = matches!(&self.phase, Phase::Live(live) if live.established);
635 if let Some(predecessor) = self.predecessor.as_mut() {
636 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 if !serving {
646 self.queue.push_back(Action::Offline(None));
647 }
648 continue;
649 }
650 }
651 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 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 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 if let Some(Poll::Ready(Ok(msg))) = live.goaway.as_ref().map(|goaway| goaway.poll(waiter)) {
714 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 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 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 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 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 let handover = match live.established {
775 true => handover,
776 false => earliest(earliest(healthy, deadline), handover),
777 };
778 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 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 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 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 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 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 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 if old.session.goaway(goaway::Goaway::new()).is_err() {
908 tracing::debug!("the fallback session was already draining");
909 }
910 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 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 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 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 fn start(&mut self) {
958 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 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 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 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 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 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 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 fn dial(&mut self, now: Instant, index: usize) -> Option<Action<A, E>> {
1067 let url = self.targets[index].url();
1068 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 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 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 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 fn attempt_failed(&mut self, now: Instant, index: usize, err: E, verdict: Verdict) {
1141 self.failure = Some(err.clone());
1142 match verdict {
1143 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 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 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 if let Some(configured) = self.configured.take() {
1181 self.targets = configured;
1182 }
1183 self.back_off(now, self.config.backoff.timeout, false, "reconnecting after backoff");
1186 }
1187
1188 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 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 _ => return None,
1209 };
1210 tracing::info!(peer = %Shown(&target), "draining fallback peer redirected; following");
1211 let redirected = std::mem::replace(&mut self.targets, vec![A::from(target)]);
1214 self.configured.get_or_insert(redirected);
1215 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 Phase::Next { .. } | Phase::Signing { .. } => {
1229 self.phase = Phase::Start;
1230 None
1231 }
1232 _ => None,
1234 }
1235 }
1236
1237 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 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 if self.config.once && matches!(ended, Ended::Goaway(_)) {
1264 return self.done(Ok(()));
1265 }
1266
1267 if matches!(ended, Ended::Closed(_)) || tenure >= pacing.settled() {
1275 self.redirects.reset();
1276 }
1277 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 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 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 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 redirect: None,
1320 });
1321 self.queue.push_back(Action::Migrating);
1322
1323 if healthy {
1325 return;
1326 }
1327
1328 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 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 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 if self.config.once {
1359 return self.done(Err(err));
1360 }
1361 if !self.established {
1367 return self.done(Err(err));
1368 }
1369
1370 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 tracing::warn!(peer = %Shown(url), "session closed, reconnecting");
1385 } else {
1386 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 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 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 if let Some(dials) = &self.dials {
1435 dials.close();
1436 }
1437 }
1438}
1439
1440fn 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 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
1465fn 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
1477struct Pacing {
1479 initial: Duration,
1481 max: Option<Duration>,
1483 multiplier: u32,
1485 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 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 fn settled(&self) -> Duration {
1511 self.max.unwrap_or(self.healthy)
1512 }
1513}
1514
1515struct Retry<E> {
1517 delay: Duration,
1519 start: Instant,
1521 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 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 fn wait(&self) -> Duration {
1545 jitter(self.delay)
1546 }
1547}
1548
1549struct Predecessor {
1551 session: Session,
1552 deadline: Instant,
1554 closing: bool,
1556 redirect: Option<Redirected>,
1558}
1559
1560struct Redirected {
1562 goaway: goaway::Consumer,
1563 url: Url,
1564}
1565
1566impl Predecessor {
1567 fn retire(self) {
1569 self.session.abort(Error::GoawayTimeout);
1570 }
1571
1572 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 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}