Skip to main content

moq_net/reconnect/
dials.rs

1//! Tokens a [`Reconnect`](super::Reconnect) asks the caller for at each dial.
2
3use std::{collections::VecDeque, task::Poll};
4
5use url::Url;
6
7use crate::auth::Token;
8
9/// How the caller answered one [`Dial`].
10pub(super) enum Answer<E> {
11	Present(Vec<Token>),
12	Fail(E),
13}
14
15/// What the policy holds of a dial it asked for: dropping it abandons the dial.
16pub(super) type Pending<E> = kio::Consumer<Option<Answer<E>>>;
17
18struct Queue<E> {
19	waiting: VecDeque<Dial<E>>,
20	/// Whether a policy took the queue: one feeds it.
21	claimed: bool,
22	closed: bool,
23}
24
25/// Tokens a reconnecting connection asks for at each dial, for a credential that must be fresh
26/// when it is presented, such as a proof a peer admits once and only shortly after it was signed.
27///
28/// Attach one with [`Reconnect::with_dials`](super::Reconnect::with_dials) and answer each
29/// [`next`](Self::next) dial: every dial waits for its answer, whatever starts it, a reconnect, a
30/// GOAWAY's handover, a probe of the preferred transport, or the next address of a walk, so none
31/// presents tokens signed for another. The wait counts against the dial's own deadline.
32///
33/// Until a session is established, the policy fails fast as with fixed tokens. After that,
34/// answering is how it retries: it backs off and asks again, with the reason on
35/// [`Dial::failure`], until a dial is [failed](Dial::fail). To retry a first connect that
36/// failed, attach a fresh queue (with a fresh signer) to a new policy: the failed one keeps
37/// this queue claimed.
38///
39/// Cheap to clone; every clone shares one queue, which one policy feeds: once that policy ends,
40/// [`next`](Self::next) returns `None`, and a policy given the queue after another took it ends
41/// at once with [`Failure::Taken`](super::Failure::Taken).
42pub struct Dials<E> {
43	queue: kio::Producer<Queue<E>>,
44}
45
46impl<E> Clone for Dials<E> {
47	fn clone(&self) -> Self {
48		Self {
49			queue: self.queue.clone(),
50		}
51	}
52}
53
54impl<E> Default for Dials<E> {
55	fn default() -> Self {
56		Self::new()
57	}
58}
59
60impl<E> Dials<E> {
61	/// An empty queue, which dials join once a policy is attached.
62	pub fn new() -> Self {
63		Self {
64			queue: kio::Producer::new(Queue {
65				waiting: VecDeque::new(),
66				claimed: false,
67				closed: false,
68			}),
69		}
70	}
71
72	/// The next dial waiting for its tokens, or `None` once the policy ended. A dial the policy
73	/// abandoned meanwhile, past its deadline, is skipped.
74	#[cfg_attr(feature = "async", kio::wrapper)]
75	pub fn poll_next(&self, waiter: &kio::Waiter) -> Poll<Option<Dial<E>>> {
76		let ready = |queue: &Queue<E>| match queue.closed || queue.waiting.iter().any(Dial::wanted) {
77			true => Poll::Ready(()),
78			false => Poll::Pending,
79		};
80		loop {
81			let mut queue = match self.queue.poll(waiter, |queue| ready(queue)) {
82				Poll::Ready(Ok(queue)) => queue,
83				Poll::Ready(Err(_)) => return Poll::Ready(None),
84				Poll::Pending => return Poll::Pending,
85			};
86			while let Some(dial) = queue.waiting.pop_front() {
87				if dial.wanted() {
88					return Poll::Ready(Some(dial));
89				}
90			}
91			if queue.closed {
92				return Poll::Ready(None);
93			}
94			// Every dial seen wanted was abandoned since: wait again rather than report an end.
95		}
96	}
97
98	/// Ask for the tokens of a dial to `url`, after `failure`. Once closed, the dial goes
99	/// unanswered at once, which ends the policy.
100	pub(super) fn request(&self, url: Url, failure: Option<E>) -> Pending<E> {
101		let answer = kio::Producer::new(None);
102		let pending = answer.consume();
103		if let Ok(mut queue) = self.queue.write()
104			&& !queue.closed
105		{
106			queue.waiting.retain(Dial::wanted);
107			queue.waiting.push_back(Dial { url, failure, answer });
108		}
109		pending
110	}
111
112	/// Take the queue for one policy: `false` once another took it.
113	pub(super) fn claim(&self) -> bool {
114		let Ok(mut queue) = self.queue.write() else {
115			return false;
116		};
117		!std::mem::replace(&mut queue.claimed, true)
118	}
119
120	/// End [`next`](Self::next), dropping every dial still waiting.
121	pub(super) fn close(&self) {
122		if let Ok(mut queue) = self.queue.write() {
123			queue.closed = true;
124			queue.waiting.clear();
125		}
126	}
127}
128
129/// One dial of a reconnecting connection, waiting for the tokens it presents.
130///
131/// Dropping it unanswered fails it, as [`fail`](Self::fail) would.
132#[must_use = "an unanswered dial ends the policy"]
133pub struct Dial<E> {
134	url: Url,
135	failure: Option<E>,
136	answer: kio::Producer<Option<Answer<E>>>,
137}
138
139impl<E> Dial<E> {
140	/// Where the dial goes: one of the configured addresses, or where a GOAWAY redirected it.
141	pub fn url(&self) -> &Url {
142		&self.url
143	}
144
145	/// Why the previous attempt or session ended, such as a refused credential or a redirect
146	/// before the session was healthy, or `None` when nothing failed since a session was last
147	/// established, as for the first dial or a healthy session's GOAWAY handover. Mirrors the
148	/// connection's own record of why it is retrying.
149	pub fn failure(&self) -> Option<&E> {
150		self.failure.as_ref()
151	}
152
153	/// Present `tokens` on this dial, as [`Reconnect::with_tokens`](super::Reconnect::with_tokens)
154	/// would: the first is the connection credential, and the rest ride AUTH on its session.
155	///
156	/// Only the credential is this dial's alone. The rest join the connection's shared set,
157	/// which a successor attaches to before its own answer replaces them, so a single-use
158	/// token belongs first.
159	pub fn present(self, tokens: Vec<Token>) {
160		self.answer(Answer::Present(tokens));
161	}
162
163	/// End the policy with `err` instead of dialing, as for a [`failure`](Self::failure) no retry
164	/// can repair. A probe of the preferred transport, which the serving session does without, is
165	/// skipped instead.
166	pub fn fail(self, err: E) {
167		self.answer(Answer::Fail(err));
168	}
169
170	fn answer(self, answer: Answer<E>) {
171		if let Ok(mut slot) = self.answer.write() {
172			*slot = Some(answer);
173		}
174	}
175
176	/// Whether the policy still waits for this dial's answer.
177	fn wanted(&self) -> bool {
178		self.answer.wanted()
179	}
180}
181
182impl<E> std::fmt::Debug for Dial<E> {
183	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184		// The URL may carry a credential, which a log never shows.
185		f.debug_struct("Dial")
186			.field("url", &format_args!("{}", super::redirect::Shown(&self.url)))
187			.finish_non_exhaustive()
188	}
189}