Skip to main content

moq_native/
reconnect.rs

1use std::task::{Poll, ready};
2use std::time::Duration;
3
4use moq_net::Version;
5use moq_net::bandwidth::{Consumer as BandwidthConsumer, Producer as BandwidthProducer};
6use moq_net::kio;
7use rand::RngExt;
8use url::Url;
9
10use crate::{Client, Error, RedactedUrl};
11
12/// Exponential backoff configuration for reconnection attempts.
13///
14/// This decides how long to wait between reconnect attempts and when to give up. The delays carry
15/// jitter, so a fleet knocked offline together doesn't reconnect in lockstep.
16///
17/// [`timeout`](Self::timeout) is what ends a hopeless loop: every failure rides the same backoff,
18/// and the short default budget is what surfaces a broken target instead of hiding it. The only
19/// failures short-circuited are answers a server actually gave (an auth rejection, or a CONNECT
20/// status that isn't an invitation to retry). A zero timeout removes the backstop, so it belongs
21/// only where an unattended process must outlive an outage of any length.
22#[derive(Clone, Debug, clap::Args, serde::Serialize, serde::Deserialize)]
23#[serde(default, deny_unknown_fields)]
24#[non_exhaustive]
25pub struct Backoff {
26	/// Initial delay before first reconnect attempt.
27	#[arg(
28		id = "backoff-initial",
29		long,
30		default_value = "1s",
31		env = "MOQ_BACKOFF_INITIAL",
32		value_parser = humantime::parse_duration,
33	)]
34	#[serde(with = "humantime_serde")]
35	pub initial: Duration,
36
37	/// Multiplier applied to delay after each failure.
38	#[arg(id = "backoff-multiplier", long, default_value_t = 2, env = "MOQ_BACKOFF_MULTIPLIER")]
39	pub multiplier: u32,
40
41	/// Maximum delay between reconnect attempts.
42	#[arg(
43		id = "backoff-max",
44		long,
45		default_value = "5s",
46		env = "MOQ_BACKOFF_MAX",
47		value_parser = humantime::parse_duration,
48	)]
49	#[serde(with = "humantime_serde")]
50	pub max: Duration,
51
52	/// Maximum time to spend retrying before giving up.
53	/// Resets after a stable connection (one that outlives the initial backoff), so a flapping
54	/// session that reconnects then immediately drops still counts toward the timeout. Set to 0 for
55	/// unlimited retries.
56	#[arg(
57		id = "backoff-timeout",
58		long,
59		default_value = "10s",
60		env = "MOQ_BACKOFF_TIMEOUT",
61		value_parser = humantime::parse_duration,
62	)]
63	#[serde(with = "humantime_serde")]
64	pub timeout: Duration,
65}
66
67impl Default for Backoff {
68	fn default() -> Self {
69		Self {
70			initial: Duration::from_secs(1),
71			multiplier: 2,
72			max: Duration::from_secs(5),
73			timeout: Duration::from_secs(10),
74		}
75	}
76}
77
78impl Backoff {
79	/// Reject a backoff that would retry without pacing.
80	///
81	/// The loop sleeps `delay`, then `delay = min(delay * multiplier, max)`. A zero in
82	/// any of the three collapses that to zero forever, so a relay that is simply down
83	/// becomes a hot loop of dials and DNS lookups, unbounded when
84	/// [`timeout`](Self::timeout) is also zero. A zero `timeout` on its own is fine and
85	/// documented: it means retry forever, which is only a problem unpaced.
86	///
87	/// A `multiplier` of 1 is allowed: the delay stays at `initial`, which is a
88	/// constant-delay retry rather than an unpaced one.
89	pub(crate) fn validate(&self) -> crate::Result<()> {
90		match self.initial.is_zero() || self.multiplier == 0 || self.max.is_zero() {
91			true => Err(crate::Error::BackoffUnpaced),
92			false => Ok(()),
93		}
94	}
95
96	/// Grow the retry delay without overflowing before applying the configured cap.
97	fn next_delay(&self, delay: Duration) -> Duration {
98		delay.saturating_mul(self.multiplier.max(1)).min(self.max)
99	}
100
101	/// How long broadcasts fed by a reconnecting session should outlive a session
102	/// drop (see [`moq_net::origin::Info::linger`]): slightly past the give-up
103	/// [`timeout`](Self::timeout), so when the loop does give up its error surfaces
104	/// before the broadcasts tear down. A zero timeout retries forever, so the
105	/// broadcasts linger forever too.
106	pub fn linger(&self) -> Duration {
107		match self.timeout.is_zero() {
108			true => Duration::MAX,
109			false => self.timeout.saturating_add(Duration::from_secs(1)),
110		}
111	}
112}
113
114/// When a reconnect sequence gives up, or `None` when [`Backoff::timeout`] is zero and it never
115/// does. Measured from now, so it covers the connect attempts as well as the waits between them.
116fn deadline_from(backoff: &Backoff) -> Option<tokio::time::Instant> {
117	match backoff.timeout.is_zero() {
118		true => None,
119		false => Some(tokio::time::Instant::now() + backoff.timeout),
120	}
121}
122
123/// A connection lifecycle transition reported by [`Reconnect::status`].
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125#[non_exhaustive]
126pub enum Status {
127	/// A session connected (the first connect, or a reconnect after a drop).
128	Connected,
129	/// An established session dropped; a reconnect attempt follows.
130	Disconnected,
131}
132
133/// Shared reconnect state, observed by consumers through a [`kio`] channel.
134///
135/// The channel closing (all producers dropped) is the terminal signal; `error`
136/// distinguishes a permanent give-up from a graceful close.
137#[derive(Default)]
138struct State {
139	/// Current connection status, or `None` before the first connect.
140	status: Option<Status>,
141	/// The negotiated MoQ version of the live session, or `None` when disconnected.
142	version: Option<Version>,
143	/// Set when the reconnect loop permanently gives up: the backoff timeout expiring, or a server
144	/// answer that redialing cannot change.
145	error: Option<Error>,
146	/// The currently-connected session, or `None` while reconnecting. Read by
147	/// [`ConnectionStatsReader`] to snapshot live connection stats.
148	session: Option<moq_net::Session>,
149}
150
151/// Statistics and protocol sampled from the same live connection.
152#[non_exhaustive]
153pub struct ConnectionSnapshot {
154	/// Transport statistics at the time of the snapshot.
155	pub stats: moq_net::ConnectionStats,
156	/// Protocol negotiated by the connection that supplied these statistics.
157	pub version: Version,
158}
159
160/// A cloneable read handle for the live connection stats of a [`Reconnect`] loop.
161///
162/// Obtained via [`Reconnect::stats`]. [`stats`](Self::stats) returns `None` while the loop is
163/// between connections (reconnecting), and `Some` snapshot while a session is established.
164#[derive(Clone)]
165pub struct ConnectionStatsReader {
166	state: kio::Consumer<State>,
167}
168
169impl ConnectionStatsReader {
170	/// Snapshot the current connection's stats, or `None` if not currently connected.
171	pub fn stats(&self) -> Option<moq_net::ConnectionStats> {
172		self.state.read().session.as_ref().map(moq_net::Session::stats)
173	}
174
175	/// Snapshot statistics and protocol together, or `None` while disconnected.
176	pub fn snapshot(&self) -> Option<ConnectionSnapshot> {
177		let state = self.state.read();
178		let session = state.session.as_ref()?;
179		Some(ConnectionSnapshot {
180			stats: session.stats(),
181			version: session.version(),
182		})
183	}
184}
185
186/// Handle to a background reconnect loop.
187///
188/// Spawns a tokio task that connects, waits for session close, then reconnects with exponential
189/// backoff until [`Backoff::timeout`] runs out. This loop is the only retry owner for the connection:
190/// a caller that rebuilds it on failure restarts the backoff from its initial delay, which turns the
191/// escalation back into a tight loop. Watch [`closed`](Self::closed) instead.
192///
193/// The read surface mirrors [`moq_net::Session`] so a caller can treat it like a session
194/// that transparently reconnects: [`version`](Self::version), [`send_bandwidth`](Self::send_bandwidth),
195/// and [`recv_bandwidth`](Self::recv_bandwidth) track the live session and reset while disconnected.
196/// The extra toggle a plain session doesn't have is the connection lifecycle: [`connected`](Self::connected)
197/// reads it synchronously and [`status`](Self::status) waits for the next change. [`closed`](Self::closed)
198/// waits for the loop to stop. Dropping the handle aborts the background task.
199pub struct Reconnect {
200	abort: tokio::task::AbortHandle,
201	state: kio::Consumer<State>,
202	/// Persistent send-bitrate estimate, fed by the loop from each live session.
203	send_bandwidth: BandwidthConsumer,
204	/// Persistent recv-bitrate estimate, fed by the loop from each live session.
205	recv_bandwidth: BandwidthConsumer,
206	/// The last status returned by [`status`](Self::status), for change detection.
207	last_reported: Option<Status>,
208}
209
210impl Reconnect {
211	pub(crate) fn new(client: Client, url: Url, backoff: Backoff) -> Self {
212		let producer = kio::Producer::<State>::default();
213		let state = producer.consume();
214
215		// The loop feeds these across every reconnect, so a consumer's handle survives session churn
216		// (unlike a session's own bandwidth consumer, which dies with the session).
217		let send_bw = BandwidthProducer::new();
218		let recv_bw = BandwidthProducer::new();
219		let send_bandwidth = send_bw.consume();
220		let recv_bandwidth = recv_bw.consume();
221
222		let task = tokio::spawn(async move {
223			if let Err(err) = Self::run(&producer, &send_bw, &recv_bw, client, url, backoff).await {
224				tracing::error!(%err, "reconnect loop exited");
225				if let Ok(mut state) = producer.write() {
226					state.error = Some(err);
227				}
228			}
229			// Dropping the producers here closes the channels, signaling consumers.
230		});
231		Self {
232			abort: task.abort_handle(),
233			state,
234			send_bandwidth,
235			recv_bandwidth,
236			last_reported: None,
237		}
238	}
239
240	async fn run(
241		state: &kio::Producer<State>,
242		send_bw: &BandwidthProducer,
243		recv_bw: &BandwidthProducer,
244		client: Client,
245		url: Url,
246		backoff: Backoff,
247	) -> crate::Result<()> {
248		// The escalating wait between attempts, and the instant the give-up budget expires. Both
249		// restart after a session that stayed healthy, so a one-off drop reconnects promptly. A zero
250		// timeout means no deadline at all: retry for as long as the process lives.
251		let mut delay = backoff.initial;
252		let mut deadline = deadline_from(&backoff);
253		let mut last_error: Option<Error> = None;
254
255		// The dial target usually carries an auth token in its query, so every line
256		// below logs the redacted form.
257		let url_log = RedactedUrl::new(&url);
258
259		loop {
260			tracing::info!(url = %url_log, "connecting");
261
262			match client.connect(url.clone()).await {
263				Ok(session) => {
264					tracing::info!(url = %url_log, "connected");
265					if let Ok(mut state) = state.write() {
266						state.status = Some(Status::Connected);
267						state.version = Some(session.version());
268						state.session = Some(session.clone());
269					}
270
271					let connected = tokio::time::Instant::now();
272					// Wait for the session to close, forwarding its bandwidth estimates into the
273					// persistent producers meanwhile so consumers track the live stats across the connection.
274					let closed = run_session(send_bw, recv_bw, &session).await;
275					if let Ok(mut state) = state.write() {
276						state.status = Some(Status::Disconnected);
277						state.version = None;
278						state.session = None;
279					}
280					// The estimates belonged to the now-closed session; reset until the next connect.
281					let _ = send_bw.set(None);
282					let _ = recv_bw.set(None);
283
284					if connected.elapsed() >= backoff.initial {
285						// Stayed up past the initial backoff: a healthy session. Reset the backoff
286						// window so a one-off drop reconnects promptly.
287						tracing::warn!(url = %url_log, "session closed, reconnecting");
288						delay = backoff.initial;
289						deadline = deadline_from(&backoff);
290						last_error = None;
291					} else {
292						// Connected then dropped almost immediately (e.g. the server accepts then
293						// resets). Treat it as a failed connection: keep the close reason so the
294						// give-up timeout reports a real cause, and fall through to the shared backoff
295						// sleep below so repeated flaps escalate instead of spinning the CPU.
296						if let Err(err) = closed {
297							let err = Error::from(err);
298							tracing::warn!(url = %url_log, %err, "session severed immediately, retrying");
299							last_error = Some(err);
300						} else {
301							tracing::warn!(url = %url_log, "session severed immediately, retrying");
302						}
303					}
304				}
305				Err(err) => {
306					// The two answers a server can give that redialing cannot change: it rejected our
307					// credentials, or it answered the CONNECT with a status that isn't an invitation
308					// to come back. Everything else falls through to the backoff, whose budget is
309					// what stops the loop.
310					if err.is_auth() {
311						return Err(err);
312					}
313					if let Some(status) = err.status()
314						&& !crate::error::status_retryable(status)
315					{
316						return Err(err);
317					}
318					last_error = Some(err);
319				}
320			}
321
322			let now = tokio::time::Instant::now();
323			if deadline.is_some_and(|deadline| now >= deadline) {
324				let timeout = backoff.timeout;
325				let msg = match last_error {
326					Some(err) => format!("reconnect timed out after {timeout:?}: {err}"),
327					None => format!("reconnect timed out after {timeout:?}"),
328				};
329				return Err(Error::Reconnect(msg));
330			}
331
332			// Jittered so a fleet knocked offline together doesn't reconnect on the same tick, and
333			// never past the deadline the budget promised.
334			let mut wait = delay.mul_f64(0.5 + rand::rng().random::<f64>() / 2.0);
335			if let Some(deadline) = deadline {
336				wait = wait.min(deadline - now);
337			}
338			delay = backoff.next_delay(delay);
339
340			tracing::warn!(url = %url_log, ?wait, "reconnecting after backoff");
341			tokio::time::sleep(wait).await;
342		}
343	}
344
345	/// Poll for the next connection status change since this handle last reported one.
346	///
347	/// `Ready(Ok(status))` on a change, `Ready(Err)` once the loop has stopped (the give-up error,
348	/// or a generic one when the handle is dropped), `Pending` otherwise.
349	pub fn poll_status(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Status>> {
350		let last = self.last_reported;
351		let status = match ready!(self.state.poll(waiter, |state| match state.status {
352			Some(status) if Some(status) != last => Poll::Ready(status),
353			_ => Poll::Pending,
354		})) {
355			Ok(status) => status,
356			Err(state) => return Poll::Ready(Err(terminal(&state))),
357		};
358
359		self.last_reported = Some(status);
360		Poll::Ready(Ok(status))
361	}
362
363	/// Wait until the connection status changes from what this handle last reported.
364	///
365	/// Returns the current [`Status`]. The loop alternates `Connected`/`Disconnected`, so successive
366	/// calls alternate too; but a status that flips and flips back before the caller polls is
367	/// reported once. This tracks the *current* state, not every edge.
368	pub async fn status(&mut self) -> crate::Result<Status> {
369		kio::wait(|waiter| self.poll_status(waiter)).await
370	}
371
372	/// Whether a session is currently connected.
373	///
374	/// The synchronous read behind [`status`](Self::status), for callers that just want the current
375	/// state rather than the next change.
376	pub fn connected(&self) -> bool {
377		self.state.read().status == Some(Status::Connected)
378	}
379
380	/// The negotiated MoQ version of the live session, or `None` while disconnected.
381	///
382	/// The [`moq_net::Session::version`] counterpart; `Option` because a reconnecting handle can be
383	/// between sessions.
384	pub fn version(&self) -> Option<Version> {
385		self.state.read().version
386	}
387
388	/// A consumer for the live session's estimated send bitrate, mirroring
389	/// [`moq_net::Session::send_bandwidth`].
390	///
391	/// Unlike the session's, this handle is persistent: the reconnect loop forwards each session's
392	/// estimate into it, so it survives reconnects. Its value is `None` while disconnected or when the
393	/// backend has no estimate.
394	pub fn send_bandwidth(&self) -> BandwidthConsumer {
395		self.send_bandwidth.clone()
396	}
397
398	/// A consumer for the live session's estimated receive bitrate, mirroring
399	/// [`moq_net::Session::recv_bandwidth`]. Persistent across reconnects like
400	/// [`send_bandwidth`](Self::send_bandwidth); `None` while disconnected or unavailable.
401	pub fn recv_bandwidth(&self) -> BandwidthConsumer {
402		self.recv_bandwidth.clone()
403	}
404
405	/// Poll whether the reconnect loop has stopped.
406	///
407	/// `Ready(Err)` if it permanently gave up (a failure no retry can clear, or the backoff timeout
408	/// expiring), `Ready(Ok(()))` if stopped by dropping the handle, `Pending` while it's still
409	/// running.
410	pub fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<crate::Result<()>> {
411		ready!(self.state.poll_closed(waiter));
412		Poll::Ready(match &self.state.read().error {
413			Some(err) => Err(err.clone()),
414			None => Ok(()),
415		})
416	}
417
418	/// Wait until the reconnect loop stops.
419	pub async fn closed(&self) -> crate::Result<()> {
420		kio::wait(|waiter| self.poll_closed(waiter)).await
421	}
422
423	/// A cloneable handle for reading the current connection's stats.
424	///
425	/// The handle keeps working across reconnects, reporting `None` between connections.
426	pub fn stats(&self) -> ConnectionStatsReader {
427		ConnectionStatsReader {
428			state: self.state.clone(),
429		}
430	}
431}
432
433/// Wait for `session` to close, forwarding its send/recv bandwidth estimates into the persistent
434/// producers meanwhile so [`Reconnect`] consumers track the live estimates across the connection.
435/// Returns the session's close result (the loop uses it to distinguish a healthy drop from an
436/// immediate sever).
437///
438/// One `poll_*` step drives it all: [`poll_forward`] mirrors each kio bandwidth estimate, and the
439/// transport's close future (the one non-kio source) is polled through the waiter's own waker.
440async fn run_session(
441	send_bw: &BandwidthProducer,
442	recv_bw: &BandwidthProducer,
443	session: &moq_net::Session,
444) -> Result<(), moq_net::Error> {
445	let mut send = session.send_bandwidth();
446	let mut recv = session.recv_bandwidth();
447	let closed = session.closed();
448	tokio::pin!(closed);
449
450	let err = kio::wait(|waiter| {
451		poll_forward(&mut send, send_bw, waiter);
452		poll_forward(&mut recv, recv_bw, waiter);
453		waiter.poll_future(closed.as_mut())
454	})
455	.await;
456
457	Err(err)
458}
459
460/// Mirror `bw`'s live estimate into `out` for as long as it changes, dropping the source handle once
461/// the session's producer is gone so we don't keep polling a dead arm. A `poll_*` step: on return,
462/// `waiter` is registered for the next change (unless the source is gone). Seeding is implicit
463/// (the first call forwards the current value if there is one).
464///
465/// A `None` estimate is forwarded but keeps the arm alive: the backend reporting nothing right now
466/// isn't the same as the session ending, and the caller resets `out` to `None` on disconnect anyway.
467fn poll_forward(bw: &mut Option<BandwidthConsumer>, out: &BandwidthProducer, waiter: &kio::Waiter) {
468	loop {
469		let Some(consumer) = bw.as_mut() else { return };
470		let Poll::Ready(res) = consumer.poll_changed(waiter) else {
471			return;
472		};
473		match res {
474			Ok(rate) => {
475				let _ = out.set(rate);
476			}
477			Err(_) => {
478				*bw = None;
479				return;
480			}
481		}
482	}
483}
484
485impl Drop for Reconnect {
486	fn drop(&mut self) {
487		self.abort.abort();
488	}
489}
490
491/// The terminal error read from a closed channel's final state.
492fn terminal(state: &State) -> Error {
493	match &state.error {
494		Some(err) => err.clone(),
495		None => Error::Reconnect("reconnect stopped".to_string()),
496	}
497}
498
499#[cfg(test)]
500mod tests {
501	#[tokio::test]
502	async fn snapshot_uses_one_live_session() {
503		let mut config = crate::ServerConfig {
504			bind: Some("[::]:0".into()),
505			..Default::default()
506		};
507		config.tls.generate = vec!["localhost".into()];
508		let mut server = config.init().unwrap();
509		let url = format!("moqt://localhost:{}", server.local_addr().unwrap().port())
510			.parse()
511			.unwrap();
512		let mut config = crate::ClientConfig::default();
513		config.tls.disable_verify = Some(true);
514		let client = config.init().unwrap();
515		let (accepted, connected) = tokio::time::timeout(Duration::from_secs(10), async {
516			tokio::join!(
517				async { server.accept().await.unwrap().ok().await.unwrap() },
518				client.connect(url)
519			)
520		})
521		.await
522		.unwrap();
523		let session = connected.unwrap();
524		let version = session.version();
525		let producer = kio::Producer::<State>::default();
526		let reader = ConnectionStatsReader {
527			state: producer.consume(),
528		};
529		assert!(reader.snapshot().is_none());
530		producer.write().ok().unwrap().session = Some(session);
531		// The snapshot must read the protocol from that same session, without a second state query.
532		assert_eq!(reader.snapshot().unwrap().version, version);
533		producer.write().ok().unwrap().session = None;
534		assert!(reader.snapshot().is_none());
535		drop(accepted);
536	}
537
538	/// The retry loop is `delay = min(delay * multiplier, max)`, so a zero anywhere
539	/// pins the delay at zero and turns an unreachable relay into a hot dial loop,
540	/// unbounded when the give-up timeout is also zero.
541	#[test]
542	fn backoff_rejects_an_unpaced_retry() {
543		assert!(Backoff::default().validate().is_ok());
544
545		for bad in [
546			Backoff {
547				initial: Duration::ZERO,
548				..Default::default()
549			},
550			Backoff {
551				multiplier: 0,
552				..Default::default()
553			},
554			Backoff {
555				max: Duration::ZERO,
556				..Default::default()
557			},
558		] {
559			assert!(
560				matches!(bad.validate(), Err(crate::Error::BackoffUnpaced)),
561				"{bad:?} should be rejected"
562			);
563		}
564
565		// A zero timeout is documented as retry-forever, which is only a hazard
566		// unpaced, and a multiplier of 1 is a constant delay rather than no delay.
567		let forever = Backoff {
568			timeout: Duration::ZERO,
569			multiplier: 1,
570			..Default::default()
571		};
572		assert!(forever.validate().is_ok());
573	}
574
575	#[test]
576	fn backoff_growth_saturates_before_applying_the_cap() {
577		let backoff = Backoff {
578			multiplier: u32::MAX,
579			..Default::default()
580		};
581		assert_eq!(backoff.next_delay(Duration::MAX), backoff.max);
582	}
583
584	use super::*;
585
586	#[test]
587	fn test_backoff_default() {
588		let backoff = Backoff::default();
589		assert_eq!(backoff.initial, Duration::from_secs(1));
590		assert_eq!(backoff.multiplier, 2);
591		assert_eq!(backoff.max, Duration::from_secs(5));
592		assert_eq!(backoff.timeout, Duration::from_secs(10));
593	}
594
595	/// The linger outlives the give-up timeout (so the reconnect error surfaces
596	/// first), and an unlimited-retry timeout lingers forever.
597	#[test]
598	fn test_backoff_linger() {
599		let backoff = Backoff::default();
600		assert_eq!(backoff.linger(), backoff.timeout + Duration::from_secs(1));
601
602		let unlimited = Backoff {
603			timeout: Duration::ZERO,
604			..Backoff::default()
605		};
606		assert_eq!(unlimited.linger(), Duration::MAX);
607	}
608
609	#[test]
610	fn poll_forward_mirrors_until_the_source_closes() {
611		let src = BandwidthProducer::new();
612		let out = BandwidthProducer::new();
613		let out_rx = out.consume();
614		let waiter = kio::Waiter::noop();
615
616		// No estimate yet: nothing forwarded, source retained.
617		let mut bw = Some(src.consume());
618		poll_forward(&mut bw, &out, &waiter);
619		assert_eq!(out_rx.peek(), None);
620		assert!(bw.is_some());
621
622		// A value is mirrored through.
623		src.set(Some(3_000)).unwrap();
624		poll_forward(&mut bw, &out, &waiter);
625		assert_eq!(out_rx.peek(), Some(3_000));
626
627		// The estimate becoming unavailable is mirrored, but the arm stays: the
628		// backend reporting nothing right now is not the session ending.
629		src.set(None).unwrap();
630		poll_forward(&mut bw, &out, &waiter);
631		assert_eq!(out_rx.peek(), None);
632		assert!(bw.is_some());
633
634		// So a later value on the same live session still gets through. Dropping the
635		// arm on the `None` above would have stranded the estimate at `None` for the
636		// rest of the session.
637		src.set(Some(9_000)).unwrap();
638		poll_forward(&mut bw, &out, &waiter);
639		assert_eq!(out_rx.peek(), Some(9_000));
640
641		// Closing the source is what retires the arm, so we stop polling a dead one.
642		src.abort(moq_net::Error::Cancel).unwrap();
643		poll_forward(&mut bw, &out, &waiter);
644		assert!(bw.is_none());
645	}
646}