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_cluster: 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_cluster: 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_cluster: 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		let parameters = parameters.encode_bytes(ietf_encoding)?;
367
368		let client = setup::Client {
369			versions: supported.clone().into(),
370			parameters,
371		};
372
373		stream.writer.encode(&client).await?;
374
375		let mut server: setup::Server = stream.reader.decode().await?;
376
377		let version = supported
378			.iter()
379			.find(|v| coding::Version::from(**v) == server.version)
380			.copied()
381			.ok_or(Error::Version)?;
382
383		let (recv_bw, protocol, connecting) = match version {
384			Version::Lite(v) => {
385				let stream = stream.with_version(v);
386				let start = lite::start(lite::Config {
387					session: session.clone(),
388					setup_stream: Some(stream),
389					publish: publish.clone(),
390					subscribe: subscribe.clone(),
391					peer_origin: self.peer_origin,
392					version: v,
393					// This path only handles versions negotiated via the bidi SETUP exchange
394					// (pre-lite-05), which have no Setup Stream.
395					our_setup: lite::Setup::default(),
396					peer_setup: None,
397				})?;
398
399				(start.recv_bandwidth, start.driver, Some(start.connecting))
400			}
401			Version::Ietf(v) => {
402				// Decode the parameters to get the initial request ID.
403				let parameters = ietf::Parameters::decode(&mut server.parameters, v)?;
404				let request_id_max = parameters
405					.get_varint(ietf::ParameterVarInt::MaxRequestId)
406					.map(ietf::RequestId);
407
408				let stream = stream.with_version(v);
409				// Draft 14-16: the path rode in the bidi SETUP above, not the uni one.
410				let protocol = ietf::start(ietf::Config {
411					session: session.clone(),
412					setup: Some(stream),
413					request_id_max,
414					client: true,
415					publish: publish.clone(),
416					subscribe: subscribe.clone(),
417					peer_origin: self.peer_origin,
418					cost: self.cost,
419					version: v,
420					path: None,
421					peer_setup_stream: None,
422					peer_cluster: None,
423				})?;
424				(None, protocol, None)
425			}
426		};
427
428		let (session, mut driver) = Session::new(session, version, recv_bw, protocol);
429		if let Some(connecting) = connecting {
430			// Block until the initial announce set has landed (for versions that
431			// report one); resolves immediately otherwise.
432			driver.wait_ready(|waiter| connecting.poll_ready(waiter)).await;
433		}
434
435		Ok((session, driver))
436	}
437}
438
439#[cfg(test)]
440mod tests {
441	use super::*;
442	use std::{
443		collections::VecDeque,
444		sync::{Arc, Mutex},
445	};
446
447	use crate::coding::{Decode, Encode};
448	use bytes::{BufMut, Bytes};
449
450	#[derive(Debug, Clone, Default)]
451	struct FakeError;
452
453	impl std::fmt::Display for FakeError {
454		fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
455			write!(f, "fake transport error")
456		}
457	}
458
459	impl std::error::Error for FakeError {}
460
461	impl web_transport_trait::Error for FakeError {
462		fn session_error(&self) -> Option<(u32, String)> {
463			Some((0, "closed".to_string()))
464		}
465	}
466
467	#[derive(Clone, Default)]
468	struct FakeSession {
469		state: Arc<FakeSessionState>,
470	}
471
472	#[derive(Default)]
473	struct FakeSessionState {
474		protocol: Option<&'static str>,
475		control_stream: Mutex<Option<(FakeSendStream, FakeRecvStream)>>,
476		close_events: Mutex<Vec<(u32, String)>>,
477		close_notify: tokio::sync::Notify,
478		control_writes: Arc<Mutex<Vec<u8>>>,
479		send_rate: Mutex<Option<u64>>,
480	}
481
482	impl FakeSession {
483		fn new(protocol: Option<&'static str>, server_control_bytes: Vec<u8>) -> Self {
484			let writes = Arc::new(Mutex::new(Vec::new()));
485			let send = FakeSendStream { writes: writes.clone() };
486			let recv = FakeRecvStream {
487				data: VecDeque::from(server_control_bytes),
488			};
489			let state = FakeSessionState {
490				protocol,
491				control_stream: Mutex::new(Some((send, recv))),
492				close_events: Mutex::new(Vec::new()),
493				close_notify: tokio::sync::Notify::new(),
494				control_writes: writes,
495				send_rate: Mutex::new(None),
496			};
497			Self { state: Arc::new(state) }
498		}
499
500		fn set_send_rate(&self, rate: Option<u64>) {
501			*self.state.send_rate.lock().unwrap() = rate;
502		}
503
504		fn control_writes(&self) -> Vec<u8> {
505			self.state.control_writes.lock().unwrap().clone()
506		}
507
508		async fn wait_for_first_close(&self) -> (u32, String) {
509			loop {
510				let notified = self.state.close_notify.notified();
511				if let Some(close) = self.state.close_events.lock().unwrap().first().cloned() {
512					return close;
513				}
514				notified.await;
515			}
516		}
517	}
518
519	impl web_transport_trait::Session for FakeSession {
520		type SendStream = FakeSendStream;
521		type RecvStream = FakeRecvStream;
522		type Error = FakeError;
523
524		async fn accept_uni(&self) -> Result<Self::RecvStream, Self::Error> {
525			std::future::pending().await
526		}
527
528		async fn accept_bi(&self) -> Result<(Self::SendStream, Self::RecvStream), Self::Error> {
529			std::future::pending().await
530		}
531
532		async fn open_bi(&self) -> Result<(Self::SendStream, Self::RecvStream), Self::Error> {
533			self.state.control_stream.lock().unwrap().take().ok_or(FakeError)
534		}
535
536		async fn open_uni(&self) -> Result<Self::SendStream, Self::Error> {
537			std::future::pending().await
538		}
539
540		fn send_datagram(&self, _payload: Bytes) -> Result<(), Self::Error> {
541			Ok(())
542		}
543
544		async fn recv_datagram(&self) -> Result<Bytes, Self::Error> {
545			std::future::pending().await
546		}
547
548		fn max_datagram_size(&self) -> usize {
549			1200
550		}
551
552		fn protocol(&self) -> Option<&str> {
553			self.state.protocol
554		}
555
556		fn close(&self, code: u32, reason: &str) {
557			self.state.close_events.lock().unwrap().push((code, reason.to_string()));
558			self.state.close_notify.notify_waiters();
559		}
560
561		async fn closed(&self) -> Self::Error {
562			loop {
563				let notified = self.state.close_notify.notified();
564				if !self.state.close_events.lock().unwrap().is_empty() {
565					return FakeError;
566				}
567				notified.await;
568			}
569		}
570
571		fn stats(&self) -> impl web_transport_trait::Stats {
572			FakeStats {
573				send_rate: *self.state.send_rate.lock().unwrap(),
574			}
575		}
576	}
577
578	struct FakeStats {
579		send_rate: Option<u64>,
580	}
581
582	impl web_transport_trait::Stats for FakeStats {
583		fn estimated_send_rate(&self) -> Option<u64> {
584			self.send_rate
585		}
586	}
587
588	#[derive(Clone, Default)]
589	struct FakeSendStream {
590		writes: Arc<Mutex<Vec<u8>>>,
591	}
592
593	impl web_transport_trait::SendStream for FakeSendStream {
594		type Error = FakeError;
595
596		async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
597			self.writes.lock().unwrap().put_slice(buf);
598			Ok(buf.len())
599		}
600
601		fn set_priority(&mut self, _order: u8) {}
602
603		fn finish(&mut self) -> Result<(), Self::Error> {
604			Ok(())
605		}
606
607		fn reset(&mut self, _code: u32) {}
608
609		async fn closed(&mut self) -> Result<(), Self::Error> {
610			Ok(())
611		}
612	}
613
614	struct FakeRecvStream {
615		data: VecDeque<u8>,
616	}
617
618	impl web_transport_trait::RecvStream for FakeRecvStream {
619		type Error = FakeError;
620
621		async fn read(&mut self, dst: &mut [u8]) -> Result<Option<usize>, Self::Error> {
622			if self.data.is_empty() {
623				return Ok(None);
624			}
625
626			let size = dst.len().min(self.data.len());
627			for slot in dst.iter_mut().take(size) {
628				*slot = self.data.pop_front().unwrap();
629			}
630			Ok(Some(size))
631		}
632
633		fn stop(&mut self, _code: u32) {}
634
635		async fn closed(&mut self) -> Result<(), Self::Error> {
636			Ok(())
637		}
638	}
639
640	fn mock_server_setup(negotiated: Version) -> Vec<u8> {
641		let mut encoded = Vec::new();
642		let server = setup::Server {
643			version: negotiated.into(),
644			parameters: Bytes::new(),
645		};
646		server
647			.encode(&mut encoded, Version::Ietf(ietf::Version::Draft14))
648			.unwrap();
649
650		// Add a setup-stream SessionInfo frame using the negotiated Lite version.
651		let info = lite::SessionInfo { bitrate: Some(1) };
652		let lite_v = lite::Version::try_from(negotiated).unwrap();
653		info.encode(&mut encoded, lite_v).unwrap();
654
655		encoded
656	}
657
658	async fn run_alpn_lite_fallback_case(protocol: Option<&'static str>) {
659		let fake = FakeSession::new(protocol, mock_server_setup(Version::Lite(lite::Version::Lite01)));
660		let client = Client::new().with_versions(
661			[
662				Version::Lite(lite::Version::Lite03),
663				Version::Lite(lite::Version::Lite02),
664				Version::Lite(lite::Version::Lite01),
665				Version::Ietf(ietf::Version::Draft14),
666			]
667			.into(),
668		);
669
670		let _connection = client.connect(fake.clone()).await.unwrap();
671
672		// Verify the client setup was encoded using Draft14 framing (ALPN_LITE fallback path).
673		let mut setup_bytes = Bytes::from(fake.control_writes());
674		let setup = setup::Client::decode(&mut setup_bytes, Version::Ietf(ietf::Version::Draft14)).unwrap();
675		let advertised: Vec<Version> = setup.versions.iter().map(|v| Version::try_from(*v).unwrap()).collect();
676		assert_eq!(
677			advertised,
678			vec![
679				Version::Lite(lite::Version::Lite02),
680				Version::Lite(lite::Version::Lite01),
681				Version::Ietf(ietf::Version::Draft14),
682			]
683		);
684
685		// The first close comes from the lite connection driver.
686		// Any non-Version error here means SessionInfo decoded successfully
687		// after set_version(). This test cares about the SETUP framing
688		// fallback, not the specific close code. Cancel is what we'd see
689		// with no origin; RequiredExtension (or similar) is what an
690		// auto-created origin's first interaction with a Lite01 peer trips.
691		let (code, _) = fake.wait_for_first_close().await;
692		assert_ne!(code, Error::Version.to_code(), "SessionInfo failed to decode");
693	}
694
695	#[tokio::test(start_paused = true)]
696	async fn alpn_lite_falls_back_to_draft14_and_switches_version_post_setup() {
697		run_alpn_lite_fallback_case(Some(ALPN_LITE)).await;
698	}
699
700	#[tokio::test(start_paused = true)]
701	async fn no_alpn_falls_back_to_draft14_and_switches_version_post_setup() {
702		run_alpn_lite_fallback_case(None).await;
703	}
704
705	// This fake reports no send-rate estimate, so it never reaches the tokio timer in
706	// the bandwidth loop. A driver is NOT runtime-free in general; see the Async
707	// docs in lib.rs.
708	//
709	// The driver must hold no Session clone (the #2286 leak), so the transport still
710	// closes when the caller drops their last session handle, which is what lets a
711	// spawned driver task finish.
712	#[test]
713	fn driver_is_caller_polled_and_holds_no_session() {
714		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
715		let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into());
716
717		let (session, mut driver) = futures::executor::block_on(client.connect(fake.clone())).unwrap();
718		assert_eq!(session.version(), Version::Lite(lite::Version::Lite04));
719
720		// An arbitrary waiter drives it kio-style: nothing was spawned onto a runtime.
721		assert!(driver.poll(&kio::Waiter::noop()).is_pending());
722
723		// The driver is also a plain future (stand in for spawning it).
724		let mut context = std::task::Context::from_waker(std::task::Waker::noop());
725		assert!(std::future::Future::poll(std::pin::Pin::new(&mut driver), &mut context).is_pending());
726
727		// The caller drops their only session clone, so the transport closes even
728		// though the driver is still alive.
729		drop(session);
730		assert_eq!(fake.state.close_events.lock().unwrap()[0].0, Error::Cancel.to_code());
731	}
732
733	// Clones share the connection: the transport closes on the LAST drop, and
734	// abort() closes it explicitly (first close wins).
735	#[test]
736	fn session_clones_share_the_close() {
737		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
738		let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into());
739
740		let (session, _driver) = futures::executor::block_on(client.connect(fake.clone())).unwrap();
741		let clone = session.clone();
742
743		// One clone dropping does nothing while another is alive.
744		drop(session);
745		assert!(fake.state.close_events.lock().unwrap().is_empty());
746
747		clone.abort(Error::Cancel);
748		assert_eq!(fake.state.close_events.lock().unwrap()[0].0, Error::Cancel.to_code());
749
750		// The final drop is a no-op thanks to close-once.
751		drop(clone);
752		assert_eq!(fake.state.close_events.lock().unwrap().len(), 1);
753	}
754
755	// The send-bandwidth sampler lives inside the driver: it samples as soon as a
756	// consumer exists and keeps sampling on its interval. Paused tokio time makes
757	// the interval fire deterministically.
758	#[tokio::test(start_paused = true)]
759	async fn send_bandwidth_samples_while_the_driver_runs() {
760		let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new());
761		fake.set_send_rate(Some(1_000_000));
762
763		let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into());
764		let (session, driver) = client.connect(fake.clone()).await.unwrap();
765		tokio::spawn(driver);
766
767		let mut bandwidth = session.send_bandwidth().expect("backend reports an estimate");
768		assert_eq!(bandwidth.changed().await.unwrap(), Some(1_000_000));
769
770		// A later change is picked up by the next interval tick.
771		fake.set_send_rate(Some(2_000_000));
772		assert_eq!(bandwidth.changed().await.unwrap(), Some(2_000_000));
773	}
774}