Skip to main content

moq_mux/container/ts/
follower.rs

1//! [`Follower`]: an [`Export`] or a [`Release`](super::Release) driven by the publisher identities
2//! serving its path, as a player is.
3
4use std::pin::Pin;
5use std::task::Poll;
6use std::time::Duration;
7
8use kio::clock::Instant;
9
10use super::error::malformed;
11use super::{Export, catalog};
12use crate::catalog::CatalogFormat;
13use crate::container::Frame;
14
15/// What a [`Follower`] carries across its path's identities: an [`Export`], or a
16/// [`Release`](super::Release) of a passthrough track.
17pub trait Followed: sealed::Followed {}
18
19impl<T: sealed::Followed> Followed for T {}
20
21pub(super) mod sealed {
22	use super::*;
23
24	/// What a [`Follower`](super::Follower) asks of the export it carries on.
25	pub trait Followed {
26		/// The catalog extension the export reads.
27		type Ext: catalog::Catalog + 'static;
28
29		/// The next frame, or `None` once the broadcast ends.
30		fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Option<Frame>>>;
31
32		/// Whether the catalog last subscribed has delivered a snapshot.
33		fn cataloged(&self) -> bool;
34
35		/// The source the export reads.
36		fn source(&self) -> &crate::Source;
37
38		/// The identity of the broadcast being exported, `None` for one not resolved through
39		/// an origin.
40		fn identity(&self) -> Option<&moq_net::Identity>;
41
42		/// Why the publisher left, while the export still plays out what it buffered before
43		/// reporting it.
44		fn departed(&self) -> Option<&crate::Error>;
45
46		/// The identity carried on into while playing out went before serving: stop reading it,
47		/// and report `err` once what was buffered has gone out.
48		fn depart(&mut self, err: crate::Error) -> crate::Result<()>;
49
50		/// Carry on into `broadcast`, whose `catalog` is subscribed, waiting up to `follow` for
51		/// another identity's program to become usable.
52		fn followed(
53			&mut self,
54			broadcast: &moq_net::broadcast::Consumer,
55			catalog: crate::catalog::Consumer<Self::Ext>,
56			follow: Duration,
57		) -> crate::Result<()>;
58
59		/// The format of the catalog being read.
60		fn catalog_format(&self) -> CatalogFormat;
61	}
62
63	impl<E: catalog::Catalog + 'static> Followed for Export<crate::catalog::Consumer<E>> {
64		type Ext = E;
65
66		fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Option<Frame>>> {
67			Export::poll_next(self, waiter)
68		}
69
70		fn cataloged(&self) -> bool {
71			Export::cataloged(self)
72		}
73
74		fn source(&self) -> &crate::Source {
75			Export::source(self)
76		}
77
78		fn identity(&self) -> Option<&moq_net::Identity> {
79			Export::identity(self)
80		}
81
82		fn departed(&self) -> Option<&crate::Error> {
83			Export::departed(self)
84		}
85
86		fn depart(&mut self, err: crate::Error) -> crate::Result<()> {
87			Export::depart(self, err)
88		}
89
90		fn followed(
91			&mut self,
92			broadcast: &moq_net::broadcast::Consumer,
93			catalog: crate::catalog::Consumer<E>,
94			follow: Duration,
95		) -> crate::Result<()> {
96			Export::followed(self, broadcast, catalog, follow)
97		}
98
99		fn catalog_format(&self) -> CatalogFormat {
100			Export::catalog_format(self)
101		}
102	}
103}
104
105/// What the identities say serves the exported path.
106enum Serving {
107	/// The identity being exported, with no change since the export carried on into it.
108	Ours,
109	/// Nothing: the identity handed out last went.
110	Gone,
111	/// The identity being exported, handed out again since: it came back after a gap.
112	Return(moq_net::broadcast::Consumer),
113	/// Another stream: a broadcast of another identity.
114	Other(moq_net::broadcast::Consumer),
115	/// A return or another stream that refused its catalog: nothing is followed until the
116	/// next change.
117	Refused,
118}
119
120/// Subscribing to an identity's catalog, to carry the export on into it.
121struct Subscription<E: catalog::Catalog> {
122	target: moq_net::broadcast::Consumer,
123	catalog: crate::catalog::Subscribing<E>,
124}
125
126/// Why the export awaits the first catalog snapshot of the identity it carried on into.
127enum Missing {
128	/// Carried on after the export ended with `end`: an identity that ends before it serves
129	/// leaves the export waiting for another until `deadline`.
130	Ended { end: crate::Result<()>, deadline: Instant },
131	/// A replacement switched to mid-stream, which ending before it serves is a failure.
132	Switch,
133	/// The same identity returned while the export played out what it buffered after the
134	/// publisher left with this error, which an end before it serves reports after all.
135	Return(crate::Error),
136}
137
138enum State<E: catalog::Catalog> {
139	/// Exporting, while switching to a replacement when stitching one, and awaiting the
140	/// catalog's first snapshot after carrying on into an identity.
141	Running {
142		awaiting: Option<Missing>,
143		switching: Option<Subscription<E>>,
144	},
145	/// The export ended with `end`, waiting until `deadline` for an identity to carry on into.
146	Settling { end: crate::Result<()>, deadline: Instant },
147	/// The export ended with `end`, and an identity serving the path is being subscribed.
148	Resuming {
149		subscription: Subscription<E>,
150		end: crate::Result<()>,
151		deadline: Instant,
152	},
153	/// Nothing follows.
154	Done,
155}
156
157/// Carries an [`Export`], or a [`Release`](super::Release) of a passthrough track, across its
158/// broadcast's returns, following the publisher identities serving its path through
159/// [`Following`](moq_net::origin::Following).
160///
161/// The same stream (the same identity) returning within the [follow](Self::with_follow)
162/// continues the export. Another identity taking the path fails with
163/// [`Error::Replaced`](crate::Error::Replaced), unless [stitching](Self::with_stitch), which
164/// switches the program to it at once. Subscriptions are sticky, so without stitching a
165/// replaced publisher that stays up keeps the export until it ends.
166///
167/// A track failure is followed only when its cause says the publisher left: the source failed
168/// to deliver, as [`moq_net::Error::retry`] answers (a lost route, an ended session, a cancel,
169/// or a going away), or a moq-transport peer ended it with a code it does not register, since
170/// PUBLISH_DONE has none for a lost route. Any other failure is the export's own and fails
171/// here at once.
172///
173/// An identity that comes back is awaited until its catalog serves a first snapshot, with no
174/// deadline but its own end. A return that refuses its catalog waits for the next change, and
175/// the follow running out reports that refusal. A refusal to resolve the path at all fails at
176/// once, as it does for every [`Following`](moq_net::origin::Following) reader.
177pub struct Follower<T: Followed = Export<crate::catalog::Consumer<()>>> {
178	export: T,
179	state: State<T::Ext>,
180	identities: moq_net::origin::Following,
181	path: moq_net::Path,
182	serving: Serving,
183	/// Taking the identities on hand when built, which replay the route the export resolved.
184	priming: bool,
185	/// The origin closed, so nothing more is announced.
186	closed: bool,
187	/// Why the last return refused its catalog, reported instead of the end if the follow runs out.
188	failed: Option<crate::Error>,
189	follow: Duration,
190	stitch: bool,
191	timer: Option<Pin<Box<kio::clock::Sleep>>>,
192}
193
194impl<T: Followed> Follower<T> {
195	/// Follow the path `export` reads, from the broadcast it resolved.
196	///
197	/// Fails when the export's origin can never cover its path.
198	pub fn new(export: T) -> crate::Result<Self> {
199		let source = export.source();
200		let identities = source.origin().follow(source.path(), None)?;
201		let mut follower = Self {
202			path: source.path().clone(),
203			export,
204			state: State::Running {
205				awaiting: None,
206				switching: None,
207			},
208			identities,
209			serving: Serving::Ours,
210			priming: true,
211			closed: false,
212			failed: None,
213			follow: Duration::ZERO,
214			stitch: false,
215			timer: None,
216		};
217		// Take the identity on hand now, before a gap can fold into it: one handed out at once is
218		// the route the export resolved, so only a later one is a return.
219		follower.poll_identities(&kio::Waiter::noop())?;
220		follower.priming = false;
221		Ok(follower)
222	}
223
224	/// Wait up to `follow` after the broadcast ends for the same identity, or with
225	/// [stitching](Self::with_stitch) a replacement, to come back. Defaults to
226	/// [`Duration::ZERO`], which carries on only into an identity already serving the path.
227	pub fn with_follow(mut self, follow: Duration) -> Self {
228		self.follow = follow;
229		self
230	}
231
232	/// Follow another publisher identity taking the path, as a full program switch (see
233	/// [`Export::follow`]). Defaults to `false`.
234	pub fn with_stitch(mut self, stitch: bool) -> Self {
235		self.stitch = stitch;
236		self
237	}
238
239	/// The export being carried on.
240	pub fn export(&self) -> &T {
241		&self.export
242	}
243
244	/// Get the next muxed frame, or `None` once the broadcast ends with nothing to follow.
245	#[cfg_attr(feature = "async", kio::wrapper)]
246	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Option<Frame>>> {
247		let next = self.poll_state(waiter);
248		if matches!(next, Poll::Ready(Ok(None) | Err(_))) {
249			self.state = State::Done;
250		}
251		next
252	}
253
254	fn poll_state(&mut self, waiter: &kio::Waiter) -> Poll<crate::Result<Option<Frame>>> {
255		loop {
256			match std::mem::replace(&mut self.state, State::Done) {
257				State::Done => return Poll::Ready(Ok(None)),
258				State::Running {
259					mut awaiting,
260					mut switching,
261				} => {
262					self.poll_identities(waiter)?;
263					if let Some(missing) = self.poll_switch(waiter, &mut switching)? {
264						awaiting = Some(missing);
265					}
266					let next = self.export.poll_next(waiter);
267					awaiting = awaiting.filter(|_| !self.export.cataloged());
268					let end = match next {
269						Poll::Ready(Ok(Some(frame))) => {
270							self.state = State::Running { awaiting, switching };
271							return Poll::Ready(Ok(Some(frame)));
272						}
273						Poll::Ready(Err(err)) if !left(&err) => {
274							tracing::warn!(path = %self.path, %err, "export failed, so not following");
275							return Poll::Ready(Err(err));
276						}
277						Poll::Ready(end) => end.map(|_| ()),
278						Poll::Pending => {
279							// An identity that goes with its catalog still open never served.
280							if let Some(missing) = awaiting.take_if(|_| matches!(self.serving, Serving::Gone)) {
281								self.state = self.withdrawn(missing)?;
282								continue;
283							}
284							// The publisher left during this poll, so a return already on hand is
285							// carried on into now: nothing else wakes the follower for it.
286							if switching.is_none()
287								&& matches!(self.serving, Serving::Return(_))
288								&& self.export.departed().is_some()
289							{
290								self.state = State::Running { awaiting, switching };
291								continue;
292							}
293							self.state = State::Running { awaiting, switching };
294							return Poll::Pending;
295						}
296					};
297					// Ending abandons the catalog switch; a return of this identity reuses its source.
298					if switching.is_some() {
299						self.export.source().priority(0)?;
300					}
301					// Nor did one whose catalog ended before its first snapshot.
302					if let Some(missing) = awaiting {
303						self.state = match missing {
304							// What was buffered has gone out too, so the export ends as the publisher left.
305							Missing::Return(err) => {
306								tracing::warn!(path = %self.path, "broadcast ended before serving its catalog");
307								State::Settling {
308									end: Err(err),
309									deadline: kio::clock::now().saturating_add(self.follow),
310								}
311							}
312							missing => self.withdrawn(missing)?,
313						};
314						continue;
315					}
316					self.following(&end);
317					self.state = State::Settling {
318						end,
319						deadline: kio::clock::now().saturating_add(self.follow),
320					};
321				}
322				State::Settling { end, deadline } => {
323					self.poll_identities(waiter)?;
324					let target = match &self.serving {
325						Serving::Return(target) => Some(target.clone()),
326						Serving::Other(target) if self.stitch => Some(target.clone()),
327						Serving::Other(_) => return Poll::Ready(Err(crate::Error::Replaced(self.path.to_string()))),
328						Serving::Ours | Serving::Gone | Serving::Refused => None,
329					};
330					if let Some(target) = target {
331						self.state = State::Resuming {
332							subscription: self.subscribe(target),
333							end,
334							deadline,
335						};
336						continue;
337					}
338					if self.closed || self.elapsed(waiter, deadline) {
339						return Poll::Ready(self.gone(end));
340					}
341					self.state = State::Settling { end, deadline };
342					return Poll::Pending;
343				}
344				State::Resuming {
345					mut subscription,
346					end,
347					deadline,
348				} => {
349					// Whatever the subscription waits on, the identities say what serves the path
350					// now: rather than sit out one that went, decide afresh from there.
351					if self.poll_identities(waiter)? {
352						tracing::debug!(path = %self.path, "identity changed while subscribing, deciding again");
353						self.state = State::Settling { end, deadline };
354						continue;
355					}
356					match subscription.catalog.poll_ok(waiter) {
357						Poll::Ready(Ok(catalog)) => {
358							self.carry_on(&subscription.target, catalog)?;
359							self.state = State::Running {
360								awaiting: Some(Missing::Ended { end, deadline }),
361								switching: None,
362							};
363						}
364						// Refused, or gone before the identities say so: nothing is followed until
365						// the next change. Only the follow running out reports a refusal.
366						Poll::Ready(Err(err)) => {
367							tracing::warn!(path = %self.path, %err, "catalog subscription failed, still waiting");
368							if !left(&err) {
369								self.failed = Some(err);
370							}
371							self.serving = Serving::Refused;
372							self.state = State::Settling { end, deadline };
373						}
374						Poll::Pending => {
375							self.state = State::Resuming {
376								subscription,
377								end,
378								deadline,
379							};
380							return Poll::Pending;
381						}
382					}
383				}
384			}
385		}
386	}
387
388	/// Drive a switch to the replacement serving the path when stitching, or a carry on into the
389	/// same identity returning while the export plays out what it buffered after the publisher
390	/// left, returning why the export awaits the first snapshot once it carried on.
391	///
392	/// When stitching, the old identity keeps playing until the replacement's catalog is
393	/// subscribed, however long that takes, and a replacement that goes first is no switch. The
394	/// old program's track subscriptions yield priority while acquiring the replacement.
395	///
396	/// A return is carried on into as soon as its catalog is subscribed, rather than once the
397	/// buffered output has gone out, so each track reads on from where it stopped before that
398	/// media is due ([`Export::follow`]).
399	fn poll_switch(
400		&mut self,
401		waiter: &kio::Waiter,
402		switching: &mut Option<Subscription<T::Ext>>,
403	) -> crate::Result<Option<Missing>> {
404		let (target, missing) = match &self.serving {
405			Serving::Other(target) if self.stitch => (target, None),
406			Serving::Return(target) => match self.export.departed() {
407				Some(err) => (target, Some(err.clone())),
408				None => return self.abandon(switching),
409			},
410			_ => return self.abandon(switching),
411		};
412		if !switching
413			.as_ref()
414			.is_some_and(|switching| switching.target.is_clone(target))
415		{
416			let target = target.clone();
417			match missing {
418				// A replacement being acquired may have lowered the priority; the return reads on.
419				Some(_) => {
420					tracing::info!(path = %self.path, "broadcast returned, carrying on while the old output plays out");
421					self.export.source().priority(0)?;
422				}
423				None => {
424					tracing::info!(path = %self.path, "broadcast replaced, switching the program to the new identity");
425					self.export.source().priority(-1)?;
426				}
427			}
428			*switching = Some(self.subscribe(target));
429		}
430		let subscription = switching.as_mut().expect("just set");
431		match subscription.catalog.poll_ok(waiter) {
432			Poll::Ready(Ok(catalog)) => {
433				let subscription = switching.take().expect("just polled");
434				self.carry_on(&subscription.target, catalog)?;
435				Ok(Some(missing.map_or(Missing::Switch, Missing::Return)))
436			}
437			// Gone before the identities say so: no switch until the next change.
438			Poll::Ready(Err(err)) if left(&err) => {
439				tracing::warn!(path = %self.path, %err, "identity went before its catalog subscribed");
440				self.serving = Serving::Refused;
441				self.abandon(switching)
442			}
443			// A return that refuses its catalog waits for the next change, as one after the
444			// output ended does. Only the follow running out reports the refusal.
445			Poll::Ready(Err(err)) if missing.is_some() => {
446				tracing::warn!(path = %self.path, %err, "catalog subscription failed, still waiting");
447				self.failed = Some(err);
448				self.serving = Serving::Refused;
449				self.abandon(switching)
450			}
451			// The replacement would not serve, so the switch fails loud.
452			Poll::Ready(Err(err)) => Err(err),
453			Poll::Pending => Ok(None),
454		}
455	}
456
457	/// Drop the catalog subscription [`Self::poll_switch`] holds, if any, giving the old program's
458	/// tracks back their priority.
459	fn abandon(&mut self, switching: &mut Option<Subscription<T::Ext>>) -> crate::Result<Option<Missing>> {
460		if switching.take().is_some() {
461			self.export.source().priority(0)?;
462		}
463		Ok(None)
464	}
465
466	/// Carry the export on into `target`, whose `catalog` is subscribed.
467	fn carry_on(
468		&mut self,
469		target: &moq_net::broadcast::Consumer,
470		catalog: crate::catalog::Consumer<T::Ext>,
471	) -> crate::Result<()> {
472		self.export.followed(target, catalog, self.follow)?;
473		self.serving = Serving::Ours;
474		self.failed = None;
475		tracing::info!(
476			path = %self.path,
477			identity = ?self.export.identity(),
478			"exporting broadcast"
479		);
480		Ok(())
481	}
482
483	/// Apply every change on hand, returning whether any came through.
484	fn poll_identities(&mut self, waiter: &kio::Waiter) -> crate::Result<bool> {
485		let mut any = false;
486		while !self.closed {
487			match self.identities.poll_available(waiter) {
488				Poll::Ready(Ok(Some(broadcast))) => {
489					self.serving = match self.export.identity() {
490						// A broadcast not resolved through an origin has no identity to match,
491						// so only the broadcast being exported is its own.
492						None if broadcast.is_clone(&self.export.source().broadcast()) => Serving::Ours,
493						// Even the same broadcast handed out again is a return: the origin hands
494						// one out only for an announcement that brings it.
495						Some(identity) if broadcast.info().identity.as_ref() == Some(identity) => match self.priming {
496							true => Serving::Ours,
497							false => Serving::Return(broadcast),
498						},
499						_ => Serving::Other(broadcast),
500					};
501				}
502				Poll::Ready(Ok(None)) => self.serving = Serving::Gone,
503				Poll::Ready(Err(moq_net::Error::Closed)) => self.closed = true,
504				Poll::Ready(Err(err)) => return Err(err.into()),
505				Poll::Pending => break,
506			}
507			any = true;
508		}
509		Ok(any)
510	}
511
512	/// Begin subscribing to `target`'s catalog.
513	fn subscribe(&self, target: moq_net::broadcast::Consumer) -> Subscription<T::Ext> {
514		Subscription {
515			catalog: crate::catalog::Subscribing::new(&target, self.export.catalog_format()),
516			target,
517		}
518	}
519
520	/// Where the export goes once the identity it carried on into ends before its first snapshot.
521	fn withdrawn(&mut self, missing: Missing) -> crate::Result<State<T::Ext>> {
522		tracing::warn!(path = %self.path, "broadcast ended before serving its catalog");
523		Ok(match missing {
524			Missing::Ended { end, deadline } => State::Settling { end, deadline },
525			Missing::Switch => State::Settling {
526				end: Err(malformed!("replacement broadcast `{}` ended before serving its catalog", self.path).into()),
527				deadline: kio::clock::now().saturating_add(self.follow),
528			},
529			// What was buffered still goes out, and then the export ends as the publisher left.
530			Missing::Return(err) => {
531				self.export.depart(err)?;
532				State::Running {
533					awaiting: None,
534					switching: None,
535				}
536			}
537		})
538	}
539
540	fn following(&self, end: &crate::Result<()>) {
541		if self.follow.is_zero() {
542			return;
543		}
544		match end {
545			Ok(()) => {
546				tracing::info!(path = %self.path, follow = ?self.follow, "broadcast finished, waiting for it to return")
547			}
548			Err(err) => {
549				tracing::warn!(path = %self.path, %err, follow = ?self.follow, "broadcast ended, waiting for it to return")
550			}
551		}
552	}
553
554	/// How the export ends once the follow runs out with nothing back: with why the last
555	/// return refused its catalog, if one did, else as the broadcast ended.
556	fn gone(&mut self, end: crate::Result<()>) -> crate::Result<Option<Frame>> {
557		tracing::info!(path = %self.path, follow = ?self.follow, "broadcast did not return");
558		match self.failed.take() {
559			Some(err) => Err(err),
560			None => end.map(|()| None),
561		}
562	}
563
564	/// Whether `at` has come, registering `waiter` to wake then if not.
565	fn elapsed(&mut self, waiter: &kio::Waiter, at: Instant) -> bool {
566		if kio::clock::now() >= at {
567			return true;
568		}
569		let timer = self.timer.get_or_insert_with(|| Box::pin(kio::clock::sleep_until(at)));
570		if timer.deadline() != at {
571			timer.as_mut().reset(at);
572		}
573		waiter.poll_future(timer.as_mut()).is_ready()
574	}
575}
576
577/// Whether a failure says the publisher left rather than the export failing: the source failed
578/// to deliver (see [`moq_net::Error::retry`]), or a moq-transport peer named no cause.
579///
580/// moq-transport's PUBLISH_DONE has no code for a lost route, so a relay's lost upstream and a
581/// publisher's own failure both end with an unregistered one, which `retry` cannot answer for.
582pub(super) fn left(err: &crate::Error) -> bool {
583	let (crate::Error::Moq(err) | crate::Error::Hang(hang::Error::Moq(err))) = err else {
584		return false;
585	};
586	err.retry() != moq_net::Retry::Never || matches!(err, moq_net::Error::Remote(_))
587}