Skip to main content

moq_net/
client.rs

1use crate::origin;
2use crate::{
3	ALPN_14, ALPN_15, ALPN_16, ALPN_17, ALPN_18, ALPN_19, ALPN_LITE, ALPN_LITE_03, ALPN_LITE_04, ALPN_LITE_05,
4	ALPN_LITE_06_WIP, Consume, Driver, Error, NEGOTIATED, Session, Version, Versions,
5	coding::{self, Decode, Encode, Stream},
6	ietf, lite, setup, stats,
7};
8
9/// A MoQ client session builder.
10#[derive(Default, Clone)]
11pub struct Client {
12	publish: Option<origin::Consumer>,
13	subscribe: Option<origin::Producer>,
14	stats: stats::Session,
15	versions: Versions,
16	setup_path: Option<String>,
17	cost: Option<u64>,
18	peer_origin: Option<crate::Origin>,
19}
20
21impl Client {
22	/// A client that neither publishes nor subscribes until configured.
23	pub fn new() -> Self {
24		Default::default()
25	}
26
27	/// Publish local broadcasts to the remote: the session reads from the given
28	/// origin (pass an [`origin::Producer`] or [`origin::Consumer`] by reference) and
29	/// forwards its announcements. Omit to publish nothing.
30	pub fn with_publisher(mut self, publish: impl Consume<origin::Consumer>) -> Self {
31		self.publish = Some(publish.consume());
32		self
33	}
34
35	/// Subscribe to remote broadcasts: the session writes the broadcasts the
36	/// remote announces into this [`origin::Producer`]. Omit to subscribe to nothing.
37	pub fn with_subscriber(mut self, subscribe: origin::Producer) -> Self {
38		self.subscribe = Some(subscribe);
39		self
40	}
41
42	/// Attach a per-connection [`stats::Session`] context. The session's publish
43	/// (egress) and subscribe (ingress) origin handles are tagged with it, so all
44	/// traffic counters are attributed through the model for this session's lifetime.
45	/// Pass [`stats::Session::default`] (a no-op context) to opt out.
46	pub fn with_stats(mut self, stats: stats::Session) -> Self {
47		self.stats = stats;
48		self
49	}
50
51	/// Set both publish and subscribe from one shared [`origin::Producer`].
52	///
53	/// Equivalent to [`with_publisher`](Self::with_publisher) and
54	/// [`with_subscriber`](Self::with_subscriber) with the same origin.
55	pub fn with_origin(self, origin: origin::Producer) -> Self {
56		self.with_publisher(&origin).with_subscriber(origin)
57	}
58
59	/// Restrict which protocol versions to offer, in preference order.
60	/// Defaults to every version this crate supports.
61	pub fn with_versions(mut self, versions: Versions) -> Self {
62		self.versions = versions;
63		self
64	}
65
66	/// Set the request path to advertise in the SETUP (moq-lite-05 and every
67	/// moq-transport draft we speak).
68	///
69	/// Only for transports that carry no request URI of their own (native QUIC, qmux
70	/// over TCP/TLS, unix sockets), so the server learns which path the client wants.
71	/// Append `?` and the URI query when there is one: that is how a credential in the
72	/// query (`?jwt=`) reaches the server.
73	/// Bindings that already carry a URI (WebTransport, qmux over WebSocket) convey
74	/// the path there and MUST NOT send this; a server is entitled to treat it as a
75	/// protocol violation. An empty path is equivalent to omitting it. Ignored by
76	/// versions with no in-band request path (lite 01-04).
77	pub fn with_path(mut self, path: impl Into<String>) -> Self {
78		self.setup_path = Some(path.into());
79		self
80	}
81
82	/// Price this link, in the units the rest of the mesh uses (moq-lite-06+, and
83	/// `moqt-17`+ via the MoQ Cluster extension).
84	///
85	/// The dialer is the side that knows what a link costs, because it chose the peer:
86	/// use `0` for a sibling in the same datacenter and something large for another
87	/// region across a metered backbone. So this prices both directions. We add it to
88	/// the route cost of every announcement the peer sends us, and declare it in our
89	/// SETUP so the peer adds it to every announcement we send, which is what a server
90	/// accepting an anonymous connection needs: it cannot tell a sibling from a
91	/// stranger, so it has no price of its own to apply.
92	///
93	/// A price the peer declares applies only where we set none. An unpriced link costs
94	/// `1`, which makes the cost track the hop count and so reproduces plain
95	/// shortest-path routing.
96	pub fn with_cost(mut self, cost: u64) -> Self {
97		self.cost = Some(cost);
98		self
99	}
100
101	/// Assign an origin (hop) id to the peer, used whenever the peer doesn't declare
102	/// one itself.
103	///
104	/// Some relays never declare their identity: moq-lite peers without the hops
105	/// extension, and moq-transport peers that don't negotiate the MoQ Cluster
106	/// extension (or predate it, on `moqt-16` and earlier).
107	/// Broadcasts received from such a peer are normally attributed to the reserved
108	/// origin 0 ("unknown"), which identifies nothing: it never proves continuity,
109	/// so their advertisements neither splice nor survive a restart in place. This
110	/// knob pins a real identity instead, exactly as if the peer had declared it:
111	///
112	/// - broadcasts received from the peer carry `origin` in their hop chains, so
113	///   every session dialing the same relay (with the same id) resolves to one
114	///   route and loop checks can recognize it;
115	/// - broadcasts whose hop chain already contains `origin` are neither announced
116	///   nor served back to the peer, preventing an echo through a relay that does
117	///   no loop detection of its own.
118	///
119	/// An identity the peer does declare wins over this one.
120	pub fn with_peer_origin(mut self, origin: crate::Origin) -> Self {
121		self.peer_origin = Some(origin);
122		self
123	}
124
125	/// Perform the MoQ handshake, returning the [`Session`] and the [`Driver`] that
126	/// runs its protocol work. The driver must be polled (spawned or awaited) for
127	/// the session to make progress.
128	pub async fn connect<S: web_transport_trait::Session>(&self, session: S) -> Result<(Session, Driver), Error> {
129		if self.publish.is_none() && self.subscribe.is_none() {
130			tracing::warn!("not publishing or consuming anything");
131		}
132
133		// Tag the origin pair with the stats context: reads through the publish
134		// (egress) consumer and writes through the subscribe (ingress) producer are
135		// then attributed by the model. One shared context, so presence and viewer
136		// counts are never double-attributed across the two halves.
137		let publish = self.publish.clone().map(|origin| origin.with_stats(self.stats.clone()));
138		let subscribe = self
139			.subscribe
140			.clone()
141			.map(|origin| origin.with_stats(self.stats.clone()));
142
143		// An assigned peer identity means subscriptions from the peer resolve to a
144		// source whose hop chain excludes it, the same split-horizon rule applied
145		// when a peer declares its own id. Announce filtering is per-protocol and
146		// handled inside each publisher.
147		let publish = match self.peer_origin {
148			Some(peer) => publish.map(|origin| origin.excluding(peer)),
149			None => publish,
150		};
151
152		// If ALPN was used to negotiate the version, use the appropriate encoding.
153		// Default to IETF 14 if no ALPN was used and we'll negotiate the version later.
154		let (encoding, supported) = match session.protocol() {
155			Some(ALPN_19) => {
156				let v = self
157					.versions
158					.select(Version::Ietf(ietf::Version::Draft19))
159					.ok_or(Error::Version)?;
160
161				// Draft-17+: SETUP is exchanged by the connection driver.
162				let protocol = ietf::start(ietf::Config {
163					session: session.clone(),
164					setup: None,
165					request_id_max: None,
166					client: true,
167					publish: publish.clone(),
168					subscribe: subscribe.clone(),
169					peer_origin: self.peer_origin,
170					cost: self.cost,
171					version: ietf::Version::Draft19,
172					path: self.setup_path.clone(),
173					peer_setup_stream: None,
174					peer_declared: None,
175				})?;
176
177				tracing::debug!(version = ?v, "connected");
178				return Ok(Session::new(session, v, None, protocol));
179			}
180			Some(ALPN_18) => {
181				let v = self
182					.versions
183					.select(Version::Ietf(ietf::Version::Draft18))
184					.ok_or(Error::Version)?;
185
186				// Draft-17+: SETUP is exchanged by the connection driver.
187				// We advertise the request path in our SETUP for URL-less transports.
188				let protocol = ietf::start(ietf::Config {
189					session: session.clone(),
190					setup: None,
191					request_id_max: None,
192					client: true,
193					publish: publish.clone(),
194					subscribe: subscribe.clone(),
195					peer_origin: self.peer_origin,
196					cost: self.cost,
197					version: ietf::Version::Draft18,
198					path: self.setup_path.clone(),
199					peer_setup_stream: None,
200					peer_declared: None,
201				})?;
202
203				tracing::debug!(version = ?v, "connected");
204				return Ok(Session::new(session, v, None, protocol));
205			}
206			Some(ALPN_17) => {
207				let v = self
208					.versions
209					.select(Version::Ietf(ietf::Version::Draft17))
210					.ok_or(Error::Version)?;
211
212				// Draft-17+: SETUP is exchanged by the connection driver.
213				// We advertise the request path in our SETUP for URL-less transports.
214				let protocol = ietf::start(ietf::Config {
215					session: session.clone(),
216					setup: None,
217					request_id_max: None,
218					client: true,
219					publish: publish.clone(),
220					subscribe: subscribe.clone(),
221					peer_origin: self.peer_origin,
222					cost: self.cost,
223					version: ietf::Version::Draft17,
224					path: self.setup_path.clone(),
225					peer_setup_stream: None,
226					peer_declared: None,
227				})?;
228
229				tracing::debug!(version = ?v, "connected");
230				return Ok(Session::new(session, v, None, protocol));
231			}
232			Some(ALPN_16) => {
233				let v = self
234					.versions
235					.select(Version::Ietf(ietf::Version::Draft16))
236					.ok_or(Error::Version)?;
237				(v, v.into())
238			}
239			Some(ALPN_15) => {
240				let v = self
241					.versions
242					.select(Version::Ietf(ietf::Version::Draft15))
243					.ok_or(Error::Version)?;
244				(v, v.into())
245			}
246			Some(ALPN_14) => {
247				let v = self
248					.versions
249					.select(Version::Ietf(ietf::Version::Draft14))
250					.ok_or(Error::Version)?;
251				(v, v.into())
252			}
253			Some(alpn @ (ALPN_LITE_05 | ALPN_LITE_06_WIP)) => {
254				let version = match alpn {
255					ALPN_LITE_06_WIP => lite::Version::Lite06Wip,
256					_ => lite::Version::Lite05,
257				};
258				self.versions.select(Version::Lite(version)).ok_or(Error::Version)?;
259
260				// Advertise our capabilities (we report send bitrate; we don't pad) plus
261				// the request path on URI-less transports, and the direction we intend to
262				// use so the server can reject a token that lacks the matching scope during
263				// the handshake instead of silently carrying no media.
264				let our_setup = lite::Setup {
265					probe: lite::ProbeLevel::Report,
266					path: self.setup_path.clone(),
267					role: lite::Role::from_origins(self.publish.is_some(), self.subscribe.is_some()),
268					cost: self.cost,
269					// Filled by `lite::start` from the attached origin handles.
270					origin: None,
271				};
272
273				let start = lite::start(lite::Config {
274					session: session.clone(),
275					setup_stream: None,
276					publish: publish.clone(),
277					subscribe: subscribe.clone(),
278					peer_origin: self.peer_origin,
279					version,
280					our_setup,
281					peer_setup: None,
282				})?;
283
284				// Block until the initial announce set has landed (Lite05+ reports it
285				// via AnnounceOk + N), so a `request_broadcast()` for a live path resolves
286				// immediately instead of racing announcement gossip.
287				let (session, mut driver) = Session::new(session, version.into(), start.recv_bandwidth, start.driver);
288				driver.wait_ready(|waiter| start.connecting.poll_ready(waiter)).await;
289
290				return Ok((session, driver));
291			}
292			Some(ALPN_LITE_04) => {
293				self.versions
294					.select(Version::Lite(lite::Version::Lite04))
295					.ok_or(Error::Version)?;
296
297				let start = lite::start(lite::Config {
298					session: session.clone(),
299					setup_stream: None,
300					publish: publish.clone(),
301					subscribe: subscribe.clone(),
302					peer_origin: self.peer_origin,
303					version: lite::Version::Lite04,
304					our_setup: lite::Setup::default(),
305					peer_setup: None,
306				})?;
307
308				// Lite04 has no initial-set boundary, so this resolves immediately.
309				let (session, mut driver) = Session::new(
310					session,
311					lite::Version::Lite04.into(),
312					start.recv_bandwidth,
313					start.driver,
314				);
315				driver.wait_ready(|waiter| start.connecting.poll_ready(waiter)).await;
316
317				return Ok((session, driver));
318			}
319			Some(ALPN_LITE_03) => {
320				self.versions
321					.select(Version::Lite(lite::Version::Lite03))
322					.ok_or(Error::Version)?;
323
324				// Starting with draft-03, there's no more SETUP control stream.
325				let start = lite::start(lite::Config {
326					session: session.clone(),
327					setup_stream: None,
328					publish: publish.clone(),
329					subscribe: subscribe.clone(),
330					peer_origin: self.peer_origin,
331					version: lite::Version::Lite03,
332					our_setup: lite::Setup::default(),
333					peer_setup: None,
334				})?;
335
336				// Lite03 has no initial-set boundary, so this resolves immediately.
337				let (session, mut driver) = Session::new(
338					session,
339					lite::Version::Lite03.into(),
340					start.recv_bandwidth,
341					start.driver,
342				);
343				driver.wait_ready(|waiter| start.connecting.poll_ready(waiter)).await;
344
345				return Ok((session, driver));
346			}
347			Some(ALPN_LITE) | None => {
348				let supported = self.versions.filter(&NEGOTIATED.into()).ok_or(Error::Version)?;
349				(Version::Ietf(ietf::Version::Draft14), supported)
350			}
351			Some(p) => return Err(Error::UnknownAlpn(p.to_string())),
352		};
353
354		let mut stream = Stream::open(&session, encoding).await?;
355
356		// The encoding is always an IETF version for SETUP negotiation.
357		let ietf_encoding = ietf::Version::try_from(encoding).map_err(|_| Error::Version)?;
358
359		let mut parameters = ietf::Parameters::default();
360		parameters.set_varint(ietf::ParameterVarInt::MaxRequestId, u32::MAX as u64);
361		parameters.set_bytes(ietf::ParameterBytes::Implementation, b"moq-lite-rs".to_vec());
362		// Advertise the request path in-band (draft 14-16), same as the lite-05 SETUP.
363		if let Some(path) = &self.setup_path {
364			parameters.set_bytes(ietf::ParameterBytes::Path, path.clone().into_bytes());
365		}
366		ietf::solicit::into_setup(&mut parameters, ietf_encoding);
367		let parameters = parameters.encode_bytes(ietf_encoding)?;
368
369		let client = setup::Client {
370			versions: supported.clone().into(),
371			parameters,
372		};
373
374		stream.writer.encode(&client).await?;
375
376		let mut server: setup::Server = stream.reader.decode().await?;
377
378		let version = supported
379			.iter()
380			.find(|v| coding::Version::from(**v) == server.version)
381			.copied()
382			.ok_or(Error::Version)?;
383
384		let (recv_bw, protocol, connecting) = match version {
385			Version::Lite(v) => {
386				let stream = stream.with_version(v);
387				let start = lite::start(lite::Config {
388					session: session.clone(),
389					setup_stream: Some(stream),
390					publish: publish.clone(),
391					subscribe: subscribe.clone(),
392					peer_origin: self.peer_origin,
393					version: v,
394					// This path only handles versions negotiated via the bidi SETUP exchange
395					// (pre-lite-05), which have no Setup Stream.
396					our_setup: lite::Setup::default(),
397					peer_setup: None,
398				})?;
399
400				(start.recv_bandwidth, start.driver, Some(start.connecting))
401			}
402			Version::Ietf(v) => {
403				// Decode the parameters to get the initial request ID and what the server
404				// requires of us.
405				let parameters = ietf::Parameters::decode(&mut server.parameters, v)?;
406				let request_id_max = parameters
407					.get_varint(ietf::ParameterVarInt::MaxRequestId)
408					.map(ietf::RequestId);
409				let peer_declared = ietf::peer::Peer {
410					solicit: ietf::solicit::from_setup(&parameters, v)?,
411					..Default::default()
412				};
413
414				let stream = stream.with_version(v);
415				// Draft 14-16: the path rode in the bidi SETUP above, not the uni one.
416				let protocol = ietf::start(ietf::Config {
417					session: session.clone(),
418					setup: Some(stream),
419					request_id_max,
420					client: true,
421					publish: publish.clone(),
422					subscribe: subscribe.clone(),
423					peer_origin: self.peer_origin,
424					cost: self.cost,
425					version: v,
426					path: None,
427					peer_setup_stream: None,
428					peer_declared: Some(peer_declared),
429				})?;
430				(None, protocol, None)
431			}
432		};
433
434		let (session, mut driver) = Session::new(session, version, recv_bw, protocol);
435		if let Some(connecting) = connecting {
436			// Block until the initial announce set has landed (for versions that
437			// report one); resolves immediately otherwise.
438			driver.wait_ready(|waiter| connecting.poll_ready(waiter)).await;
439		}
440
441		Ok((session, driver))
442	}
443}
444
445#[cfg(test)]
446mod tests {
447	use super::*;
448	use std::{
449		collections::VecDeque,
450		sync::{Arc, Mutex},
451	};
452
453	use crate::coding::{Decode, Encode};
454	use bytes::{BufMut, Bytes};
455
456	#[derive(Debug, Clone, Default)]
457	struct FakeError;
458
459	impl std::fmt::Display for FakeError {
460		fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
461			write!(f, "fake transport error")
462		}
463	}
464
465	impl std::error::Error for FakeError {}
466
467	impl web_transport_trait::Error for FakeError {
468		fn session_error(&self) -> Option<(u32, String)> {
469			Some((0, "closed".to_string()))
470		}
471	}
472
473	#[derive(Clone, Default)]
474	struct FakeSession {
475		state: Arc<FakeSessionState>,
476	}
477
478	#[derive(Default)]
479	struct FakeSessionState {
480		protocol: Option<&'static str>,
481		control_stream: Mutex<Option<(FakeSendStream, FakeRecvStream)>>,
482		close_events: Mutex<Vec<(u32, String)>>,
483		close_notify: tokio::sync::Notify,
484		control_writes: Arc<Mutex<Vec<u8>>>,
485		send_rate: Mutex<Option<u64>>,
486	}
487
488	impl FakeSession {
489		fn new(protocol: Option<&'static str>, server_control_bytes: Vec<u8>) -> Self {
490			let writes = Arc::new(Mutex::new(Vec::new()));
491			let send = FakeSendStream { writes: writes.clone() };
492			let recv = FakeRecvStream {
493				data: VecDeque::from(server_control_bytes),
494			};
495			let state = FakeSessionState {
496				protocol,
497				control_stream: Mutex::new(Some((send, recv))),
498				close_events: Mutex::new(Vec::new()),
499				close_notify: tokio::sync::Notify::new(),
500				control_writes: writes,
501				send_rate: Mutex::new(None),
502			};
503			Self { state: Arc::new(state) }
504		}
505
506		fn set_send_rate(&self, rate: Option<u64>) {
507			*self.state.send_rate.lock().unwrap() = rate;
508		}
509
510		fn control_writes(&self) -> Vec<u8> {
511			self.state.control_writes.lock().unwrap().clone()
512		}
513
514		async fn wait_for_first_close(&self) -> (u32, String) {
515			loop {
516				let notified = self.state.close_notify.notified();
517				if let Some(close) = self.state.close_events.lock().unwrap().first().cloned() {
518					return close;
519				}
520				notified.await;
521			}
522		}
523	}
524
525	impl web_transport_trait::Session for FakeSession {
526		type SendStream = FakeSendStream;
527		type RecvStream = FakeRecvStream;
528		type Error = FakeError;
529
530		async fn accept_uni(&self) -> Result<Self::RecvStream, Self::Error> {
531			std::future::pending().await
532		}
533
534		async fn accept_bi(&self) -> Result<(Self::SendStream, Self::RecvStream), Self::Error> {
535			std::future::pending().await
536		}
537
538		async fn open_bi(&self) -> Result<(Self::SendStream, Self::RecvStream), Self::Error> {
539			self.state.control_stream.lock().unwrap().take().ok_or(FakeError)
540		}
541
542		async fn open_uni(&self) -> Result<Self::SendStream, Self::Error> {
543			std::future::pending().await
544		}
545
546		fn send_datagram(&self, _payload: Bytes) -> Result<(), Self::Error> {
547			Ok(())
548		}
549
550		async fn recv_datagram(&self) -> Result<Bytes, Self::Error> {
551			std::future::pending().await
552		}
553
554		fn max_datagram_size(&self) -> usize {
555			1200
556		}
557
558		fn protocol(&self) -> Option<&str> {
559			self.state.protocol
560		}
561
562		fn close(&self, code: u32, reason: &str) {
563			self.state.close_events.lock().unwrap().push((code, reason.to_string()));
564			self.state.close_notify.notify_waiters();
565		}
566
567		async fn closed(&self) -> Self::Error {
568			loop {
569				let notified = self.state.close_notify.notified();
570				if !self.state.close_events.lock().unwrap().is_empty() {
571					return FakeError;
572				}
573				notified.await;
574			}
575		}
576
577		fn stats(&self) -> impl web_transport_trait::Stats {
578			FakeStats {
579				send_rate: *self.state.send_rate.lock().unwrap(),
580			}
581		}
582	}
583
584	struct FakeStats {
585		send_rate: Option<u64>,
586	}
587
588	impl web_transport_trait::Stats for FakeStats {
589		fn estimated_send_rate(&self) -> Option<u64> {
590			self.send_rate
591		}
592	}
593
594	#[derive(Clone, Default)]
595	struct FakeSendStream {
596		writes: Arc<Mutex<Vec<u8>>>,
597	}
598
599	impl web_transport_trait::SendStream for FakeSendStream {
600		type Error = FakeError;
601
602		async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
603			self.writes.lock().unwrap().put_slice(buf);
604			Ok(buf.len())
605		}
606
607		fn set_priority(&mut self, _order: u8) {}
608
609		fn finish(&mut self) -> Result<(), Self::Error> {
610			Ok(())
611		}
612
613		fn reset(&mut self, _code: u32) {}
614
615		async fn closed(&mut self) -> Result<(), Self::Error> {
616			Ok(())
617		}
618	}
619
620	struct FakeRecvStream {
621		data: VecDeque<u8>,
622	}
623
624	impl web_transport_trait::RecvStream for FakeRecvStream {
625		type Error = FakeError;
626
627		async fn read(&mut self, dst: &mut [u8]) -> Result<Option<usize>, Self::Error> {
628			if self.data.is_empty() {
629				return Ok(None);
630			}
631
632			let size = dst.len().min(self.data.len());
633			for slot in dst.iter_mut().take(size) {
634				*slot = self.data.pop_front().unwrap();
635			}
636			Ok(Some(size))
637		}
638
639		fn stop(&mut self, _code: u32) {}
640
641		async fn closed(&mut self) -> Result<(), Self::Error> {
642			Ok(())
643		}
644	}
645
646	fn mock_server_setup(negotiated: Version) -> Vec<u8> {
647		let mut encoded = Vec::new();
648		let server = setup::Server {
649			version: negotiated.into(),
650			parameters: Bytes::new(),
651		};
652		server
653			.encode(&mut encoded, Version::Ietf(ietf::Version::Draft14))
654			.unwrap();
655
656		// Add a setup-stream SessionInfo frame using the negotiated Lite version.
657		let info = lite::SessionInfo { bitrate: Some(1) };
658		let lite_v = lite::Version::try_from(negotiated).unwrap();
659		info.encode(&mut encoded, lite_v).unwrap();
660
661		encoded
662	}
663
664	async fn run_alpn_lite_fallback_case(protocol: Option<&'static str>) {
665		let fake = FakeSession::new(protocol, mock_server_setup(Version::Lite(lite::Version::Lite01)));
666		let client = Client::new().with_versions(
667			[
668				Version::Lite(lite::Version::Lite03),
669				Version::Lite(lite::Version::Lite02),
670				Version::Lite(lite::Version::Lite01),
671				Version::Ietf(ietf::Version::Draft14),
672			]
673			.into(),
674		);
675
676		let _connection = client.connect(fake.clone()).await.unwrap();
677
678		// Verify the client setup was encoded using Draft14 framing (ALPN_LITE fallback path).
679		let mut setup_bytes = Bytes::from(fake.control_writes());
680		let setup = setup::Client::decode(&mut setup_bytes, Version::Ietf(ietf::Version::Draft14)).unwrap();
681		let advertised: Vec<Version> = setup.versions.iter().map(|v| Version::try_from(*v).unwrap()).collect();
682		assert_eq!(
683			advertised,
684			vec![
685				Version::Lite(lite::Version::Lite02),
686				Version::Lite(lite::Version::Lite01),
687				Version::Ietf(ietf::Version::Draft14),
688			]
689		);
690
691		// The first close comes from the lite connection driver.
692		// Any non-Version error here means SessionInfo decoded successfully
693		// after set_version(). This test cares about the SETUP framing
694		// fallback, not the specific close code. Cancel is what we'd see
695		// with no origin; RequiredExtension (or similar) is what an
696		// auto-created origin's first interaction with a Lite01 peer trips.
697		let (code, _) = fake.wait_for_first_close().await;
698		assert_ne!(code, Error::Version.to_code(), "SessionInfo failed to decode");
699	}
700
701	#[tokio::test(start_paused = true)]
702	async fn alpn_lite_falls_back_to_draft14_and_switches_version_post_setup() {
703		run_alpn_lite_fallback_case(Some(ALPN_LITE)).await;
704	}
705
706	#[tokio::test(start_paused = true)]
707	async fn no_alpn_falls_back_to_draft14_and_switches_version_post_setup() {
708		run_alpn_lite_fallback_case(None).await;
709	}
710
711	// This fake reports no send-rate estimate, so it never reaches the tokio timer in
712	// the bandwidth loop. A driver is NOT runtime-free in general; see the Async
713	// docs in lib.rs.
714	//
715	// The driver must hold no Session clone (the #2286 leak), so the transport still
716	// closes when the caller drops their last session handle, which is what lets a
717	// spawned driver task finish.
718	#[test]
719	fn driver_is_caller_polled_and_holds_no_session() {
720		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
721		let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into());
722
723		let (session, mut driver) = futures::executor::block_on(client.connect(fake.clone())).unwrap();
724		assert_eq!(session.version(), Version::Lite(lite::Version::Lite04));
725
726		// An arbitrary waiter drives it kio-style: nothing was spawned onto a runtime.
727		assert!(driver.poll(&kio::Waiter::noop()).is_pending());
728
729		// The driver is also a plain future (stand in for spawning it).
730		let mut context = std::task::Context::from_waker(std::task::Waker::noop());
731		assert!(std::future::Future::poll(std::pin::Pin::new(&mut driver), &mut context).is_pending());
732
733		// The caller drops their only session clone, so the transport closes even
734		// though the driver is still alive.
735		drop(session);
736		assert_eq!(fake.state.close_events.lock().unwrap()[0].0, Error::Cancel.to_code());
737	}
738
739	// Clones share the connection: the transport closes on the LAST drop, and
740	// abort() closes it explicitly (first close wins).
741	#[test]
742	fn session_clones_share_the_close() {
743		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
744		let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into());
745
746		let (session, _driver) = futures::executor::block_on(client.connect(fake.clone())).unwrap();
747		let clone = session.clone();
748
749		// One clone dropping does nothing while another is alive.
750		drop(session);
751		assert!(fake.state.close_events.lock().unwrap().is_empty());
752
753		clone.abort(Error::Cancel);
754		assert_eq!(fake.state.close_events.lock().unwrap()[0].0, Error::Cancel.to_code());
755
756		// The final drop is a no-op thanks to close-once.
757		drop(clone);
758		assert_eq!(fake.state.close_events.lock().unwrap().len(), 1);
759	}
760
761	// The send-bandwidth sampler lives inside the driver: it samples as soon as a
762	// consumer exists and keeps sampling on its interval. Paused tokio time makes
763	// the interval fire deterministically.
764	#[tokio::test(start_paused = true)]
765	async fn send_bandwidth_samples_while_the_driver_runs() {
766		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
767		fake.set_send_rate(Some(1_000_000));
768
769		let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into());
770		let (session, driver) = client.connect(fake.clone()).await.unwrap();
771		tokio::spawn(driver);
772
773		let mut bandwidth = session.send_bandwidth().expect("backend reports an estimate");
774		assert_eq!(bandwidth.changed().await.unwrap(), Some(1_000_000));
775
776		// A later change is picked up by the next interval tick.
777		fake.set_send_rate(Some(2_000_000));
778		assert_eq!(bandwidth.changed().await.unwrap(), Some(2_000_000));
779	}
780}