diff --git a/doc/bin/gstreamer.md b/doc/bin/gstreamer.md index f56cba540d5..edb94e52407 100644 --- a/doc/bin/gstreamer.md +++ b/doc/bin/gstreamer.md @@ -63,7 +63,11 @@ Audio packets share groups of at least 20 ms while forwarding as they arrive. Each `sink_%u` request pad is one track. Pad properties: `track` names it (default: after the codec), `container=loc` publishes it as [LOC](/concept/standard#loc) instead of the legacy hang container, and -`track-status`/`track-error` report its lifecycle. Element properties: +`track-status`/`track-error` report its lifecycle. Caps that only change what +the bitstream already carries (a video resolution) keep the track live. A run +never publishes a track name it ended again: new codec config, a pad requested +again, or a stream resumed after EOS publishes as `/`, which `track` +reads back. Element properties: `url`, `broadcast`, `linger`, `connect-version`, `tls-disable-verify`, `quic-idle-timeout`, `quic-keylog`, `quic-keep-alive`, and read-only `status`, `connected`, `moq-version`, and `estimated-send-rate`, `estimated-recv-rate`, `connection-stats`, and diff --git a/js/net/src/ietf/publish.ts b/js/net/src/ietf/publish.ts index 5145437c753..5c50fab437b 100644 --- a/js/net/src/ietf/publish.ts +++ b/js/net/src/ietf/publish.ts @@ -216,7 +216,10 @@ export const PublishDoneStatus = { UPDATE_FAILED: 0x8, } as const; -/** Whether a PUBLISH_DONE status ends the track cleanly rather than aborting it. */ +/** + * Whether a PUBLISH_DONE status ends the subscription cleanly, so its data streams in flight still + * drain, rather than aborting it. Only TRACK_ENDED also ends the track. + */ export function publishDoneClean(statusCode: number, version: IetfVersion): boolean { if (statusCode === PublishDoneStatus.TRACK_ENDED) return true; if (statusCode !== PublishDoneStatus.SUBSCRIPTION_ENDED) return false; diff --git a/js/net/src/ietf/subscriber.ts b/js/net/src/ietf/subscriber.ts index fb659a19222..1a0a92c8f25 100644 --- a/js/net/src/ietf/subscriber.ts +++ b/js/net/src/ietf/subscriber.ts @@ -1077,6 +1077,11 @@ export class Subscriber { const { tail, track } = subscription; const complete = () => count > 0n && BigInt(tail.streams) >= count; await tail.settle(complete, track.closed); + // SUBSCRIPTION_ENDED ends just this subscription, so the copy fails rather than declare an + // end the track may run past: a later reader subscribes afresh, and its groups continue. + if (done.statusCode !== PublishDoneStatus.TRACK_ENDED) { + throw new Error(`publish done: subscription ended reason=${done.reasonPhrase}`); + } } /** diff --git a/js/net/src/ietf/tail.test.ts b/js/net/src/ietf/tail.test.ts index 79451cc6b61..f0132141fbf 100644 --- a/js/net/src/ietf/tail.test.ts +++ b/js/net/src/ietf/tail.test.ts @@ -18,6 +18,7 @@ const ALIAS = 9n; const TRACK_ENDED = 0x2; const INTERNAL_ERROR = 0x0; const UNAUTHORIZED = 0x1; +const SUBSCRIPTION_ENDED = 0x3; // A plain subgroup stream: no extensions, no subgroup id, end of group on FIN. const FLAGS: GroupFlags = { @@ -162,6 +163,21 @@ test("a PUBLISH_DONE with an error status aborts the track", async () => { expect(await reader.closed).toBeInstanceOf(Error); }); +// SUBSCRIPTION_ENDED ends only the subscription: a later one continues the track past these +// groups, so the copy delivers what was in flight and then fails rather than declare an end. +test("a SUBSCRIPTION_ENDED PUBLISH_DONE drains, then aborts the track", async () => { + const { subscriber, reader, done } = await subscribed(); + const group = groupStream(subscriber, 0); + group.write(object("0.0")); + group.finish(); + await group.handled; + await done(SUBSCRIPTION_ENDED, 1n); + + expect(await readAll(await reader.recvGroup())).toEqual(["0.0"]); + expect(await reader.closed).toBeInstanceOf(Error); + expect(reader.end()).toBeUndefined(); +}); + test("an UNAUTHORIZED PUBLISH_DONE reads as the revocation a moq-lite peer sends", async () => { const { reader, done } = await subscribed(); await done(UNAUTHORIZED, 0n); diff --git a/quest/m1/README.md b/quest/m1/README.md index b5fb183ce52..56f0d6274e8 100644 --- a/quest/m1/README.md +++ b/quest/m1/README.md @@ -109,7 +109,6 @@ divergences, under one epic; its redesign proposals went to m2. - [Empty segments refused](/quest/m1/empty-segments.md) - `room//cam` fails loud instead of naming `room/cam` - [In-band auth](/quest/m1/auth/README.md) - a session tells its peer what it may publish and subscribe to, unions tokens presented in band, and fails loud on an out-of-scope publish - [Cluster routing](/quest/m1/cluster-routing/README.md) - prove shared routing contracts, implement per-origin routes, and connect outbound local clusters -- [No reused track names](/quest/m1/name-reuse.md) - no first-party publisher re-creates a finished track under its old name - [Routing guide](/quest/m1/routing-guide.md) - concepts and practical outbound federation setup - [Generated C bindings](/quest/m1/c/README.md) - C generated from moq-ffi ships as `moq-c` 0.8.0 and replaces the hand-written libmoq - [Exact timestamps in every binding](/quest/m1/binding-timestamps.md) - bindings carry `{value, scale}` timestamps instead of lossy microseconds diff --git a/quest/m1/name-reuse.md b/quest/m1/name-reuse.md deleted file mode 100644 index 5f029ea6b49..00000000000 --- a/quest/m1/name-reuse.md +++ /dev/null @@ -1,18 +0,0 @@ -# [M] Publishers never reuse a finished track's name - -## Goal - -No first-party publisher finishes a track and then publishes different -content under the same name. Each either aborts the track or numbers its -groups past its predecessor's. - -## Plan - -moq-transcode already finishes a rung only when its source finished. Others still -finish and re-create: moq-gst's sink on caps renegotiation and `release_pad` -(`rs/moq-gst/src/sink/imp.rs`). Also audit moq-mux's timeline error path, -moq-cli echo retire, moq-rtsp, moq-rtmp, `cpp/obs`, `js/publish`, and the IETF -SUBSCRIPTION_ENDED path in moq-net. Fix each with a test that a restart -never repeats a group sequence. - -Public API: none expected. Wire: none. diff --git a/rs/moq-gst/src/sink/imp.rs b/rs/moq-gst/src/sink/imp.rs index 1522246b98d..a2a3e7c63ec 100644 --- a/rs/moq-gst/src/sink/imp.rs +++ b/rs/moq-gst/src/sink/imp.rs @@ -20,7 +20,7 @@ use gst::prelude::*; use gst::subclass::prelude::*; use hang::moq_net; -use super::pad::{CapsOutcome, ProducerOptions, PushOutcome, caps_supported}; +use super::pad::{CapsOutcome, Names, ProducerOptions, PushOutcome, caps_supported}; use super::request_pad::{MoqSinkPad, Notifications, PadLifecycle}; use super::session::{ CAT, Completion, CompletionHandle, ConnectionStatus, RUNTIME, ResolvedSettings, Session, SessionRegistration, @@ -70,6 +70,8 @@ struct State { broadcast: moq_net::origin::Publication, catalog: Option, wall: std::sync::Arc, + /// The configured track names this run ended, which it never publishes again. + names: Names, /// How long a clean end keeps the finished broadcast up before its EOS. linger: Duration, /// Whether the finished broadcast closed, so the EOS it owes may go out. @@ -435,7 +437,7 @@ impl ElementImpl for MoqSink { if let Some(state) = control.live.as_ref() && let Some(catalog) = state.catalog.as_ref() { - pad.lifecycle().media.reserve(catalog, state.wall.clone()); + pad.lifecycle().media.reserve(catalog, state.wall.clone(), &state.names); } control.admissions.insert(pad.clone()); } @@ -582,6 +584,7 @@ impl MoqSink { broadcast, catalog: Some(catalog), wall, + names: Names::default(), linger, drained: false, lingering: None, @@ -598,7 +601,7 @@ impl MoqSink { let changes = lifecycle.reset(); lifecycle.completion = Some(completion.clone()); if !lifecycle.releasing { - lifecycle.media.reserve(catalog, wall.clone()); + lifecycle.media.reserve(catalog, wall.clone(), &state.names); } changes }; @@ -885,7 +888,7 @@ impl MoqSink { if !lifecycle.releasing { lifecycle.ended = false; if let Some(catalog) = &state.catalog { - lifecycle.media.reserve(catalog, state.wall.clone()); + lifecycle.media.reserve(catalog, state.wall.clone(), &state.names); } } } @@ -911,7 +914,7 @@ impl MoqSink { lifecycle.media.flush(); let catalog = state.catalog.as_ref(); if let Some(catalog) = catalog { - lifecycle.media.reserve(catalog, state.wall.clone()); + lifecycle.media.reserve(catalog, state.wall.clone(), &state.names); } let caps = lifecycle.media.resumable_caps(); caps.zip(catalog).and_then(|(caps, catalog)| { @@ -1206,7 +1209,7 @@ fn observe_caps( lifecycle: &mut PadLifecycle, caps: &gst::Caps, ) -> (Option, bool) { - lifecycle.media.reserve(catalog, state.wall.clone()); + lifecycle.media.reserve(catalog, state.wall.clone(), &state.names); let requested = lifecycle.requested().map(str::to_owned); let mut options = ProducerOptions::new(caps).with_container(lifecycle.container().into()); if let Some(track) = requested.as_deref() { @@ -1596,7 +1599,8 @@ mod tests { assert!(completion_of(&run.0).is_open()); } - // GStreamer keeps CAPS sticky across a flush, so a resumed pad gets no new CAPS event. + // GStreamer keeps CAPS sticky across a flush, so a resumed pad gets no new CAPS event. EOS ended its + // track, so the resumed one takes a fresh name. #[test] fn an_unresolved_pad_resumed_after_eos_publishes_without_new_caps() { use futures::FutureExt; @@ -1626,7 +1630,7 @@ mod tests { let std::task::Poll::Ready(Ok(Some(next))) = next_catalog(&mut catalog) else { panic!("the resumed pad must publish its rendition ({resume})") }; - assert!(next.video.renditions.contains_key("video"), "{resume}"); + assert!(next.video.renditions.contains_key("video/1"), "{resume}"); let broadcast = run .0 .imp() @@ -1639,7 +1643,7 @@ mod tests { .broadcast .consume(); let mut track = broadcast - .track("video") + .track("video/1") .expect("the resumed track is published") .subscribe(None) .now_or_never() diff --git a/rs/moq-gst/src/sink/pad.rs b/rs/moq-gst/src/sink/pad.rs index 46ec68abebf..b817cd559d0 100644 --- a/rs/moq-gst/src/sink/pad.rs +++ b/rs/moq-gst/src/sink/pad.rs @@ -37,6 +37,53 @@ enum Sink { Opaque(Box), } +impl Sink { + /// The track name, as the broadcast knows it. + fn name(&self) -> String { + match self { + Sink::Media(media) => media.track.name(), + Sink::Text(text) => text.producer.name().to_owned(), + Sink::Opaque(producer) => producer.name().to_owned(), + } + } +} + +/// Every configured track name a run has published, and whether it ended. +/// +/// A name always means the same content, and a reader that saw a track end (here or at a relay) +/// never follows the name into a successor. So a run never publishes an ended name again: a pad that +/// would (a new codec config, a pad requested again, a stream resumed after EOS) publishes under the +/// first `/` the run has not used instead, as js/publish does. Generated names are never +/// reused, so they are not recorded. +#[derive(Clone, Default)] +pub(super) struct Names(std::sync::Arc>>); + +impl Names { + /// `name`, unless the run ended it: then the first `name/` the run has not used. + /// + /// A name another pad still publishes is returned as is, so the duplicate fails loudly. + fn claim(&self, name: &str) -> String { + let mut names = self.0.lock().unwrap(); + if names.get(name) != Some(&true) { + names.entry(name.to_owned()).or_insert(false); + return name.to_owned(); + } + let mut n = 1u64; + loop { + let minted = format!("{name}/{n}"); + if let std::collections::hash_map::Entry::Vacant(entry) = names.entry(minted.clone()) { + entry.insert(false); + return minted; + } + n += 1; + } + } + + fn end(&self, name: String) { + self.0.lock().unwrap().insert(name, true); + } +} + /// Keep finished rendition owners until a whole run's catalog has closed. #[must_use] pub(super) struct Closed { @@ -209,7 +256,8 @@ fn escape_cue(text: &str) -> String { /// lets the caller report a status instead of only logging one. #[derive(Debug, Clone, PartialEq, Eq)] pub enum CapsOutcome { - /// Already publishing under these caps, or already failed: no producer was built. + /// The live producer keeps publishing (the caps build the same importer), or the pad already + /// failed: no producer was built. Unchanged, /// A producer was built, reserving this track name. Active(String), @@ -237,7 +285,11 @@ pub struct Pad { /// The requested pad gates the first catalog even before CAPS can name its rendition. reserved: Option, wall: Option>, + /// The run's, once reserved; until then this pad's own, which still covers renegotiation. + names: Names, track: Option, + /// Whether `track` has a configured name, which may be requested again. A generated one never is. + named: bool, caps: Option, /// Set once a producer build rejects this pad's caps or bitstream; further buffers are dropped and /// the track stays finalized. Isolated to the pad, so the session and other pads keep going. The @@ -258,7 +310,9 @@ impl Pad { Self { reserved: None, wall: None, + names: Names::default(), track: None, + named: false, caps: None, failed: false, state: PadState::NoSegment, @@ -269,8 +323,14 @@ impl Pad { } /// Fill a run's slot once, including a pad visible before its admission confirms. - pub(super) fn reserve(&mut self, catalog: &moq_mux::catalog::Producer, wall: std::sync::Arc) { + pub(super) fn reserve( + &mut self, + catalog: &moq_mux::catalog::Producer, + wall: std::sync::Arc, + names: &Names, + ) { self.wall = Some(wall); + self.names = names.clone(); if self.reserved.is_none() && self.track.is_none() && !self.failed { self.reserved = Some(catalog.reserve()); } @@ -315,14 +375,21 @@ impl Pad { /// (Re)build the producer when the pad's caps change, under `track` when the pad was given a name. /// A build failure invalidates only this pad; the caller keeps the session and other pads alive. - /// Identical caps re-sent as a sticky event keep the live producer. + /// Caps that build the same importer keep the live producer, so its readers continue. pub(super) fn observe_caps( &mut self, broadcast: &moq_net::broadcast::Producer, catalog: &moq_mux::catalog::Producer, options: ProducerOptions<'_>, ) -> CapsOutcome { - if self.failed || (self.track.is_some() && self.caps.as_deref() == Some(options.caps)) { + if self.failed { + return CapsOutcome::Unchanged; + } + if self.track.is_some() + && let Some(caps) = &self.caps + && same_importer(caps, options.caps) + { + self.caps = Some(options.caps.clone()); return CapsOutcome::Unchanged; } let reserved = self.reserved.take().unwrap_or_else(|| catalog.reserve()); @@ -348,8 +415,18 @@ impl Pad { requested, } = options; let structure = caps.structure(0).context("empty caps")?; - // Renegotiation: finalize the previous producer before replacing it (closed once, not abandoned). + // Renegotiation to new content: finalize the previous producer before replacing it (closed once, + // not abandoned), so its name has ended and the replacement takes a fresh one. self.finalize()?; + self.named = requested.is_some(); + let requested = requested.map(|name| { + let claimed = self.names.claim(name); + if claimed != name { + gst::info!(CAT, "track {name} already ended in this run, publishing as {claimed}"); + } + claimed + }); + let requested = requested.as_deref(); // Opaque data has no codec importer and no catalog entry, so it never reaches the codec match. if structure.name() == "application/octet-stream" { // A generated name would leave the track unfindable: nothing advertises it. @@ -842,6 +919,9 @@ impl Pad { Sink::Text(text) => text.producer.finish().map_err(anyhow::Error::from), Sink::Opaque(producer) => producer.clone().finish().map_err(anyhow::Error::from), }; + if self.named { + self.names.end(track.name()); + } self.failed |= result.is_err(); (closed, result.map(|()| true)) } @@ -1132,6 +1212,19 @@ pub fn caps_supported(caps: &gst::CapsRef) -> bool { ) } +/// Whether `next` builds the same importer as `current`, so the live track continues under it. +/// +/// Video configures in band and opaque data carries no config, so only their media type counts. An +/// audio or text pad builds from its whole caps (the codec config, rate, channels, language), which +/// is what a subscriber decodes or selects by, so any change there is new content. +fn same_importer(current: &gst::CapsRef, next: &gst::CapsRef) -> bool { + let (Some(was), Some(now)) = (current.structure(0), next.structure(0)) else { + return false; + }; + let media = now.name().as_str(); + was.name() == now.name() && (media.starts_with("video/") || media == "application/octet-stream" || current == next) +} + fn segment_info(segment: &gst::Segment) -> SegmentInfo { match segment.downcast_ref::() { Some(time) => SegmentInfo { @@ -1284,28 +1377,115 @@ mod tests { assert!(first.finalize().unwrap(), "the first producer is still live"); } - // Renegotiation re-reserves the same explicit name. `build` finalizes the old producer first and the - // broadcast reclaims closed entries on insert, so the pad does not collide with itself. - #[test] - fn renegotiation_keeps_the_explicit_name() { + /// Caps the importer does not configure from keep the track live, so a reader subscribed before + /// the renegotiation reads on into the new caps rather than seeing the track end. + #[tokio::test] + async fn renegotiation_keeps_an_established_reader() { gst::init().unwrap(); let (broadcast, catalog) = producers(); let mut pad = Pad::new(); - assert_eq!( - pad.observe_caps(&broadcast, &catalog, producer_options(&h264_caps(), Some("camera")),), - CapsOutcome::Active("camera".to_string()) - ); + pad.observe_caps(&broadcast, &catalog, producer_options(&h264_caps(), Some("camera"))); + pad.observe_segment(time_segment()); + let mut subscriber = broadcast + .consume() + .track("camera") + .unwrap() + .subscribe(None) + .await + .unwrap(); + for ms in [0, 40] { + let pushed = pad.push_buffer(h264_keyframe_au(), Some(gst::ClockTime::from_mseconds(ms)), None, None); + assert_eq!(pushed, Ok(PushOutcome::Published)); + } + let renegotiated = gst::Caps::builder("video/x-h264") .field("stream-format", "byte-stream") .field("alignment", "au") .field("width", 1280i32) .build(); assert_eq!( - pad.observe_caps(&broadcast, &catalog, producer_options(&renegotiated, Some("camera")),), - CapsOutcome::Active("camera".to_string()), - "the same name is reserved again, not rejected as a duplicate" + pad.observe_caps(&broadcast, &catalog, producer_options(&renegotiated, Some("camera"))), + CapsOutcome::Unchanged ); - assert!(!pad.is_failed()); + let pushed = pad.push_buffer(h264_keyframe_au(), Some(gst::ClockTime::from_mseconds(80)), None, None); + assert_eq!(pushed, Ok(PushOutcome::Published)); + + // The reader may skip to the latest group, but never sees the track end before the new caps. + loop { + let group = subscriber.recv_group().await.unwrap().expect("the track continues"); + if group.sequence == 2 { + break; + } + } + } + + /// A new codec config is new content: the old track ends on its name, and the replacement takes a + /// fresh one rather than reusing it. + #[tokio::test] + async fn a_new_codec_config_takes_a_fresh_name() { + gst::init().unwrap(); + let (broadcast, catalog) = producers(); + let mut pad = Pad::new(); + pad.observe_caps(&broadcast, &catalog, producer_options(&h264_caps(), Some("camera"))); + pad.observe_segment(time_segment()); + let mut subscriber = broadcast + .consume() + .track("camera") + .unwrap() + .subscribe(None) + .await + .unwrap(); + let pushed = pad.push_buffer(h264_keyframe_au(), Some(gst::ClockTime::ZERO), None, None); + assert_eq!(pushed, Ok(PushOutcome::Published)); + + let vp8 = gst::Caps::builder("video/x-vp8").build(); + assert_eq!( + pad.observe_caps(&broadcast, &catalog, producer_options(&vp8, Some("camera"))), + CapsOutcome::Active("camera/1".to_string()) + ); + assert_eq!(subscriber.recv_group().await.unwrap().expect("a group").sequence, 0); + assert!(subscriber.recv_group().await.unwrap().is_none(), "the old track ended"); + } + + /// A run never publishes a name it ended again, whoever asks for it next: each replacement mints + /// the next free name. + #[test] + fn an_ended_name_is_never_published_again() { + gst::init().unwrap(); + let (broadcast, catalog) = producers(); + let names = Names::default(); + let publish = || { + let mut pad = Pad::new(); + pad.reserve(&catalog, super::super::wall::Wall::new(&catalog), &names); + let outcome = pad.observe_caps(&broadcast, &catalog, producer_options(&opaque_caps(), Some("levels"))); + assert!(pad.finalize().unwrap()); + outcome + }; + + assert_eq!(publish(), CapsOutcome::Active("levels".to_string())); + assert_eq!(publish(), CapsOutcome::Active("levels/1".to_string())); + assert_eq!(publish(), CapsOutcome::Active("levels/2".to_string())); + } + + /// A fresh name skips one another pad publishes, rather than colliding with it. + #[test] + fn a_fresh_name_skips_a_live_one() { + gst::init().unwrap(); + let (broadcast, catalog) = producers(); + let names = Names::default(); + let publish = |name| { + let mut pad = Pad::new(); + pad.reserve(&catalog, super::super::wall::Wall::new(&catalog), &names); + let outcome = pad.observe_caps(&broadcast, &catalog, producer_options(&opaque_caps(), Some(name))); + (pad, outcome) + }; + + let (mut levels, _) = publish("levels"); + let (_live, outcome) = publish("levels/1"); + assert_eq!(outcome, CapsOutcome::Active("levels/1".to_string())); + assert!(levels.finalize().unwrap()); + let (_again, outcome) = publish("levels"); + assert_eq!(outcome, CapsOutcome::Active("levels/2".to_string())); } // AAC carries its config in caps; without codec_data the producer cannot be built. diff --git a/rs/moq-mux/src/timeline.rs b/rs/moq-mux/src/timeline.rs index 423aceb09b2..7771c93d66a 100644 --- a/rs/moq-mux/src/timeline.rs +++ b/rs/moq-mux/src/timeline.rs @@ -433,6 +433,8 @@ impl Iterator for Segmenter { /// Records must be pushed in sequence order, starting at the window's next index. pub struct Producer { sink: moq_json::window::Producer, + /// The window's track, kept to abort it with the cause of a failure. + track: moq_net::track::Producer, } impl Producer { @@ -448,10 +450,22 @@ impl Producer { /// Publish onto `track`, starting at record zero. pub fn new(track: moq_net::track::Producer) -> Self { Self { - sink: moq_json::window::Producer::new(track, Self::config()), + sink: moq_json::window::Producer::new(track.clone(), Self::config()), + track, } } + /// Abort the timeline track with `err`, so its readers see a failure rather than an end. + fn abort(self, err: &crate::Error) { + // A cause outside moq-net has no wire code, so readers get a generic failure. + let reason = match err { + crate::Error::Moq(err) => err.clone(), + _ => moq_net::StreamError::Internal.into(), + }; + // A track that already closed keeps its first reason. + let _ = self.track.abort(reason); + } + fn config() -> moq_json::window::ProducerConfig { moq_json::window::ProducerConfig::default() .with_compression(true) @@ -529,9 +543,10 @@ impl Live { continue; }; if let Err(err) = output.push(&record) { - tracing::warn!(%err, "timeline publish failed; dropping the timeline track"); - let _ = output.finish(); - self.output = None; + tracing::warn!(%err, "timeline publish failed; aborting the timeline track"); + if let Some(output) = self.output.take() { + output.abort(&err); + } } } if let Some(duration) = self.segmenter.declared_duration() @@ -720,10 +735,12 @@ impl Recorder { pub fn frame(&mut self, position: Position, pts: Timestamp, keyframe: bool) { let mut live = self.live.lock().unwrap(); if let Err(err) = live.segmenter.frame(position, pts, keyframe) { - tracing::warn!(%err, "timeline report rejected; dropping the timeline track"); + tracing::warn!(%err, "timeline report rejected; aborting the timeline track"); live.segmenter.close(); - // Dropped without a finish, so subscribers see the timeline fail rather than end. - live.output = None; + // Subscribers see the timeline fail rather than end. + if let Some(output) = live.output.take() { + output.abort(&err); + } } live.publish(); } @@ -1421,7 +1438,19 @@ mod test { match consumer.next().await { Ok(Some(_)) => continue, Ok(None) => panic!("the timeline ended cleanly despite omitting a frame"), - Err(_) => break, + // Aborted with the failure, not left to read as a producer that went away. + Err(err) => { + assert!( + matches!( + err, + crate::Error::Json(moq_json::Error::Net(moq_net::Error::Stream( + moq_net::StreamError::Internal + ))) + ), + "{err:?}" + ); + break; + } } } } diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index d3da9daee7e..2bbadfa867e 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -3779,10 +3779,11 @@ impl Subscriber { End::Done(res) => { // Only TRACK_ENDED ends a listing entry quietly; a clean end of another // kind, such as SUBSCRIPTION_ENDED, leaves the track's fate unknown. - ended = Some(match &res { + let end = match &res { Ok(done) => tracks::listing_end(done, self.version), Err(err) => Err(err.clone()), - }); + }; + ended = Some(end.clone()); match res.map(|done| done.stream_count) { Ok(count) => { tracing::debug!(broadcast = %self.origin.absolute(broadcast_path), track = %track_name, "subscribe complete"); @@ -3819,12 +3820,21 @@ impl Subscriber { fill.end(); } } - // A no-op once an END_OF_TRACK declared the end, whose readers wait - // for a missing group only as long as the grace. - let _ = track.finish(); - // Only TRACK_ENDED ends the track: after SUBSCRIPTION_ENDED a - // later reader subscribes afresh. - finished = matches!(ended, Some(Ok(()))); + // Only TRACK_ENDED ends the track. Any other status ends just this + // subscription, so the copy fails rather than declare an end the + // track may run past: a later reader subscribes afresh to the same + // name, and its groups continue. + match end { + // A no-op once an END_OF_TRACK declared the end, whose readers + // wait for a missing group only as long as the grace. + Ok(()) => { + let _ = track.finish(); + finished = true; + } + Err(err) => { + let _ = track.clone().abort(err); + } + } } Err(err) => { tracing::debug!(%err, "subscribe ended with error"); @@ -16750,7 +16760,9 @@ mod joining_fetch_tests { } /// SUBSCRIPTION_ENDED ends only our subscription, not the track, so the copy is released - /// for a later reader to subscribe afresh rather than lingering as if the track ended. + /// for a later reader to subscribe afresh rather than lingering as if the track ended. Its + /// reader sees an error, not a clean end: the fresh copy's groups continue past this one's, + /// so an end here would be one the track runs past. #[moq_clock::test] async fn a_subscription_ended_copy_does_not_linger() { for version in JOINING_DRAFTS { @@ -16767,12 +16779,14 @@ mod joining_fetch_tests { version, )); let mut run = JoinRun::start(version, None, ok, Vec::new()).await; - let _subscriber = (&mut run._hold.2).await.expect("subscribed"); + let mut subscriber = (&mut run._hold.2).await.expect("subscribed"); while !run.subscriber.state.lock().subscribes.is_empty() { settle().await; } settle().await; assert!(run.serving.is_finished(), "{version}: the copy is released"); + let end = subscriber.recv_group().await.map(|group| group.is_some()); + assert!(end.is_err(), "{version}: the copy ended cleanly: {end:?}"); } }