Skip to main content

moq_net/
client.rs

1use std::task::{Poll, ready};
2
3use crate::driver::Transport;
4use crate::origin;
5use crate::time::{Deadlines, Instant};
6use crate::transport::poll::Session as _;
7use crate::{
8	ALPN_18, ALPN_20, ALPN_22, ALPN_23, ALPN_LITE, ALPN_LITE_03, ALPN_LITE_04, ALPN_LITE_05, ALPN_LITE_06,
9	ALPN_LITE_07_WIP, Consume, Error, NEGOTIATED, Session, Version, Versions,
10	coding::{self, Encode, Stream},
11	ietf, lite, setup, stats,
12};
13
14/// A MoQ client session builder.
15#[derive(Default, Clone)]
16pub struct Client {
17	publish: Option<origin::Consumer>,
18	subscribe: Option<origin::Producer>,
19	stats: stats::Session,
20	pub(crate) versions: Versions,
21	url: Option<url::Url>,
22	setup_token: Option<setup::Token>,
23	cost: Option<u64>,
24	peer_node: Option<std::num::NonZeroU64>,
25	limits: crate::session::Limits,
26	extensions: setup::Extensions,
27	auth: Option<crate::auth::Handle>,
28	allocator: Option<crate::bandwidth::Allocator>,
29	viewers: Option<crate::bandwidth::Viewers>,
30	implementation: Option<String>,
31	keep_alive: Option<crate::transport::KeepAlive>,
32}
33
34impl Client {
35	/// A client that neither publishes nor subscribes until configured.
36	pub fn new() -> Self {
37		Default::default()
38	}
39
40	/// Publish local broadcasts to the remote: the session reads from the given
41	/// origin (pass an [`origin::Producer`] or [`origin::Consumer`] by reference) and
42	/// forwards its announcements. Omit to publish nothing.
43	pub fn with_publisher(mut self, publish: impl Consume<origin::Consumer>) -> Self {
44		self.publish = Some(publish.consume());
45		self
46	}
47
48	/// Subscribe to remote broadcasts: the session writes the broadcasts the
49	/// remote announces into this [`origin::Producer`]. Omit to subscribe to nothing.
50	pub fn with_subscriber(mut self, subscribe: origin::Producer) -> Self {
51		self.subscribe = Some(subscribe);
52		self
53	}
54
55	/// Attach a per-connection [`stats::Session`] context. The session's publish
56	/// (egress) and subscribe (ingress) origin handles are tagged with it, so all
57	/// traffic counters are attributed through the model for this session's lifetime,
58	/// and how the session ended is recorded there.
59	/// Pass [`stats::Session::default`] (a no-op context) to opt out.
60	pub fn with_stats(mut self, stats: stats::Session) -> Self {
61		self.stats = stats;
62		self
63	}
64
65	/// Cap what the server can make this session hold. Defaults to [`session::Limits::default`](crate::session::Limits::default).
66	pub fn with_limits(mut self, limits: crate::session::Limits) -> Self {
67		self.limits = limits;
68		self
69	}
70
71	/// Share `allocator`'s reservations with every session this client dials.
72	///
73	/// Each session probes for what they add up to, and its
74	/// [`Session::allocator`](crate::Session::allocator) reserves into the same registry,
75	/// so a reservation taken on one session still counts after a reconnect. Without
76	/// one, each session starts an empty registry of its own.
77	pub fn with_allocator(mut self, allocator: crate::bandwidth::Allocator) -> Self {
78		self.allocator = Some(allocator);
79		self
80	}
81
82	/// The registry the next session probes for.
83	fn allocator(&self) -> crate::bandwidth::Allocator {
84		self.allocator.clone().unwrap_or_default()
85	}
86
87	/// Share `viewers` with every session this client dials.
88	///
89	/// Each session sends what they add up to as its PROBE target, and its
90	/// [`Session::viewers`](crate::Session::viewers) watches into the same registry, so
91	/// a viewer taken on one session still counts after a reconnect. Without one, each
92	/// session starts an empty registry of its own.
93	pub fn with_viewers(mut self, viewers: crate::bandwidth::Viewers) -> Self {
94		self.viewers = Some(viewers);
95		self
96	}
97
98	/// The registry the next session sends the target of.
99	fn viewers(&self) -> crate::bandwidth::Viewers {
100		self.viewers.clone().unwrap_or_default()
101	}
102
103	/// Probe a quiet peer and report it [`Stale`](crate::transport::Liveness::Stale) through
104	/// [`Session::liveness`] before closing on it; see [`KeepAlive`](crate::transport::KeepAlive).
105	///
106	/// Each session's connect fails with [`Error::KeepAlive`] on a transport that refuses it.
107	/// Without one, a session keeps the transport's own keep-alive and never reports staleness.
108	pub fn with_keep_alive(mut self, keep_alive: crate::transport::KeepAlive) -> Self {
109		self.keep_alive = Some(keep_alive);
110		self
111	}
112
113	/// Restrict which protocol versions to offer, in preference order.
114	/// Defaults to every version this crate supports.
115	pub fn with_versions(mut self, versions: Versions) -> Self {
116		self.versions = versions;
117		self
118	}
119
120	/// Name the URL each session is dialed at, so the server learns the request target.
121	///
122	/// A transport whose request URI already reaches the server
123	/// ([`Address::Uri`](crate::transport::Address::Uri)) sends nothing more. Otherwise
124	/// SETUP carries the path and query (moq-lite-05 and newer, every moq-transport
125	/// draft), which is how a credential in the query (`?jwt=`) arrives, and for
126	/// `moqt://` the authority (moq-transport only). A `unix://` URL names its target in
127	/// its `?path=` query, since its path is the socket file.
128	pub fn with_url(mut self, url: url::Url) -> Self {
129		self.url = Some(url);
130		self
131	}
132
133	/// The URL [`with_url`](Self::with_url) set, if any.
134	pub fn url(&self) -> Option<&url::Url> {
135		self.url.as_ref()
136	}
137
138	/// The request target our SETUP carries: the dialed URL's path, plus `?` and the
139	/// query when there is one (draft-ietf-moq-transport-22, section 9.1.2).
140	///
141	/// `None` on a transport that carries its own request URI, where a SETUP path is a
142	/// protocol violation, and when the target is empty, which means the server's
143	/// default path: a peer on published lite-05 rejects an empty value outright.
144	fn setup_path(&self, address: crate::transport::Address) -> Option<String> {
145		let url = self
146			.url
147			.as_ref()
148			.filter(|_| address == crate::transport::Address::Setup)?;
149
150		let target = match url.scheme() {
151			// One form-encoded value, so a target with its own `?query` arrives percent-encoded.
152			"unix" => url.query_pairs().find(|(k, _)| k == "path")?.1.into_owned(),
153			// A trailing `?` parses as an empty query, which is not a query: appending it
154			// would spell one target two ways.
155			_ => match url.query().filter(|query| !query.is_empty()) {
156				Some(query) => format!("{}?{}", url.path(), query),
157				None => url.path().to_owned(),
158			},
159		};
160
161		(!target.is_empty()).then_some(target)
162	}
163
164	/// The URI authority our SETUP carries, which a raw-QUIC `moqt://` client must send
165	/// (draft-ietf-moq-transport-22, 9.1.1).
166	///
167	/// Built from the host and port so URL userinfo never goes on the wire. `None` for
168	/// every other scheme, on a transport that carries its own request URI, and when the
169	/// URL has no host.
170	fn setup_authority(&self, address: crate::transport::Address) -> Option<String> {
171		let url = self
172			.url
173			.as_ref()
174			.filter(|_| address == crate::transport::Address::Setup)?;
175		if url.scheme() != "moqt" {
176			return None;
177		}
178
179		let host = url.host_str().filter(|host| !host.is_empty())?;
180		Some(match url.port() {
181			Some(port) => format!("{host}:{port}"),
182			None => host.to_owned(),
183		})
184	}
185
186	/// Present `token` as the connection credential in SETUP, on versions that carry one
187	/// (moq-lite-07+ and every moq-transport draft we speak). The session's empty-token
188	/// AUTH stream then answers with its grant.
189	///
190	/// Other versions send nothing, so a caller that may negotiate one also puts the
191	/// token in the URL query. moq-lite carries no Token Type, so only
192	/// [`Token::OUT_OF_BAND`](setup::Token::OUT_OF_BAND) reaches it; another type fails
193	/// the handshake.
194	pub fn with_token(mut self, token: setup::Token) -> Self {
195		self.setup_token = Some(token);
196		self
197	}
198
199	/// Build every session on `auth`, so each presents the tokens it holds and a route
200	/// naming one of its [`Credential`](crate::auth::Credential)s keeps it across a reconnect. Omit to
201	/// give each session a handle of its own, which ends with it.
202	///
203	/// The handle backs one active session at a time, plus the ones draining after a
204	/// GOAWAY: connecting another while one is still active fails with
205	/// [`Error::Duplicate`].
206	pub fn with_auth(mut self, auth: crate::auth::Handle) -> Self {
207		self.auth = Some(auth);
208		self
209	}
210
211	/// Offer the `ietf` extension on moq-lite-07, so a hop between relays carries the
212	/// moq-transport state of a track a moq-transport publisher made. Off by default.
213	///
214	/// Behind the `relay` feature: moq-relay's door for its own links, not an API.
215	#[cfg(feature = "relay")]
216	pub fn with_ietf(mut self, ietf: bool) -> Self {
217		self.extensions.ietf = ietf;
218		self
219	}
220
221	/// Whether to offer MoQ Solicit on moq-transport, which every session does. Off acts as a
222	/// moq-transport peer without it.
223	///
224	/// Behind the `test-support` feature: a test's door, not an API.
225	#[cfg(feature = "test-support")]
226	pub fn with_solicit(mut self, solicit: bool) -> Self {
227		self.extensions.solicit = solicit;
228		self
229	}
230
231	/// Set the implementation to advertise in SETUP, as space-separated `name/version`
232	/// product tokens, outermost first. Defaults to [`IMPLEMENTATION`](crate::IMPLEMENTATION);
233	/// an empty string advertises nothing.
234	pub fn with_implementation(mut self, implementation: impl Into<String>) -> Self {
235		self.implementation = Some(implementation.into());
236		self
237	}
238
239	/// The Implementation our SETUP carries, or `None` to omit it.
240	fn implementation(&self) -> Option<String> {
241		setup::implementation(self.implementation.as_deref().unwrap_or(crate::IMPLEMENTATION))
242	}
243
244	/// Price this link, in the units the rest of the mesh uses (moq-lite-06+, and
245	/// moq-transport via the MoQ Cluster extension).
246	///
247	/// The dialer is the side that knows what a link costs, because it chose the peer:
248	/// use `1` for a sibling in the same datacenter and something large for another
249	/// region across a metered backbone. Zero is refused on moq-lite-07, whose routing
250	/// needs every link to cost something. So this prices both directions. We add it to
251	/// the route cost of every announcement the peer sends us, and declare it in our
252	/// SETUP so the peer adds it to every announcement we send, which is what a server
253	/// accepting an anonymous connection needs: it cannot tell a sibling from a
254	/// stranger, so it has no price of its own to apply.
255	///
256	/// A price the peer declares applies only where we set none. An unpriced link costs
257	/// `1`, which makes the cost track the hop count and so reproduces plain
258	/// shortest-path routing.
259	pub fn with_cost(mut self, cost: impl Into<crate::origin::Cost>) -> Self {
260		self.cost = Some(cost.into().value());
261		self
262	}
263
264	/// Assign the Node ID this peer's routes are attributed to, overriding the fresh
265	/// per-dial default.
266	///
267	/// A dialed session whose peer declares no Node ID gets a random one for that
268	/// connection, the same way an accepted session does. That keeps a route
269	/// learned from the peer off the session that learned it, and keeps a
270	/// SUBSCRIBE that arrives on it from being routed back to it. An identity the
271	/// peer declares on the wire still wins.
272	///
273	/// Pass an id only for a peer whose identity the caller has actually
274	/// established. Two dials given the same node are treated as one endpoint:
275	/// routes learned from either are kept off both, and content arriving on
276	/// either is interchangeable with the other's. That is the point when they
277	/// really are one peer reconnecting or running redundant links, and a bug
278	/// otherwise. Derive it from the authenticated identity, never from something
279	/// coarser like the remote address.
280	pub fn with_peer_node(mut self, node: std::num::NonZeroU64) -> Self {
281		self.peer_node = Some(node);
282		self
283	}
284
285	/// The hop this connection attributes the peer to when the peer declares none.
286	///
287	/// A caller-supplied id is stable across dials of this client. Otherwise each
288	/// connection gets a fresh one, matching the per-session default an accepted
289	/// session already has.
290	fn assigned_hop(&self) -> crate::Hop {
291		self.peer_node.map_or_else(crate::Hop::random, crate::Hop::from)
292	}
293
294	/// The new session's side of its auth handle: the one from [`with_auth`](Self::with_auth),
295	/// or one of its own. `requests` for moq-transport, where a request carries a token.
296	fn link(&self, supported: bool, requests: bool) -> Result<crate::auth::Link, Error> {
297		match &self.auth {
298			Some(handle) => crate::auth::Link::attach(handle, supported, requests),
299			None if requests => Ok(crate::auth::Link::ietf()),
300			None => Ok(crate::auth::Link::new(supported)),
301		}
302	}
303
304	/// The origin pair a session attaches, tagged and filtered.
305	///
306	/// Reads through the publish (egress) consumer and writes through the
307	/// subscribe (ingress) producer are attributed by the model through the
308	/// stats context; one shared context, so presence and viewer counts are
309	/// never double-attributed across the two halves. `peer_node` is the identity
310	/// this connection attributes the peer to when the peer declares none, so
311	/// subscriptions from the peer resolve to a source whose route excludes it.
312	/// A declared identity still wins inside each publisher; announce filtering
313	/// is per-protocol and handled there too.
314	fn origins(&self, peer_node: crate::Hop) -> (Option<origin::Consumer>, Option<origin::Producer>) {
315		if self.publish.is_none() && self.subscribe.is_none() {
316			tracing::warn!("not publishing or consuming anything");
317		}
318		let publish = self.publish.clone().map(|origin| origin.with_stats(self.stats.clone()));
319		let subscribe = self
320			.subscribe
321			.clone()
322			.map(|origin| origin.with_stats(self.stats.clone()));
323		let publish = publish.map(|origin| origin.excluding(peer_node));
324		(publish, subscribe)
325	}
326
327	/// Start a lite session on an already-negotiated version: build our SETUP,
328	/// wire the origins, and return the session and its driver.
329	fn start_lite(
330		&self,
331		runtime: Deadlines,
332		session: Transport,
333		version: lite::Version,
334		peer_node: crate::Hop,
335	) -> Result<(Session, crate::Driver), Error> {
336		let (publish, subscribe) = self.origins(peer_node);
337
338		// Advertise our capabilities (we report what the transport measures, and
339		// probe to the peer's target only with a sender) plus the request path on
340		// URI-less transports, and the direction we intend to use so the server
341		// can reject a token that lacks the matching scope during the handshake
342		// instead of silently carrying no media. Versions without a Setup Stream
343		// have nothing to advertise.
344		let our_setup = if version.has_setup_stream() {
345			lite::Setup {
346				probe: lite::ProbeLevel::detect(&session),
347				path: self.setup_path(session.address()),
348				role: lite::Role::from_origins(self.publish.is_some(), self.subscribe.is_some()),
349				cost: self.cost,
350				// Filled by `lite::start` from the attached origin handles.
351				hop: None,
352				node: None,
353				// Older versions carry the credential in the URL query instead.
354				token: self.setup_token.clone().filter(|_| version.has_auth()),
355				ietf: self.extensions.ietf && version.has_ietf(),
356				implementation: self.implementation(),
357			}
358		} else {
359			lite::Setup::default()
360		};
361
362		// One registry, which the subscriber sends and the session hands out.
363		let viewers = self.viewers();
364		let start = lite::start(lite::Config {
365			runtime: runtime.clone(),
366			stats: self.stats.clone(),
367			client: true,
368			limits: self.limits,
369			viewers: viewers.clone(),
370			session: session.clone(),
371			setup_stream: None,
372			publish,
373			subscribe,
374			peer_node: Some(peer_node),
375			version,
376			our_setup,
377			peer_setup: None,
378			auth: self.link(version.has_auth(), false)?,
379		})?;
380
381		Ok(Session::new(
382			runtime,
383			session,
384			version.into(),
385			start.recv_bandwidth,
386			crate::driver::Protocol::Lite(Box::new(start.driver)),
387			crate::session::Handles {
388				stats: self.stats.clone(),
389				goaway: start.goaway,
390				auth: start.auth,
391				credential: start.credential,
392				estimate: Some(start.estimate),
393				peer_target: Some(start.peer_target),
394				bandwidth: self.allocator(),
395				viewers,
396				peer_implementation: start.peer_implementation,
397				datagrams_unrouted: start.datagrams_unrouted,
398			},
399		))
400	}
401
402	/// Perform the MoQ handshake, returning the [`Session`] and its [`Driver`](crate::Driver).
403	///
404	/// Poll the returned driver with nondecreasing time, starting at `now`.
405	pub fn connect(
406		&self,
407		now: Instant,
408		session: impl crate::transport::poll::Boxable,
409	) -> impl Future<Output = Result<(Session, crate::Driver), Error>> {
410		// Box before any protocol code runs, so it is compiled once rather than per transport.
411		self.connect_boxed(now, Transport::new(session))
412	}
413
414	fn connect_boxed(
415		&self,
416		now: Instant,
417		session: Transport,
418	) -> impl Future<Output = Result<(Session, crate::Driver), Error>> {
419		let mut connect = Connect::Start {
420			runtime: Deadlines::new(now),
421			session,
422		};
423		kio::wait(move |waiter| connect.poll(self, waiter))
424	}
425
426	/// Start the session the transport's ALPN picks, or begin negotiating moq-lite on a bidi
427	/// SETUP when it picks none.
428	fn start(&self, runtime: Deadlines, session: Transport) -> Result<Connect, Error> {
429		if let Some(keep_alive) = self.keep_alive {
430			session.set_keep_alive(keep_alive).map_err(Error::KeepAlive)?;
431		}
432		let peer_node = self.assigned_hop();
433		let (publish, subscribe) = self.origins(peer_node);
434
435		let supported = match session.protocol() {
436			Some(alpn @ (ALPN_23 | ALPN_22 | ALPN_20 | ALPN_18)) => {
437				let draft = match alpn {
438					ALPN_23 => ietf::Version::Draft23,
439					ALPN_22 => ietf::Version::Draft22,
440					ALPN_20 => ietf::Version::Draft20,
441					_ => ietf::Version::Draft18,
442				};
443
444				let v = self.versions.select(Version::ietf(draft)).ok_or(Error::Version)?;
445
446				// SETUP is exchanged by the connection driver.
447				// We advertise the request path in our SETUP for URL-less transports.
448				// moq-transport carries no AUTH: a token rides the requests that name it.
449				let auth = self.link(false, true)?;
450				let peer_implementation = setup::PeerImplementation::default();
451				let (protocol, goaway) = ietf::start(ietf::Config {
452					runtime: runtime.clone(),
453					stats: self.stats.clone(),
454					limits: self.limits,
455					session: session.clone(),
456					client: true,
457					publish,
458					subscribe,
459					peer_node: Some(peer_node),
460					cost: self.cost,
461					version: draft,
462					path: self.setup_path(session.address()),
463					authority: self.setup_authority(session.address()),
464					token: self.setup_token.clone(),
465					peer_setup_stream: None,
466					peer_declared: None,
467					auth: auth.clone(),
468					early_unis: Vec::new(),
469					extensions: self.extensions,
470					implementation: self.implementation(),
471					peer_implementation: peer_implementation.clone(),
472				})?;
473
474				tracing::debug!(version = ?v, "connected");
475				return Ok(Connect::Started(Box::new(Session::new(
476					runtime,
477					session,
478					v,
479					None,
480					crate::driver::Protocol::Ietf(protocol),
481					crate::session::Handles {
482						stats: self.stats.clone(),
483						goaway,
484						auth,
485						credential: None,
486						estimate: None,
487						peer_target: None,
488						bandwidth: self.allocator(),
489						viewers: self.viewers(),
490						peer_implementation,
491						datagrams_unrouted: None,
492					},
493				))));
494			}
495			Some(alpn @ (ALPN_LITE_05 | ALPN_LITE_06 | ALPN_LITE_07_WIP)) => {
496				let version = match alpn {
497					ALPN_LITE_07_WIP => lite::Version::Lite07,
498					ALPN_LITE_06 => lite::Version::Lite06,
499					_ => lite::Version::Lite05,
500				};
501				self.versions.select(Version::lite(version)).ok_or(Error::Version)?;
502				return self
503					.start_lite(runtime, session, version, peer_node)
504					.map(|started| Connect::Started(Box::new(started)));
505			}
506			Some(ALPN_LITE_04) => {
507				self.versions
508					.select(Version::lite(lite::Version::Lite04))
509					.ok_or(Error::Version)?;
510				return self
511					.start_lite(runtime, session, lite::Version::Lite04, peer_node)
512					.map(|started| Connect::Started(Box::new(started)));
513			}
514			Some(ALPN_LITE_03) => {
515				self.versions
516					.select(Version::lite(lite::Version::Lite03))
517					.ok_or(Error::Version)?;
518				return self
519					.start_lite(runtime, session, lite::Version::Lite03, peer_node)
520					.map(|started| Connect::Started(Box::new(started)));
521			}
522			// No ALPN, or `moql`: negotiate moq-lite in a bidi SETUP.
523			Some(ALPN_LITE) | None => self.versions.filter(&NEGOTIATED.into()).ok_or(Error::Version)?,
524			Some(p) => return Err(Error::UnknownAlpn(p.to_string())),
525		};
526
527		Ok(Connect::Open {
528			negotiation: Negotiation {
529				runtime,
530				session,
531				peer_node,
532				publish,
533				subscribe,
534				supported,
535			},
536			open: Default::default(),
537		})
538	}
539
540	/// Start a lite-01/02 session on the negotiation stream the server's SETUP picked it on.
541	fn start_negotiated(
542		&self,
543		negotiation: Negotiation,
544		stream: Stream<Transport, Version>,
545		version: lite::Version,
546	) -> Result<(Session, crate::Driver), Error> {
547		let Negotiation {
548			runtime,
549			session,
550			peer_node,
551			publish,
552			subscribe,
553			..
554		} = negotiation;
555		let stream = stream.with_version(version);
556		// One registry, which the subscriber sends and the session hands out.
557		let viewers = self.viewers();
558		let start = lite::start(lite::Config {
559			runtime: runtime.clone(),
560			stats: self.stats.clone(),
561			client: true,
562			limits: self.limits,
563			viewers: viewers.clone(),
564			session: session.clone(),
565			setup_stream: Some(stream),
566			publish,
567			subscribe,
568			peer_node: Some(peer_node),
569			version,
570			// Lite 01/02 continue on the bidi SETUP stream and have no Setup Stream.
571			our_setup: lite::Setup::default(),
572			peer_setup: None,
573			// Lite 01/02 carry no AUTH.
574			auth: self.link(version.has_auth(), false)?,
575		})?;
576
577		Ok(Session::new(
578			runtime,
579			session,
580			Version::lite(version),
581			start.recv_bandwidth,
582			crate::driver::Protocol::Lite(Box::new(start.driver)),
583			crate::session::Handles {
584				stats: self.stats.clone(),
585				goaway: start.goaway,
586				auth: start.auth,
587				credential: start.credential,
588				estimate: Some(start.estimate),
589				peer_target: Some(start.peer_target),
590				bandwidth: self.allocator(),
591				viewers,
592				peer_implementation: start.peer_implementation,
593				datagrams_unrouted: start.datagrams_unrouted,
594			},
595		))
596	}
597}
598
599/// What a client without a versioned ALPN negotiates moq-lite with, held until it starts.
600struct Negotiation {
601	runtime: Deadlines,
602	session: Transport,
603	peer_node: crate::Hop,
604	publish: Option<origin::Consumer>,
605	subscribe: Option<origin::Producer>,
606	/// The versions offered in the client SETUP.
607	supported: Versions,
608}
609
610/// The client's side of a handshake: [`Client::connect`] as a poll. Dropped while pending, it
611/// releases what its step holds, resetting a negotiation stream still open.
612enum Connect {
613	/// Not polled yet: the transport's ALPN picks the path.
614	Start { runtime: Deadlines, session: Transport },
615	/// Started without waiting on the peer. Boxed, being several times the size of the
616	/// handshake steps.
617	Started(Box<(Session, crate::Driver)>),
618	/// Waiting its turn for credit to open the bidi stream the SETUP is negotiated on.
619	Open {
620		negotiation: Negotiation,
621		open: crate::transport::open::Open,
622	},
623	/// Flushing the client SETUP, already buffered, then reading the server's.
624	Exchange {
625		negotiation: Negotiation,
626		stream: Stream<Transport, Version>,
627	},
628	/// Reading the stream to its end once the server's SETUP hands the session off to a
629	/// versioned ALPN path, which keeps the drop from stopping a reply the server is still
630	/// waiting to have acknowledged.
631	HandOff {
632		negotiation: Negotiation,
633		stream: Stream<Transport, Version>,
634		version: lite::Version,
635	},
636	/// Resolved.
637	Done,
638}
639
640impl Connect {
641	/// The started session, or the error the handshake failed with.
642	fn poll(&mut self, client: &Client, waiter: &kio::Waiter) -> Poll<Result<(Session, crate::Driver), Error>> {
643		let res = ready!(self.poll_step(client, waiter));
644		// A server that shares no version with us closes the session over our SETUP, and its
645		// close reason can lose the race to the stream's reset, so name the likely cause here.
646		if let (Err(err), Self::Exchange { negotiation, .. }) = (&res, &*self) {
647			let offered: Vec<String> = negotiation.supported.iter().map(ToString::to_string).collect();
648			tracing::warn!(%err, ?offered, "version negotiation failed; the server may accept none of the offered versions");
649		}
650		// Release what the handshake held, even on a failure.
651		*self = Self::Done;
652		Poll::Ready(res)
653	}
654
655	fn poll_step(&mut self, client: &Client, waiter: &kio::Waiter) -> Poll<Result<(Session, crate::Driver), Error>> {
656		loop {
657			match self {
658				Self::Start { .. } => {
659					let Self::Start { runtime, session } = std::mem::replace(self, Self::Done) else {
660						unreachable!("matched above");
661					};
662					*self = client.start(runtime, session)?;
663				}
664				Self::Started(_) => {
665					let Self::Started(started) = std::mem::replace(self, Self::Done) else {
666						unreachable!("matched above");
667					};
668					return Poll::Ready(Ok(*started));
669				}
670				Self::Open { negotiation, open } => {
671					// The SETUP keeps lite-01's framing whichever version it offers.
672					let stream = ready!(Stream::poll_open(
673						&negotiation.session,
674						open,
675						Version::lite(lite::Version::Lite01),
676						waiter
677					))?;
678					let mut stream = stream.with_stats(&client.stats);
679					let setup = setup::Client {
680						versions: negotiation.supported.clone().into(),
681						parameters: lite::Parameters::default().encode_bytes(lite::Version::Lite01)?,
682					};
683					stream.writer.buffer(&setup)?;
684					let Self::Open { negotiation, .. } = std::mem::replace(self, Self::Done) else {
685						unreachable!("matched above");
686					};
687					*self = Self::Exchange { negotiation, stream };
688				}
689				Self::Exchange { negotiation, stream } => {
690					ready!(stream.writer.poll_flush(waiter))?;
691					let server: setup::Server = ready!(stream.reader.poll_decode(waiter))?;
692					let version = negotiation
693						.supported
694						.iter()
695						.find(|v| coding::Version::from(**v) == server.version)
696						.copied()
697						.ok_or(Error::Version)?;
698					let Version(crate::Draft::Lite(version)) = version else {
699						return Poll::Ready(Err(Error::Version));
700					};
701					let Self::Exchange { negotiation, stream } = std::mem::replace(self, Self::Done) else {
702						unreachable!("matched above");
703					};
704					if !Version::lite(version).hands_off() {
705						return Poll::Ready(client.start_negotiated(negotiation, stream, version));
706					}
707					*self = Self::HandOff {
708						negotiation,
709						stream,
710						version,
711					};
712				}
713				Self::HandOff { stream, .. } => {
714					// The server ends the stream after its SETUP.
715					ready!(stream.reader.poll_closed(waiter))?;
716					let Self::HandOff {
717						negotiation,
718						stream,
719						version,
720					} = std::mem::replace(self, Self::Done)
721					else {
722						unreachable!("matched above");
723					};
724					drop(stream);
725					let Negotiation {
726						runtime,
727						session,
728						peer_node,
729						..
730					} = negotiation;
731					return Poll::Ready(client.start_lite(runtime, session, version, peer_node));
732				}
733				Self::Done => panic!("handshake polled after it resolved"),
734			}
735		}
736	}
737}
738
739#[cfg(test)]
740mod tests {
741	use super::*;
742	use crate::model::ProduceTest;
743	use std::{
744		collections::VecDeque,
745		sync::{Arc, Mutex},
746	};
747
748	use std::task::Poll;
749
750	use crate::SessionError;
751	use crate::coding::{Decode, Encode};
752	use bytes::{BufMut, Bytes};
753
754	#[derive(Debug, Clone, Default)]
755	struct FakeError;
756
757	impl std::fmt::Display for FakeError {
758		fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
759			write!(f, "fake transport error")
760		}
761	}
762
763	impl std::error::Error for FakeError {}
764
765	/// Only this side ever closes a fake session, and like QUIC it says only that.
766	impl crate::transport::Error for FakeError {
767		fn close_kind(&self) -> crate::transport::CloseKind {
768			crate::transport::CloseKind::Closed
769		}
770		fn session_error(&self) -> Option<(u32, String)> {
771			None
772		}
773	}
774
775	#[derive(Clone, Default)]
776	struct FakeSession {
777		state: Arc<FakeSessionState>,
778		/// The sender, set by [`Self::with_probe`].
779		probe: Option<crate::transport::Probe>,
780	}
781
782	#[derive(Default)]
783	struct FakeSessionState {
784		panic_on_poll: std::sync::atomic::AtomicBool,
785		protocol: Option<&'static str>,
786		control_stream: Mutex<Option<(FakeSendStream, FakeRecvStream)>>,
787		close_events: kio::Shared<Vec<(u32, String)>>,
788		control_writes: Arc<Mutex<Vec<u8>>>,
789		send_rate: Mutex<Option<u64>>,
790		wire: crate::transport::Wire,
791	}
792
793	fn any_close(events: &kio::Ref<'_, Vec<(u32, String)>>) -> Poll<()> {
794		match events.is_empty() {
795			true => Poll::Pending,
796			false => Poll::Ready(()),
797		}
798	}
799
800	impl FakeSession {
801		fn new(protocol: Option<&'static str>, server_control_bytes: Vec<u8>) -> Self {
802			let writes = Arc::new(Mutex::new(Vec::new()));
803			let send = FakeSendStream { writes: writes.clone() };
804			let recv = crate::transport::poll::Buffered::new(FakeChunks {
805				data: VecDeque::from(server_control_bytes),
806			});
807			let state = FakeSessionState {
808				panic_on_poll: Default::default(),
809				protocol,
810				control_stream: Mutex::new(Some((send, recv))),
811				close_events: kio::Shared::default(),
812				control_writes: writes,
813				send_rate: Mutex::new(None),
814				wire: crate::transport::Wire::new(),
815			};
816			Self {
817				state: Arc::new(state),
818				probe: None,
819			}
820		}
821
822		fn set_send_rate(&self, rate: Option<u64>) {
823			*self.state.send_rate.lock().unwrap() = rate;
824		}
825
826		/// Give the transport a sender, so the session hands it a target.
827		fn with_probe(mut self) -> Self {
828			self.probe = Some(crate::transport::Probe::new());
829			self
830		}
831
832		/// What the session last handed the sender, in bits per second.
833		fn probe_target(&self) -> u64 {
834			self.probe.as_ref().expect("built with_probe").target().as_bps()
835		}
836
837		fn set_sent_bytes(&self, bytes: u64) {
838			self.state.wire.set_sent_bytes(bytes);
839		}
840
841		fn control_writes(&self) -> Vec<u8> {
842			self.state.control_writes.lock().unwrap().clone()
843		}
844
845		async fn wait_for_first_close(&self) -> (u32, String) {
846			let events = self.state.close_events.wait(any_close).await;
847			events[0].clone()
848		}
849	}
850
851	impl crate::transport::poll::Session for FakeSession {
852		type SendStream = FakeSendStream;
853		type RecvStream = FakeRecvStream;
854		type Error = FakeError;
855
856		fn poll_accept_uni(&self, _waiter: &kio::Waiter) -> Poll<Result<Self::RecvStream, Self::Error>> {
857			Poll::Pending
858		}
859
860		fn poll_accept_bi(
861			&self,
862			_waiter: &kio::Waiter,
863		) -> Poll<Result<(Self::SendStream, Self::RecvStream), Self::Error>> {
864			Poll::Pending
865		}
866
867		fn poll_open_bi(
868			&self,
869			_waiter: &kio::Waiter,
870			_: crate::transport::poll::SendOptions<'_, crate::transport::poll::Ungrouped>,
871		) -> Poll<Result<(Self::SendStream, Self::RecvStream), Self::Error>> {
872			Poll::Ready(self.state.control_stream.lock().unwrap().take().ok_or(FakeError))
873		}
874
875		fn poll_open_uni(
876			&self,
877			_waiter: &kio::Waiter,
878			_: crate::transport::poll::SendOptions<'_, crate::transport::poll::Ungrouped>,
879		) -> Poll<Result<Self::SendStream, Self::Error>> {
880			Poll::Pending
881		}
882
883		fn send_group(&self, _: i64) -> Option<crate::transport::poll::Ungrouped> {
884			None
885		}
886
887		fn send_datagram(
888			&self,
889			_: Bytes,
890			_: crate::transport::poll::SendOptions<'_, crate::transport::poll::Ungrouped>,
891		) -> Result<(), Self::Error> {
892			Ok(())
893		}
894
895		fn poll_recv_datagram(&self, _waiter: &kio::Waiter) -> Poll<Result<Bytes, Self::Error>> {
896			Poll::Pending
897		}
898
899		fn max_datagram_size(&self) -> usize {
900			1200
901		}
902
903		fn address(&self) -> crate::transport::Address {
904			crate::transport::Address::Setup
905		}
906		fn protocol(&self) -> Option<&str> {
907			self.state.protocol
908		}
909
910		fn close(&self, code: u32, reason: &str) {
911			self.state.close_events.lock().push((code, reason.to_string()));
912		}
913
914		fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Self::Error> {
915			assert!(
916				!self
917					.state
918					.panic_on_poll
919					.swap(false, std::sync::atomic::Ordering::Relaxed),
920				"injected driver poll panic"
921			);
922			let _ = std::task::ready!(self.state.close_events.poll(waiter, any_close));
923			Poll::Ready(FakeError)
924		}
925
926		fn metrics(&self) -> impl crate::transport::Metrics {
927			FakeMetrics {
928				send_rate: *self.state.send_rate.lock().unwrap(),
929			}
930		}
931
932		fn wire(&self) -> Option<crate::transport::Wire> {
933			Some(self.state.wire.clone())
934		}
935
936		fn probe(&self) -> Option<crate::transport::Probe> {
937			self.probe.clone()
938		}
939	}
940
941	struct FakeMetrics {
942		send_rate: Option<u64>,
943	}
944
945	impl crate::transport::Metrics for FakeMetrics {
946		fn estimated_send_rate(&self) -> Option<u64> {
947			self.send_rate
948		}
949	}
950
951	#[derive(Clone, Default)]
952	struct FakeSendStream {
953		writes: Arc<Mutex<Vec<u8>>>,
954	}
955
956	impl crate::transport::poll::SendStream for FakeSendStream {
957		type Error = FakeError;
958		type Group = crate::transport::poll::Ungrouped;
959		type Offset = ();
960
961		fn offset(&self) -> Self::Offset {}
962
963		fn poll_write(&mut self, _waiter: &kio::Waiter, buf: &[u8]) -> Poll<Result<usize, Self::Error>> {
964			self.writes.lock().unwrap().put_slice(buf);
965			Poll::Ready(Ok(buf.len()))
966		}
967
968		fn set_priority(&mut self, _order: i64) {}
969
970		fn set_group(&mut self, group: &Self::Group) {
971			match *group {}
972		}
973
974		fn finish(&mut self) -> Result<(), Self::Error> {
975			Ok(())
976		}
977
978		fn reset(&mut self, _code: u32) {}
979
980		fn reset_at(&mut self, _offset: &(), _code: u32) {}
981
982		fn poll_closed(&self, _waiter: &kio::Waiter) -> Poll<Result<(), Self::Error>> {
983			Poll::Ready(Ok(()))
984		}
985	}
986
987	type FakeRecvStream = crate::transport::poll::Buffered<FakeChunks>;
988
989	struct FakeChunks {
990		data: VecDeque<u8>,
991	}
992
993	impl crate::transport::poll::Chunks for FakeChunks {
994		type Error = FakeError;
995
996		fn poll_read_chunk(&mut self, _waiter: &kio::Waiter, max: usize) -> Poll<Result<Option<Bytes>, Self::Error>> {
997			if self.data.is_empty() {
998				return Poll::Ready(Ok(None));
999			}
1000
1001			let size = max.min(self.data.len());
1002			Poll::Ready(Ok(Some(self.data.drain(..size).collect())))
1003		}
1004
1005		fn stop(&mut self, _code: u32) {}
1006	}
1007
1008	fn mock_server_setup(negotiated: Version) -> Vec<u8> {
1009		let mut encoded = Vec::new();
1010		let server = setup::Server {
1011			version: negotiated.into(),
1012			parameters: Bytes::new(),
1013		};
1014		server
1015			.encode(
1016				&mut crate::coding::Encoder::new(&mut encoded, negotiated.into()),
1017				negotiated,
1018			)
1019			.unwrap();
1020
1021		// Add a setup-stream SessionInfo frame using the negotiated Lite version.
1022		let info = lite::SessionInfo { bitrate: Some(1) };
1023		let lite_v = lite::Version::try_from(negotiated).unwrap();
1024		info.encode(&mut crate::coding::Encoder::new(&mut encoded, lite_v.into()), lite_v)
1025			.unwrap();
1026
1027		encoded
1028	}
1029
1030	async fn run_alpn_lite_fallback_case(protocol: Option<&'static str>) {
1031		let fake = FakeSession::new(protocol, mock_server_setup(Version::lite(lite::Version::Lite01)));
1032		let client = Client::new().with_versions(
1033			[
1034				Version::lite(lite::Version::Lite03),
1035				Version::lite(lite::Version::Lite02),
1036				Version::lite(lite::Version::Lite01),
1037			]
1038			.into(),
1039		);
1040
1041		// Start the returned driver after the handshake completes.
1042		let (_session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap();
1043		kio::clock::sim::spawn(crate::time::run(driver));
1044
1045		// Verify the client offered every configured moq-lite version over the `moql` SETUP.
1046		let mut setup_bytes = Bytes::from(fake.control_writes());
1047		let setup = crate::coding::decode_buf(&mut setup_bytes, Version::lite(lite::Version::Lite02), |r, v| {
1048			setup::Client::decode(r, v)
1049		})
1050		.unwrap();
1051		let advertised: Vec<Version> = setup.versions.iter().map(|v| Version::try_from(*v).unwrap()).collect();
1052		assert_eq!(
1053			advertised,
1054			vec![
1055				Version::lite(lite::Version::Lite03),
1056				Version::lite(lite::Version::Lite02),
1057				Version::lite(lite::Version::Lite01),
1058			]
1059		);
1060
1061		// The first close comes from the lite connection driver.
1062		// Any non-Version error here means SessionInfo decoded successfully
1063		// after set_version(). This test cares about the SETUP framing
1064		// fallback, not the specific close code. Cancel is what we'd see
1065		// with no origin; a protocol violation (or similar) is what an
1066		// auto-created origin's first interaction with a Lite01 peer trips.
1067		let (code, _) = fake.wait_for_first_close().await;
1068		// Session closes encode through the session registry, so compare against that one.
1069		assert_ne!(code, SessionError::Version.to_code(), "SessionInfo failed to decode");
1070	}
1071
1072	/// `connect` must not depend on the peer answering. A peer that opens the announce
1073	/// stream and then says nothing (or promises a count it never delivers) used to hold
1074	/// `connect` for the life of the session, since it waited for the initial announce
1075	/// set. Resolving a path you need is `request`'s job, which waits for
1076	/// that path rather than for the peer to finish talking.
1077	#[kio::test]
1078	async fn connect_does_not_wait_for_the_peer_to_announce() {
1079		// Serves bidi streams, so the announce stream opens, and never answers on them.
1080		let gate = kio::Producer::new(true);
1081		let transport = crate::lite::test_transport::SinkSession::gated_bi(gate.consume())
1082			.with_protocol(crate::version::ALPN_LITE_05);
1083
1084		// A subscribe origin is what makes the client open an announce stream at all.
1085		let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce();
1086		let client = Client::new()
1087			.with_versions([Version::lite(lite::Version::Lite05)].into())
1088			.with_subscriber(origin);
1089
1090		// Paused time auto-advances while every task is idle, so a `connect` that waits
1091		// on the silent peer trips this rather than hanging the suite.
1092		let (_session, _driver) = kio::clock::timeout(
1093			std::time::Duration::from_secs(30),
1094			client.connect(kio::clock::now(), transport),
1095		)
1096		.await
1097		.expect("connect waited on a peer that never announced")
1098		.expect("connect failed");
1099	}
1100
1101	fn dialed(url: &str) -> Client {
1102		Client::new().with_url(url.parse().unwrap())
1103	}
1104
1105	#[test]
1106	fn setup_path_is_the_request_target() {
1107		// An empty path and an absent one both mean the server's default, so we send
1108		// neither. A peer on published lite-05 rejects an empty value outright.
1109		let cases = [
1110			("unix:///run/moq.sock?path=/room", Some("/room")),
1111			// The whole resource path is one form-encoded value, so a `?query` inside it
1112			// arrives percent-encoded and comes back out whole.
1113			("unix:///run/moq.sock?path=/room%3Fjwt%3Dabc", Some("/room?jwt=abc")),
1114			("unix:///run/moq.sock?path=", None),
1115			("unix:///run/moq.sock", None),
1116			("tcp://localhost:4443/room?jwt=abc", Some("/room?jwt=abc")),
1117			("tcp://localhost:4443", None),
1118			("moqt://relay.example.com/anon?jwt=abc", Some("/anon?jwt=abc")),
1119			("moql://relay.example.com/anon", Some("/anon")),
1120			("moqt://relay.example.com", None),
1121			(
1122				"iroh://k5lnrlndqpqcgh4d5nhbnbnhcyrgvw6ttxwrsvsu4nlt6foorxaa/",
1123				Some("/"),
1124			),
1125			// The fragment is processed by the client and never sent (draft-22 6.1.1).
1126			("moqt://relay.example.com/anon?jwt=abc#pos:12", Some("/anon?jwt=abc")),
1127			// A trailing `?` is an empty query, not a query.
1128			("moqt://relay.example.com/anon?", Some("/anon")),
1129			("moqt://relay.example.com?", None),
1130		];
1131
1132		for (url, want) in cases {
1133			let client = dialed(url);
1134			assert_eq!(
1135				client.setup_path(crate::transport::Address::Setup).as_deref(),
1136				want,
1137				"{url}"
1138			);
1139			// The transport's own request URI carries the target: a SETUP path is a violation.
1140			assert_eq!(client.setup_path(crate::transport::Address::Uri), None, "{url}");
1141		}
1142		assert_eq!(Client::new().setup_path(crate::transport::Address::Setup), None);
1143	}
1144
1145	#[test]
1146	fn setup_authority_is_only_for_moqt() {
1147		let cases = [
1148			("moqt://relay.example.com/anon?jwt=abc", Some("relay.example.com")),
1149			("moqt://relay.example.com:4443/anon", Some("relay.example.com:4443")),
1150			("moqt://[::1]:4443", Some("[::1]:4443")),
1151			// Userinfo is a credential, and never goes on the wire.
1152			(
1153				"moqt://user:pass@relay.example.com:4443",
1154				Some("relay.example.com:4443"),
1155			),
1156			// A hostless URL has no authority to send.
1157			("moqt:///anon", None),
1158			// Only the draft's `moqt://` scheme is required to send it.
1159			("moql://relay.example.com", None),
1160			("tcp://relay.example.com:4443", None),
1161			("iroh://k5lnrlndqpqcgh4d5nhbnbnhcyrgvw6ttxwrsvsu4nlt6foorxaa", None),
1162		];
1163
1164		for (url, want) in cases {
1165			let client = dialed(url);
1166			assert_eq!(
1167				client.setup_authority(crate::transport::Address::Setup).as_deref(),
1168				want,
1169				"{url}"
1170			);
1171			assert_eq!(client.setup_authority(crate::transport::Address::Uri), None, "{url}");
1172		}
1173	}
1174
1175	#[kio::test]
1176	async fn alpn_lite_falls_back_to_moql_setup_and_switches_version_post_setup() {
1177		run_alpn_lite_fallback_case(Some(ALPN_LITE)).await;
1178	}
1179
1180	#[kio::test]
1181	async fn no_alpn_falls_back_to_moql_setup_and_switches_version_post_setup() {
1182		run_alpn_lite_fallback_case(None).await;
1183	}
1184
1185	// No executor is running: only explicitly polling the driver may process
1186	// a session close, and the driver must not retain a session handle.
1187	#[test]
1188	fn driver_is_caller_polled_and_holds_no_session() {
1189		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
1190		let client = Client::new().with_versions(Version::lite(lite::Version::Lite04).into());
1191
1192		let runtime = crate::time::Deadlines::new(crate::time::Instant::now());
1193		let (session, mut driver) = futures::executor::block_on(client.connect(runtime.now(), fake.clone())).unwrap();
1194		assert_eq!(session.version(), Version::lite(lite::Version::Lite04));
1195
1196		// Construction leaves the driver idle until the caller polls it.
1197		assert!(driver.poll(runtime.now(), &kio::Waiter::noop()).is_ok());
1198
1199		// The caller drops their only session clone; the machine observes the
1200		// last handle going away and closes the transport.
1201		drop(session);
1202		assert!(fake.state.close_events.read().is_empty());
1203		let _ = driver.poll(runtime.now(), &kio::Waiter::noop());
1204		assert_eq!(fake.state.close_events.read()[0].0, SessionError::Cancel.to_code());
1205	}
1206
1207	// Clones share the connection: the transport closes on the LAST drop, and
1208	// abort() closes it explicitly (first close wins). Both are relayed through
1209	// the machine, so each takes a tick to land.
1210	#[test]
1211	fn session_clones_share_the_close() {
1212		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
1213		let client = Client::new().with_versions(Version::lite(lite::Version::Lite04).into());
1214
1215		let runtime = crate::time::Deadlines::new(crate::time::Instant::now());
1216		let (session, mut driver) = futures::executor::block_on(client.connect(runtime.now(), fake.clone())).unwrap();
1217		let clone = session.clone();
1218
1219		// One clone dropping does nothing while another is alive.
1220		drop(session);
1221		assert!(fake.state.close_events.read().is_empty());
1222		let _ = driver.poll(runtime.now(), &kio::Waiter::noop());
1223		assert!(fake.state.close_events.read().is_empty());
1224
1225		clone.abort(Error::Cancel);
1226		let _ = driver.poll(runtime.now(), &kio::Waiter::noop());
1227		assert_eq!(fake.state.close_events.read()[0].0, SessionError::Cancel.to_code());
1228
1229		// And the machine publishes the transport's terminal error, which is
1230		// what `closed()` reports.
1231		let _ = driver.poll(runtime.now(), &kio::Waiter::noop());
1232		futures::executor::block_on(clone.closed());
1233
1234		// The final drop requests no second close: the handle-side close is once.
1235		let closes = fake.state.close_events.read().len();
1236		drop(clone);
1237		let _ = driver.poll(runtime.now(), &kio::Waiter::noop());
1238		assert_eq!(fake.state.close_events.read().len(), closes);
1239	}
1240
1241	// A transport that only knows this side closed it leaves the reason to the session,
1242	// which reports it from `closed()` and records it in the session's stats.
1243	#[test]
1244	fn a_local_close_reports_this_sides_reason() {
1245		use crate::stats::{Failure, Failures, Registry, Tier};
1246		let ended = |abort: Error| {
1247			let registry = Registry::new(Default::default());
1248			let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
1249			let client = Client::new()
1250				.with_versions(Version::lite(lite::Version::Lite04).into())
1251				.with_stats(
1252					registry
1253						.tier(Tier::default())
1254						.session(crate::stats::SessionInfo::new(crate::Path::from_static("root"))),
1255				);
1256			let runtime = crate::time::Deadlines::new(crate::time::Instant::now());
1257			let (session, mut driver) = futures::executor::block_on(client.connect(runtime.now(), fake)).unwrap();
1258			session.abort(abort);
1259			// One poll closes the transport, the next publishes how it ended.
1260			let _ = driver.poll(runtime.now(), &kio::Waiter::noop());
1261			let _ = driver.poll(runtime.now(), &kio::Waiter::noop());
1262			let err = futures::executor::block_on(session.closed());
1263			drop((client, session, driver));
1264			(err, registry.snapshot().sessions()[0].1.sessions_failed)
1265		};
1266
1267		let (err, failed) = ended(Error::Expired);
1268		assert!(matches!(err, Error::Expired), "{err:?}");
1269		assert_eq!(failed.count(Failure::Expired), 1);
1270
1271		// Anything the peer is told is "no error" is a clean close.
1272		let (err, failed) = ended(Error::GoingAway);
1273		assert!(matches!(err, Error::Cancel), "{err:?}");
1274		assert_eq!(failed, Failures::default());
1275	}
1276
1277	/// A task that closes the transport itself, as a protocol violation on one request does,
1278	/// is the session's reason even when the transport reports only a local close, and it
1279	/// wins over whatever closes it after.
1280	#[test]
1281	fn a_task_close_is_the_sessions_reason() {
1282		use crate::stats::{Failure, Registry, Tier};
1283		use crate::transport::poll::Session as _;
1284		let registry = Registry::new(Default::default());
1285		let client = Client::new()
1286			.with_versions(Version::lite(lite::Version::Lite04).into())
1287			.with_stats(
1288				registry
1289					.tier(Tier::default())
1290					.session(crate::stats::SessionInfo::new(crate::Path::from_static("root"))),
1291			);
1292		let runtime = crate::time::Deadlines::new(crate::time::Instant::now());
1293		let task = Transport::new(FakeSession::new(Some(ALPN_LITE_04), Vec::new()));
1294		let (session, mut driver) =
1295			futures::executor::block_on(client.connect_boxed(runtime.now(), task.clone())).unwrap();
1296		task.close(SessionError::ProtocolViolation.to_code(), "malformed");
1297		session.abort(Error::App(7));
1298		let _ = driver.poll(runtime.now(), &kio::Waiter::noop());
1299		let _ = driver.poll(runtime.now(), &kio::Waiter::noop());
1300		let err = futures::executor::block_on(session.closed());
1301		assert!(
1302			matches!(err, Error::Session(SessionError::ProtocolViolation)),
1303			"{err:?}"
1304		);
1305		drop((client, session, driver));
1306		let failed = registry.snapshot().sessions()[0].1.sessions_failed;
1307		assert_eq!(failed.count(Failure::Application), 1, "{failed:?}");
1308	}
1309
1310	// Dropping the driver instead of running it tears the session
1311	// down: the machine was the only transport holder, and `closed()` resolves
1312	// rather than parking forever on a machine nobody polls.
1313	#[test]
1314	fn dropped_driver_resolves_closed() {
1315		for polled in [false, true] {
1316			let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
1317			let client = Client::new().with_versions(Version::lite(lite::Version::Lite04).into());
1318			let runtime = crate::time::Deadlines::new(crate::time::Instant::now());
1319			let (session, mut driver) = futures::executor::block_on(client.connect(runtime.now(), fake)).unwrap();
1320			if polled {
1321				assert!(driver.poll(runtime.now(), &kio::Waiter::noop()).is_ok());
1322			}
1323			drop(driver);
1324			assert!(matches!(futures::executor::block_on(session.closed()), Error::Cancel));
1325		}
1326	}
1327
1328	#[test]
1329	fn driver_panic_is_published_before_the_executor_drops_it() {
1330		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
1331		let client = Client::new().with_versions(Version::lite(lite::Version::Lite04).into());
1332		let runtime = crate::time::Deadlines::new(crate::time::Instant::now());
1333		let (session, mut driver) = futures::executor::block_on(client.connect(runtime.now(), fake.clone())).unwrap();
1334		fake.state
1335			.panic_on_poll
1336			.store(true, std::sync::atomic::Ordering::Relaxed);
1337		let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1338			let _ = driver.poll(runtime.now(), &kio::Waiter::noop());
1339		}));
1340		assert!(panic.is_err(), "the owner must still receive the panic");
1341		assert!(matches!(
1342			futures::FutureExt::now_or_never(session.closed()),
1343			Some(Error::Transport(message)) if message == "session driver panicked"
1344		));
1345		// Even a caller that catches the panic cannot resume the damaged session.
1346		assert!(matches!(
1347			driver.poll(runtime.now(), &kio::Waiter::noop()),
1348			Err(Error::Transport(_))
1349		));
1350		drop(driver); // outside unwinding, as an executor's catch_unwind drops a failed future
1351		assert!(matches!(
1352			futures::executor::block_on(session.closed()),
1353			Error::Transport(_)
1354		));
1355	}
1356
1357	// `stats()` reads the machine's latest sample and primes the sampler, so a
1358	// periodic poller observes fresh counters without consuming the bandwidth
1359	// channel.
1360	#[kio::test]
1361	async fn stats_reads_prime_the_sampler() {
1362		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
1363		fake.set_send_rate(Some(1_000_000));
1364
1365		let client = Client::new().with_versions(Version::lite(lite::Version::Lite04).into());
1366		let (session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap();
1367		kio::clock::sim::spawn(crate::time::run(driver));
1368
1369		// The construction-time snapshot, before the machine sampled anything.
1370		assert_eq!(
1371			session.stats().estimated_send_rate,
1372			Some(crate::bandwidth::Rate::from_bps(1_000_000))
1373		);
1374
1375		// That read was demand: the machine keeps sampling while stats are read,
1376		// so the new rate shows up within an interval (paused time auto-advances).
1377		fake.set_send_rate(Some(2_000_000));
1378		while session.stats().estimated_send_rate != Some(crate::bandwidth::Rate::from_bps(2_000_000)) {
1379			kio::clock::sleep(std::time::Duration::from_millis(10)).await;
1380		}
1381	}
1382
1383	// Sampling stops when the supervisor ends, but `stats()` keeps serving its
1384	// cell, so the last thing the supervisor does is take a final snapshot.
1385	// Without one, "what did that session move?" asked at teardown answers with
1386	// the construction-time snapshot: this backend reports no send rate, so
1387	// there is no bandwidth consumer keeping the sampler ticking, and the test
1388	// never reads stats while the session is live.
1389	#[kio::test]
1390	async fn stats_capture_the_final_counters() {
1391		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
1392		fake.set_send_rate(None);
1393		fake.set_sent_bytes(0);
1394
1395		let client = Client::new().with_versions(Version::lite(lite::Version::Lite04).into());
1396		let (session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap();
1397		kio::clock::sim::spawn(crate::time::run(driver));
1398		assert!(
1399			session.send_bandwidth().is_none(),
1400			"no send-rate estimate, so nothing samples on its own"
1401		);
1402
1403		fake.set_sent_bytes(4242);
1404
1405		session.abort(Error::Cancel);
1406		session.closed().await;
1407
1408		assert_eq!(
1409			session.stats().bytes_sent,
1410			Some(4242),
1411			"the closing snapshot must carry the session's final counters"
1412		);
1413	}
1414
1415	// The send-bandwidth sampler lives inside the driver: it samples as soon as a
1416	// consumer exists and keeps sampling on its interval. Simulated time makes
1417	// the interval fire deterministically.
1418	#[kio::test]
1419	async fn send_bandwidth_samples_while_the_driver_runs() {
1420		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
1421		fake.set_send_rate(Some(1_000_000));
1422
1423		let client = Client::new().with_versions(Version::lite(lite::Version::Lite04).into());
1424		let (session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap();
1425		let mut bandwidth = session.send_bandwidth().expect("backend reports an estimate");
1426		assert_eq!(
1427			bandwidth.peek(),
1428			Some(crate::bandwidth::Rate::from_bps(1_000_000)),
1429			"the estimate is readable before the sampler first runs"
1430		);
1431		kio::clock::sim::spawn(crate::time::run(driver));
1432
1433		assert_eq!(
1434			bandwidth.changed().await.unwrap(),
1435			Some(crate::bandwidth::Rate::from_bps(1_000_000))
1436		);
1437
1438		// A later change is picked up by the next interval tick.
1439		fake.set_send_rate(Some(2_000_000));
1440		assert_eq!(
1441			bandwidth.changed().await.unwrap(),
1442			Some(crate::bandwidth::Rate::from_bps(2_000_000))
1443		);
1444	}
1445
1446	/// A track to reserve against, with the broadcast keeping it alive.
1447	fn reservable() -> (crate::broadcast::Producer, crate::track::Producer) {
1448		let broadcast = crate::broadcast::Info::default().produce();
1449		let track = broadcast.create_track("t", crate::track::Info::timed()).unwrap();
1450		(broadcast, track)
1451	}
1452
1453	/// Run the driver until the sender's target reads `bps`.
1454	async fn probes_to(fake: &FakeSession, bps: u64) {
1455		while fake.probe_target() != bps {
1456			kio::clock::sleep(std::time::Duration::from_millis(1)).await;
1457		}
1458	}
1459
1460	// The session probes for every reservation on its allocator, demanded or not: a
1461	// stopped rendition loses its viewers, and still has to be funded to resume.
1462	#[kio::test]
1463	async fn the_sender_probes_to_the_reservations() {
1464		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new()).with_probe();
1465		fake.set_send_rate(Some(1_000_000));
1466
1467		let client = Client::new().with_versions(Version::lite(lite::Version::Lite04).into());
1468		let (session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap();
1469		kio::clock::sim::spawn(crate::time::run(driver));
1470		let bandwidth = session.allocator();
1471
1472		let (_watched_broadcast, watched) = reservable();
1473		let _sub = watched.subscribe(None);
1474		let watched = bandwidth.reserve(&watched.demand(), crate::bandwidth::Rate::from_bps(4_000_000));
1475		probes_to(&fake, 4_000_000).await;
1476
1477		let (_idle_broadcast, idle) = reservable();
1478		let idle = bandwidth.reserve(&idle.demand(), crate::bandwidth::Rate::from_bps(1_000_000));
1479		probes_to(&fake, 5_000_000).await;
1480
1481		idle.update(crate::bandwidth::Rate::from_bps(2_000_000));
1482		probes_to(&fake, 6_000_000).await;
1483
1484		drop(watched);
1485		probes_to(&fake, 2_000_000).await;
1486		drop(idle);
1487		probes_to(&fake, 0).await;
1488	}
1489
1490	// An override replaces the sum, zero turns probing off, and clearing it follows the
1491	// reservations again.
1492	#[kio::test]
1493	async fn an_override_replaces_the_reservations() {
1494		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new()).with_probe();
1495		let client = Client::new().with_versions(Version::lite(lite::Version::Lite04).into());
1496		let (session, driver) = client.connect(kio::clock::now(), fake.clone()).await.unwrap();
1497		kio::clock::sim::spawn(crate::time::run(driver));
1498		let bandwidth = session.allocator();
1499
1500		let (_broadcast, track) = reservable();
1501		let _reserved = bandwidth.reserve(&track.demand(), crate::bandwidth::Rate::from_bps(4_000_000));
1502		probes_to(&fake, 4_000_000).await;
1503
1504		bandwidth.set_target(Some(crate::bandwidth::Rate::ZERO));
1505		probes_to(&fake, 0).await;
1506
1507		bandwidth.set_target(Some(crate::bandwidth::Rate::from_bps(10_000_000)));
1508		probes_to(&fake, 10_000_000).await;
1509
1510		bandwidth.set_target(None);
1511		probes_to(&fake, 4_000_000).await;
1512	}
1513
1514	// A reconnecting caller dials every session with one allocator, so a reservation
1515	// taken before the reconnect still moves the next session's target.
1516	#[kio::test]
1517	async fn a_reconnect_keeps_following_the_reservations() {
1518		let bandwidth = crate::bandwidth::Allocator::default();
1519		let client = Client::new()
1520			.with_versions(Version::lite(lite::Version::Lite04).into())
1521			.with_allocator(bandwidth.clone());
1522
1523		let (_broadcast, track) = reservable();
1524		let reserved = bandwidth.reserve(&track.demand(), crate::bandwidth::Rate::from_bps(4_000_000));
1525
1526		let first = FakeSession::new(Some(ALPN_LITE_04), Vec::new()).with_probe();
1527		let (session, driver) = client.connect(kio::clock::now(), first.clone()).await.unwrap();
1528		kio::clock::sim::spawn(crate::time::run(driver));
1529		probes_to(&first, 4_000_000).await;
1530		session.abort(Error::Cancel);
1531		session.closed().await;
1532		drop(session);
1533
1534		let second = FakeSession::new(Some(ALPN_LITE_04), Vec::new()).with_probe();
1535		let (_session, driver) = client.connect(kio::clock::now(), second.clone()).await.unwrap();
1536		kio::clock::sim::spawn(crate::time::run(driver));
1537		probes_to(&second, 4_000_000).await;
1538
1539		reserved.update(crate::bandwidth::Rate::from_bps(3_000_000));
1540		probes_to(&second, 3_000_000).await;
1541		assert_eq!(
1542			first.probe_target(),
1543			4_000_000,
1544			"a closed session's sender is left alone"
1545		);
1546	}
1547}