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