From 2d8c810f350b418ad581832b62a9565612453c50 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 18 Nov 2026 20:16:37 -0800 Subject: [PATCH 01/10] chore(quest): claim quest/m2/outcome-enums/small-public.md Quest-Claim: 16800343da06bb02 From a4e5af172ee80804a236d126015fbb8f5f768cad Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 18 Nov 2026 21:15:07 -0800 Subject: [PATCH 02/10] wip: reshape create_track, fill accepts, poll_acked, Connection status, local_addr Co-Authored-By: Claude Opus 5.5 --- doc/concept/identity.md | 2 +- rs/hang/examples/video.rs | 4 +- rs/libmoq/src/publish.rs | 21 +- rs/libmoq/src/server.rs | 5 +- rs/moq-archive/src/consumer/mod.rs | 2 +- rs/moq-archive/src/consumer/track.rs | 4 +- rs/moq-audio/src/encode/producer.rs | 6 +- rs/moq-bench/src/connection.rs | 46 ++-- rs/moq-boy/src/status.rs | 3 +- rs/moq-cli/src/main.rs | 2 +- rs/moq-cli/src/publish.rs | 8 +- rs/moq-cli/src/report.rs | 4 +- rs/moq-e2ee/README.md | 2 +- rs/moq-e2ee/benches/protect.rs | 4 +- rs/moq-e2ee/src/broadcast.rs | 34 ++- rs/moq-e2ee/src/tests.rs | 18 +- rs/moq-e2ee/tests/transport.rs | 4 +- rs/moq-ffi/src/datagram.rs | 5 +- rs/moq-ffi/src/media.rs | 4 +- rs/moq-ffi/src/producer.rs | 7 +- rs/moq-ffi/src/server.rs | 6 +- rs/moq-gst/src/sink/pad.rs | 4 +- rs/moq-gst/src/sink/session.rs | 53 ++-- rs/moq-mux/src/catalog/producer.rs | 17 +- rs/moq-mux/src/catalog/tracks.rs | 2 +- rs/moq-mux/src/container/flv/import.rs | 4 +- rs/moq-mux/src/container/fmp4/import.rs | 18 +- rs/moq-mux/src/container/mkv/import.rs | 6 +- rs/moq-mux/src/container/ts/export_test.rs | 9 +- rs/moq-mux/src/container/ts/import.rs | 12 +- rs/moq-mux/src/container/ts/passthrough.rs | 2 +- rs/moq-mux/src/container/ts/release_test.rs | 3 +- rs/moq-mux/src/container/ts/revision_test.rs | 6 +- rs/moq-mux/src/container/ts/si.rs | 7 +- rs/moq-net/benches/group.rs | 2 +- rs/moq-net/benches/track.rs | 2 +- rs/moq-net/src/coding/writer.rs | 44 +--- rs/moq-net/src/fuzz/ingest.rs | 2 +- rs/moq-net/src/fuzz/session.rs | 2 +- rs/moq-net/src/ietf/publisher.rs | 7 +- rs/moq-net/src/ietf/subscriber.rs | 8 +- rs/moq-net/src/ietf/subscriber/datagrams.rs | 2 +- rs/moq-net/src/lite/subscriber.rs | 14 +- rs/moq-net/src/lite/subscriber/fills.rs | 2 +- rs/moq-net/src/lite/test_transport.rs | 14 +- rs/moq-net/src/model/broadcast.rs | 118 +++++---- rs/moq-net/src/model/origin.rs | 4 +- rs/moq-net/src/model/resume.rs | 32 +-- rs/moq-net/src/model/resume_model.rs | 2 +- rs/moq-net/src/model/track.rs | 230 ++++++++++-------- rs/moq-net/src/model/track/fill.rs | 28 +-- rs/moq-net/src/transport.rs | 32 +-- rs/moq-net/src/transport/boxed.rs | 20 +- rs/moq-net/src/transport/memory.rs | 12 +- rs/moq-net/tests/integration/fetch_cancel.rs | 6 +- .../tests/integration/fetch_pipeline.rs | 2 +- rs/moq-net/tests/integration/flights.rs | 2 +- rs/moq-net/tests/integration/support/mock.rs | 2 +- rs/moq-net/tests/integration/untimed.rs | 2 +- rs/moq-relay/src/relay.rs | 12 +- rs/moq-relay/tests/drills.rs | 36 +-- rs/moq-relay/tests/integration/handoff.rs | 8 +- rs/moq-relay/tests/integration/smoke.rs | 2 +- rs/moq-rtsp/src/client.rs | 6 +- rs/moq-stats/src/produce.rs | 4 +- rs/moq-tokio/examples/chat.rs | 2 +- rs/moq-tokio/examples/clock.rs | 2 +- rs/moq-tokio/src/connection.rs | 176 ++++++-------- rs/moq-tokio/src/lib.rs | 2 +- rs/moq-tokio/src/listen.rs | 4 +- rs/moq-tokio/src/quic/web/send.rs | 4 +- rs/moq-tokio/src/quic/web/session.rs | 12 +- rs/moq-tokio/src/server.rs | 24 +- rs/moq-tokio/src/worker/group.rs | 7 +- rs/moq-tokio/tests/integration/backend.rs | 16 +- rs/moq-tokio/tests/integration/broadcast.rs | 8 +- rs/moq-tokio/tests/integration/max_age.rs | 3 +- rs/moq-tokio/tests/integration/reconnect.rs | 15 +- rs/moq-tokio/tests/integration/relay_fill.rs | 3 +- rs/moq-transcode/src/lib.rs | 9 +- rs/moq-transcode/src/rung.rs | 14 +- rs/moq-uring/src/quic/web/send.rs | 4 +- rs/moq-uring/src/transport/local.rs | 2 +- rs/moq-uring/tests/integration/web.rs | 6 +- rs/moq-video/src/decode/consumer.rs | 3 +- rs/moq-video/src/encode/capture.rs | 2 +- rs/moq-video/src/encode/producer.rs | 4 +- rs/moq-video/src/encode/publisher.rs | 6 +- rs/moq-webrtc/src/codec/av1.rs | 2 +- rs/moq-webrtc/src/codec/h264.rs | 2 +- rs/moq-webrtc/src/codec/h265.rs | 2 +- rs/moq-webrtc/src/codec/mod.rs | 2 +- rs/moq-webrtc/src/codec/opus.rs | 2 +- rs/qmux/src/session.rs | 10 +- rs/qmux/src/session/tests.rs | 6 +- test/interop/clients/rust/catalog.rs | 2 +- test/interop/clients/rust/control.rs | 2 +- test/interop/clients/rust/finish.rs | 4 +- test/interop/clients/rust/goaway.rs | 2 +- test/interop/clients/rust/hls.rs | 4 +- test/interop/clients/rust/tail.rs | 4 +- 101 files changed, 682 insertions(+), 683 deletions(-) diff --git a/doc/concept/identity.md b/doc/concept/identity.md index c1e958adf06..44851466fe6 100644 --- a/doc/concept/identity.md +++ b/doc/concept/identity.md @@ -197,7 +197,7 @@ while let Some(request) = claim.requested().await { // Takes the claim's instance, so readers resolved through the claim continue. // Hidden until its tracks exist. let job = request.route(RouteOptions::hidden())?; - let video = job.broadcast().create_track("video", info.clone())?; + let video = job.broadcast().create_track("video", info.clone()).context("video exists")?; // Announces the exact path under that instance and answers the waiting request. job.announce()?; spawn(run_job(video, job)); diff --git a/rs/hang/examples/video.rs b/rs/hang/examples/video.rs index 3c96c31f6f6..8dad03fa532 100644 --- a/rs/hang/examples/video.rs +++ b/rs/hang/examples/video.rs @@ -65,7 +65,7 @@ fn create_track(broadcast: &mut moq_net::broadcast::Producer) -> anyhow::Result< catalog.video.insert(video_track, video_config)?; // Publish the catalog as a "catalog.json" track in the broadcast. - let catalog_track = broadcast.create_track(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info())?; + let catalog_track = broadcast.create_track(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info()).context("the track already exists")?; // This catalog never changes, so its one group starts at zero, where the media's timeline does. let mut group = catalog_track.append_group(moq_net::Timestamp::ZERO)?; group.write_frame(moq_net::Timestamp::ZERO, catalog.to_json()?)?; @@ -74,7 +74,7 @@ fn create_track(broadcast: &mut moq_net::broadcast::Producer) -> anyhow::Result< // Actually create the media track now. // track_info() pins the microsecond timescale that the legacy container encodes with, and // declares the publisher priority so a subscriber orders this against a broadcast's audio. - let track = broadcast.create_track(video_track, hang::container::track_info(hang::catalog::PRIORITY.video))?; + let track = broadcast.create_track(video_track, hang::container::track_info(hang::catalog::PRIORITY.video)).context("the track already exists")?; Ok(track) } diff --git a/rs/libmoq/src/publish.rs b/rs/libmoq/src/publish.rs index 694cfc4018f..1b05cab0eef 100644 --- a/rs/libmoq/src/publish.rs +++ b/rs/libmoq/src/publish.rs @@ -517,7 +517,7 @@ impl Publish { } = self.broadcast(broadcast)?; let broadcast = broadcast.clone(); let name = broadcast.unique_name(&format!(".{}", init.format)); - let request = broadcast.reserve_track(name)?; + let request = broadcast.reserve_track(name).ok_or(moq_net::Error::Duplicate)?; let track = import::Track::audio(request, catalog.reserve().with_interval(interval), init)?; let children = children.clone(); @@ -539,7 +539,7 @@ impl Publish { } = self.broadcast(broadcast)?; let broadcast = broadcast.clone(); let name = broadcast.unique_name(&format!(".{}", init.format)); - let request = broadcast.reserve_track(name)?; + let request = broadcast.reserve_track(name).ok_or(moq_net::Error::Duplicate)?; let priority = init.priority; let track = import::Track::video(request, catalog.reserve().with_interval(interval), init)?; @@ -1190,7 +1190,10 @@ impl Publish { /// indices they have in the group rather than restarting at 0. pub fn group_request_accept(&mut self, request: Id) -> Result { let request = self.group_request.remove(request).ok_or(Error::NotFound)?; - let group = request.fill.accept(request.start, None)?; + let group = request + .fill + .accept(request.start, None)? + .ok_or(moq_net::Error::Duplicate)?; self.insert_group(group) } @@ -1218,7 +1221,7 @@ impl Publish { let children = self.children(broadcast)?; let broadcast = self.producer(broadcast)?; let info = info.unwrap_or_default(); - let track = broadcast.create_track(name, info)?; + let track = broadcast.create_track(name, info).ok_or(moq_net::Error::Duplicate)?; let raw = Kept { inner: track, children: children.clone(), @@ -1334,7 +1337,10 @@ impl Publish { .with_timescale(moq_net::Timescale::MILLI) .with_compression(moq_net::track::Compression::Deflate); info.refresh = moq_net::track::Refresh::default().with_ratio(refresh); - let track = broadcast.producer.create_track(name, info)?; + let track = broadcast + .producer + .create_track(name, info) + .ok_or(moq_net::Error::Duplicate)?; let producer = publish(&broadcast.catalog, track)?; Ok(Data { producer, @@ -1884,7 +1890,10 @@ struct DatagramDemand { impl Publish { pub fn datagrams(&mut self, broadcast: Id, name: &str, info: moq_net::datagram::Info) -> Result { let children = self.children(broadcast)?; - let producer = self.producer(broadcast)?.create_datagrams(name, info)?; + let producer = self + .producer(broadcast)? + .create_datagrams(name, info) + .ok_or(moq_net::Error::Duplicate)?; let entry = Datagrams { producer, children: children.clone(), diff --git a/rs/libmoq/src/server.rs b/rs/libmoq/src/server.rs index 15ccc156795..aa717ee9ed7 100644 --- a/rs/libmoq/src/server.rs +++ b/rs/libmoq/src/server.rs @@ -30,7 +30,10 @@ pub struct Server { impl Server { /// Serve `server`, delivering each incoming session as a request handle via `callback`. pub fn listen(&mut self, server: moq_tokio::Server, callback: OnStatus) -> Result { - let addr = server.local_addr()?.to_string(); + let addr = server + .local_addr() + .ok_or(moq_tokio::Error::NoBackend("no QUIC listener configured"))? + .to_string(); let fingerprints = server.certificates().fingerprints(); let (task, closed) = Task::new(callback); let id = self.task.insert(ServerEntry { diff --git a/rs/moq-archive/src/consumer/mod.rs b/rs/moq-archive/src/consumer/mod.rs index a9b3d83631a..f0a9031cd02 100644 --- a/rs/moq-archive/src/consumer/mod.rs +++ b/rs/moq-archive/src/consumer/mod.rs @@ -242,7 +242,7 @@ impl Consumer { fn apply(&mut self, refreshed: Refreshed) -> Result<()> { for (name, info, index) in refreshed.added { - let producer = self.broadcast.create_track(name.as_str(), info)?; + let producer = self.broadcast.create_track(name.as_str(), info).ok_or(moq_net::Error::Duplicate)?; let dynamic = producer.requests(); self.tracks.insert( name, diff --git a/rs/moq-archive/src/consumer/track.rs b/rs/moq-archive/src/consumer/track.rs index 39b33ef7040..47dcdb06bce 100644 --- a/rs/moq-archive/src/consumer/track.rs +++ b/rs/moq-archive/src/consumer/track.rs @@ -169,7 +169,7 @@ impl Asker<'_> { } } - fn accept(self, sequence: u64) -> moq_net::Result { + fn accept(self, sequence: u64) -> moq_net::Result> { match self { Self::Fill(fill) => fill.accept(sequence, None), Self::Lookup(lookup) => lookup.accept(sequence, None), @@ -388,7 +388,7 @@ async fn serve_group(shared: &Shared, index: &Mutex, a { return; } - let Ok(mut producer) = asker.accept(sequence) else { + let Ok(Some(mut producer)) = asker.accept(sequence) else { return; }; for (index, stored) in stored { diff --git a/rs/moq-audio/src/encode/producer.rs b/rs/moq-audio/src/encode/producer.rs index a1913f851ed..19db1a85250 100644 --- a/rs/moq-audio/src/encode/producer.rs +++ b/rs/moq-audio/src/encode/producer.rs @@ -165,13 +165,15 @@ impl Reserved { // The catalog's info carries the microsecond timescale audio hang frames stamp, so // Lite05 subscribers know what scale to expect and the model layer accepts // Frame::timestamp on append, plus whatever max age the catalog declared. - Some(name) => broadcast.create_track(name.clone(), catalog.track_info(hang::catalog::PRIORITY.audio))?, + Some(name) => broadcast + .create_track(name.clone(), catalog.track_info(hang::catalog::PRIORITY.audio)) + .ok_or_else(|| hang::Error::Duplicate(name.clone()))?, // Mirrors the video side, which derives a unique name from the codec // rather than making every caller invent one. None => broadcast.unique_track( &format!(".{}", options.config.codec), catalog.track_info(hang::catalog::PRIORITY.audio), - )?, + ), }; let track = catalog.audio( track, diff --git a/rs/moq-bench/src/connection.rs b/rs/moq-bench/src/connection.rs index c9a79cf184f..217734803b8 100644 --- a/rs/moq-bench/src/connection.rs +++ b/rs/moq-bench/src/connection.rs @@ -6,7 +6,7 @@ use std::time::Duration; use bytes::Bytes; use moq_net::{broadcast, group, track}; -use moq_tokio::Status; +use moq_tokio::connection::Phase; use rand::RngExt; use serde::{Deserialize, Serialize}; use tokio::task::JoinSet; @@ -141,9 +141,9 @@ pub async fn run(ctx: Connection) { .with_timescale(moq_net::Timescale::MILLI) .with_max_age(None), ) { - Ok(track) => track, - Err(err) => { - tracing::error!(connection, %err, "failed to create track"); + Some(track) => track, + None => { + tracing::error!(connection, "the track already exists"); continue; } }; @@ -162,7 +162,7 @@ pub async fn run(ctx: Connection) { } let client = client.with_publisher(&publish).with_subscriber(consume.clone()); - let mut reconnect = client.connect(url); + let reconnect = client.connect(url); match &role { Role::Mesh if rolled.subscribe > 0 => { @@ -186,29 +186,27 @@ pub async fn run(ctx: Connection) { Role::Mesh | Role::FanoutPublisher { .. } => {} } - // The status loop doubles as the keep-alive: it tracks connect/disconnect for + // The state loop doubles as the keep-alive: it tracks connect/disconnect for // the gauge and returns once the reconnect loop gives up. + let monitor = reconnect.monitor(); + let mut observed = monitor.state(); let mut connected = false; loop { + // A GOAWAY's migration still serves on the old session, so it stays connected. + let serving = matches!(observed.phase, Phase::Connected { .. } | Phase::Migrating { .. }); + // Edge-triggered so repeated same-state events can't drift the gauge. + if serving && !connected { + stats.connections.fetch_add(1, Ordering::Relaxed); + for published in publishing.iter().filter_map(std::sync::Weak::upgrade) { + published.establish(); + } + } else if !serving && connected { + stats.connections.fetch_sub(1, Ordering::Relaxed); + } + connected = serving; tokio::select! { - status = reconnect.status() => match status { - // Edge-triggered so repeated same-state events can't drift the gauge. - Ok(Status::Connected) => { - if !connected { - connected = true; - stats.connections.fetch_add(1, Ordering::Relaxed); - for published in publishing.iter().filter_map(std::sync::Weak::upgrade) { - published.establish(); - } - } - } - Ok(Status::Disconnected) => { - if connected { - connected = false; - stats.connections.fetch_sub(1, Ordering::Relaxed); - } - } - Ok(_) => {} + changed = monitor.state_changed(observed.revision) => match changed { + Ok(next) => observed = next, Err(err) => { tracing::warn!(connection, %err, "connection gave up"); break; diff --git a/rs/moq-boy/src/status.rs b/rs/moq-boy/src/status.rs index 9715d6cbc64..6dcc8dcb12d 100644 --- a/rs/moq-boy/src/status.rs +++ b/rs/moq-boy/src/status.rs @@ -47,7 +47,8 @@ impl StatusPublisher { .with_timescale(moq_net::Timescale::MILLI) // A joiner asks for a fresh snapshot once the deltas outweigh eight of them. .with_refresh(moq_net::track::Refresh::default().with_ratio(8)), - )?; + ) + .ok_or_else(|| anyhow::anyhow!("the status track already exists"))?; Ok(Self { producer: moq_json::snapshot::Producer::new(producer, moq_json::snapshot::Config::default()), diff --git a/rs/moq-cli/src/main.rs b/rs/moq-cli/src/main.rs index d0d17423e17..e8c47c5276e 100644 --- a/rs/moq-cli/src/main.rs +++ b/rs/moq-cli/src/main.rs @@ -244,7 +244,7 @@ fn is_public_transport(transport: moq_tokio::Transport, public_quic: bool) -> bo /// Serve ordinary clients from an already-bound listener, each through its lease. fn spawn_serve(tasks: &mut JoinSet>, mut listener: moq_tokio::Listener, serving: Serving) { - if let Ok(addr) = listener.local_addr() { + if let Some(addr) = listener.local_addr() { tracing::info!(%addr, "listening"); } tasks.spawn(async move { diff --git a/rs/moq-cli/src/publish.rs b/rs/moq-cli/src/publish.rs index 88d42cb24c0..16356d5b47a 100644 --- a/rs/moq-cli/src/publish.rs +++ b/rs/moq-cli/src/publish.rs @@ -445,7 +445,7 @@ impl Publish { let catalog = moq_mux::catalog::Producer::new(&mut broadcast, config)?; let decoder = match format { PublishFormat::Avc3 => { - let track = broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video))?; + let track = broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)); let import = moq_mux::codec::h264::Import::new(track, catalog.reserve(), Default::default())?; let split = Box::new(moq_mux::codec::h264::Split::new()); PublishDecoder::Avc3 { @@ -1602,8 +1602,7 @@ pub(crate) mod tests { // Section-framed verbatim stream (SCTE-35, stream_type 0x86). let section = broadcast .broadcast() - .unique_track(".scte35", hang::container::track_info(hang::catalog::PRIORITY.text)) - .unwrap(); + .unique_track(".scte35", hang::container::track_info(hang::catalog::PRIORITY.text)); let mut section_track = tscat::Track::new(SECTION_PID); section_track.verbatim = Some(tscat::Verbatim::new(0x86, tscat::Framing::Section)); catalog @@ -1631,8 +1630,7 @@ pub(crate) mod tests { // Whole-PES stream (undecoded private data, stream_type 0x06). let pes = broadcast .broadcast() - .unique_track(".data", hang::container::track_info(hang::catalog::PRIORITY.text)) - .unwrap(); + .unique_track(".data", hang::container::track_info(hang::catalog::PRIORITY.text)); let mut pes_track = tscat::Track::new(PES_PID); pes_track.pes_packet = Some(tscat::PesPacket::new(0x06)); catalog diff --git a/rs/moq-cli/src/report.rs b/rs/moq-cli/src/report.rs index d259e6890ba..66c1cd1e39d 100644 --- a/rs/moq-cli/src/report.rs +++ b/rs/moq-cli/src/report.rs @@ -54,7 +54,9 @@ impl ReportTrack { .with_priority(PRIORITY) .with_compression(moq_net::track::Compression::Deflate) .with_refresh(moq_net::track::Refresh::default().with_ratio(8)); - let track = broadcast.create_track(name, info)?; + let track = broadcast + .create_track(name, info) + .ok_or_else(|| anyhow::anyhow!("the track {name} already exists"))?; Ok(Self { track: Some(moq_json::snapshot::Producer::new(track.clone(), Default::default())), inner: track, diff --git a/rs/moq-e2ee/README.md b/rs/moq-e2ee/README.md index 21558066602..eb6139f159b 100644 --- a/rs/moq-e2ee/README.md +++ b/rs/moq-e2ee/README.md @@ -30,7 +30,7 @@ let generation = credential.produce(); let options = RouteOptions::hidden().with_instance(generation.epoch().instance(), 0); let route = origin.route(&credential.path("meeting.hang")?, options)?; let protected = broadcast::Producer::new(route.broadcast().clone(), generation.clone()); -let video = protected.create_track("video", None)?; +let video = protected.create_track("video", None)?.context("video already exists")?; route.announce()?; ``` diff --git a/rs/moq-e2ee/benches/protect.rs b/rs/moq-e2ee/benches/protect.rs index 723b8a7ff24..8a2e4a7aac2 100644 --- a/rs/moq-e2ee/benches/protect.rs +++ b/rs/moq-e2ee/benches/protect.rs @@ -36,7 +36,7 @@ fn bench_protect(c: &mut Criterion) { let info = moq_net::track::Info::default() .with_timescale(moq_net::Timescale::MILLI) .with_max_age(Duration::ZERO); - let mut producer = broadcast(&credential).create_track("video", info).unwrap(); + let mut producer = broadcast(&credential).create_track("video", info).unwrap().unwrap(); let mut ms = 0u64; b.iter(|| { ms += 1; @@ -50,7 +50,7 @@ fn bench_protect(c: &mut Criterion) { group.throughput(Throughput::Bytes(opus.len() as u64)); group.bench_function("datagram_opus160", |b| { let info = moq_net::datagram::Info::default().with_timescale(moq_net::Timescale::MILLI); - let mut producer = broadcast(&credential).create_datagrams("audio", info).unwrap(); + let mut producer = broadcast(&credential).create_datagrams("audio", info).unwrap().unwrap(); let mut ms = 0u64; b.iter(|| { ms += 1; diff --git a/rs/moq-e2ee/src/broadcast.rs b/rs/moq-e2ee/src/broadcast.rs index 47caf4e14e7..67e5e5f5733 100644 --- a/rs/moq-e2ee/src/broadcast.rs +++ b/rs/moq-e2ee/src/broadcast.rs @@ -42,16 +42,18 @@ impl Producer { /// /// # Errors /// - /// [`Error::Identity`] if `semantic` exceeds 65535 bytes, or a net error if the broadcast + /// [`Error::Identity`] if `semantic` exceeds 65535 bytes. `None` while the broadcast /// already holds it. pub fn create_track( &self, semantic: &str, info: impl Into>, - ) -> Result { + ) -> Result> { let name = self.generation.name(semantic)?; - let track = self.inner.create_track(name.as_str(), info)?; - self.generation.produce(track, semantic) + let Some(track) = self.inner.create_track(name.as_str(), info) else { + return Ok(None); + }; + self.generation.produce(track, semantic).map(Some) } /// Reserve the track for `semantic` under its physical name, to accept once it is wanted. @@ -62,16 +64,18 @@ impl Producer { /// # Errors /// /// Same as [`Self::create_track`]. - pub fn reserve_track(&self, semantic: &str) -> Result { + pub fn reserve_track(&self, semantic: &str) -> Result> { let name = self.generation.name(semantic)?; - let request = self.inner.reserve_track(name.as_str())?; + let Some(request) = self.inner.reserve_track(name.as_str()) else { + return Ok(None); + }; match self.generation.claim(semantic, Domain::Group) { - Ok(claim) => Ok(track::Request::new( + Ok(claim) => Ok(Some(track::Request::new( request, self.generation.clone(), claim, semantic.to_string(), - )), + ))), Err(err) => { request.reject(moq_net::Error::Cancel); Err(err) @@ -87,12 +91,18 @@ impl Producer { /// /// # Errors /// - /// [`Error::Identity`] if `semantic` exceeds 65535 bytes, or a net error if the broadcast + /// [`Error::Identity`] if `semantic` exceeds 65535 bytes. `None` while the broadcast /// already holds a live datagram track of that name. - pub fn create_datagrams(&self, semantic: &str, info: moq_net::datagram::Info) -> Result { + pub fn create_datagrams( + &self, + semantic: &str, + info: moq_net::datagram::Info, + ) -> Result> { let name = self.generation.name(semantic)?; - let track = self.inner.create_datagrams(name.as_str(), info)?; - self.generation.produce_datagrams(track, semantic) + let Some(track) = self.inner.create_datagrams(name.as_str(), info) else { + return Ok(None); + }; + self.generation.produce_datagrams(track, semantic).map(Some) } /// Create a handler for requests to tracks nobody created or reserved, named by their diff --git a/rs/moq-e2ee/src/tests.rs b/rs/moq-e2ee/src/tests.rs index 29711b3a7bd..0591fcd996d 100644 --- a/rs/moq-e2ee/src/tests.rs +++ b/rs/moq-e2ee/src/tests.rs @@ -780,7 +780,7 @@ fn resolve(subscribing: &kio::Pending) -> Result Fixture { async fn grouped_roundtrip(version: &str, payload: &[u8]) { kio::clock::timeout(TEST_TIMEOUT, async { let fixture = connect_protected(version.parse().unwrap(), "video").await; - let mut producer = fixture.producer.create_track("video", timed()).unwrap(); + let mut producer = fixture.producer.create_track("video", timed()).unwrap().expect("a free name"); let mut consumer = fixture .consumer .subscribe( @@ -125,7 +125,7 @@ async fn grouped_over_ietf() { async fn datagram_roundtrip(version: &str, plaintext: &[u8]) { kio::clock::timeout(TEST_TIMEOUT, async { let fixture = connect_protected(version.parse().unwrap(), "audio").await; - let mut producer = fixture.producer.create_datagrams("audio", timed_datagrams()).unwrap(); + let mut producer = fixture.producer.create_datagrams("audio", timed_datagrams()).unwrap().expect("a free name"); let mut consumer = fixture.consumer.datagrams("audio").unwrap(); // A remote subscriber is live once its request reaches the publisher, which sees its priority. consumer.set_priority(1); diff --git a/rs/moq-ffi/src/datagram.rs b/rs/moq-ffi/src/datagram.rs index 8a0577ca86d..048ea7cd4bd 100644 --- a/rs/moq-ffi/src/datagram.rs +++ b/rs/moq-ffi/src/datagram.rs @@ -55,7 +55,10 @@ impl MoqBroadcastProducer { let _guard = crate::ffi::enter(); let info = info.unwrap_or_default().try_into()?; self.with_state(|state| { - let producer = state.broadcast.create_datagrams(name, info)?; + let producer = state + .broadcast + .create_datagrams(name, info) + .ok_or(moq_net::Error::Duplicate)?; MoqDatagramProducer::child(producer, &state.children) }) } diff --git a/rs/moq-ffi/src/media.rs b/rs/moq-ffi/src/media.rs index 084c4d840e6..edbe7c93de8 100644 --- a/rs/moq-ffi/src/media.rs +++ b/rs/moq-ffi/src/media.rs @@ -1457,8 +1457,8 @@ fn reserve_track( format: &impl std::fmt::Display, ) -> Result { let name = track.unwrap_or_else(|| broadcast.unique_name(&format!(".{format}"))); - broadcast.reserve_track(name).map_err(|err| MoqError::Codec { - reason: format!("init failed: {err}"), + broadcast.reserve_track(name.clone()).ok_or_else(|| MoqError::Codec { + reason: format!("init failed: the track {name} already exists"), }) } diff --git a/rs/moq-ffi/src/producer.rs b/rs/moq-ffi/src/producer.rs index c9370eba1a0..7e5addeeef7 100644 --- a/rs/moq-ffi/src/producer.rs +++ b/rs/moq-ffi/src/producer.rs @@ -437,7 +437,10 @@ impl MoqBroadcastProducer { let _guard = crate::ffi::enter(); self.with_state(|state| { let info = raw_track_info(info)?; - let track = state.broadcast.create_track(name, Some(info))?; + let track = state + .broadcast + .create_track(name, Some(info)) + .ok_or(moq_net::Error::Duplicate)?; MoqTrackProducer::child(track, &state.children) }) } @@ -640,7 +643,7 @@ impl MoqFill { /// at [`start`](Self::start)'s frame, so its frames keep their indices. pub fn accept(&self, start: u64) -> Result, MoqError> { let _guard = crate::ffi::enter(); - let group = self.inner.accept(start, None)?; + let group = self.inner.accept(start, None)?.ok_or(moq_net::Error::Duplicate)?; Ok(Arc::new(MoqGroupProducer::from_inner(group))) } diff --git a/rs/moq-ffi/src/server.rs b/rs/moq-ffi/src/server.rs index 3810f4859c0..7c33990bd68 100644 --- a/rs/moq-ffi/src/server.rs +++ b/rs/moq-ffi/src/server.rs @@ -136,12 +136,12 @@ async fn serve( } }; match listener.local_addr() { - Ok(addr) => { + Some(addr) => { let _ = bound.send(Ok(addr.to_string())); } - Err(err) => { + None => { let _ = bound.send(Err(MoqError::Bind { - reason: format!("{err}"), + reason: "no QUIC listener configured".to_string(), })); listener.close().await; return; diff --git a/rs/moq-gst/src/sink/pad.rs b/rs/moq-gst/src/sink/pad.rs index 45229505863..434f8fcae52 100644 --- a/rs/moq-gst/src/sink/pad.rs +++ b/rs/moq-gst/src/sink/pad.rs @@ -688,7 +688,9 @@ impl Pad { name: String, structure: &gst::StructureRef, ) -> Result { - let request = broadcast.reserve_track(name.clone())?; + let request = broadcast + .reserve_track(name.clone()) + .ok_or_else(|| anyhow::anyhow!("the track {name} already exists"))?; let producer = request.accept(hang::container::track_info(hang::catalog::PRIORITY.text)); let mut config = hang::catalog::TextConfig::new(hang::catalog::TextFormat::Vtt); diff --git a/rs/moq-gst/src/sink/session.rs b/rs/moq-gst/src/sink/session.rs index 33b73953aa0..59f7078455e 100644 --- a/rs/moq-gst/src/sink/session.rs +++ b/rs/moq-gst/src/sink/session.rs @@ -13,6 +13,8 @@ use gst::glib; use gst::prelude::*; use gst::subclass::prelude::*; +use moq_tokio::connection::{Monitor, Observation, Phase}; + use super::MoqSink as Element; pub(crate) static RUNTIME: LazyLock = LazyLock::new(|| { @@ -435,7 +437,7 @@ async fn wait_for_registration(registered: Arc) { } async fn forward_registered( - mut reconnect: moq_tokio::Connection, + reconnect: moq_tokio::Connection, origin: moq_net::origin::Producer, status: Arc, completion: CompletionHandle, @@ -450,28 +452,37 @@ async fn forward_registered( let mut send_bandwidth = reconnect.send_bandwidth(); let mut recv_bandwidth = reconnect.recv_bandwidth(); let mut connection_stats = reconnect.monitor(); + let monitor = reconnect.monitor(); + // None until the first observation, which reports too: a session may connect before + // registration ends. + let mut revision = None; loop { tokio::select! { - // Poll status first: on a terminal error it is ready immediately, so we exit rather than - // spinning on the bandwidth channels the loop closes as it stops. + // Poll the state first: once the loop stops it is ready immediately, so we exit rather + // than spinning on the bandwidth channels the loop closes as it stops. biased; - result = reconnect.status() => match result { - Ok(state) => { - let connection = match state { - moq_tokio::Status::Connected => ConnectionStatus::Connected, - _ => ConnectionStatus::Disconnected, + result = next_state(&monitor, revision) => match result { + Ok(observed) if !matches!(observed.phase, Phase::Closed { .. }) => { + revision = Some(observed.revision); + // A GOAWAY's migration still serves on the old session. + let (connection, version) = match &observed.phase { + Phase::Connected { version, .. } | Phase::Migrating { version, .. } => { + (ConnectionStatus::Connected, Some(version.to_string())) + } + _ => (ConnectionStatus::Disconnected, None), }; - status.set(connection, reconnect.version().map(|v| v.to_string())); - match state { - moq_tokio::Status::Connected => gst::info!(CAT, "session connected"), - moq_tokio::Status::Disconnected => gst::warning!(CAT, "session disconnected, reconnecting"), + status.set(connection, version); + match observed.phase { + Phase::Connected { .. } => gst::info!(CAT, "session connected"), + Phase::Migrating { .. } => gst::info!(CAT, "session migrating after a GOAWAY"), + Phase::Disconnected { .. } => gst::warning!(CAT, "session disconnected, reconnecting"), _ => {} } notify(&element, &["status", "connected", "moq-version", "connection-stats"]); } - Err(_) => { + _ => { // `closed` tells a stop from a give-up. A stop is what `Session::stop` asked for: its // abort cannot cancel a poll already in flight, so the loop's end can reach the task // before the task ends. @@ -503,19 +514,21 @@ async fn forward_registered( Err(_) => return, }, result = connection_stats.presence_changed() => match result { - Ok(_) => { - // A flap that lands back on the reported status (Connected -> Disconnected -> - // Connected) never wakes the status arm above, so refresh the cached version - // here or moq-version would keep the previous session's value. - status.set(status.status(), reconnect.version().map(|v| v.to_string())); - notify(&element, &["sessions", "connection-stats", "moq-version"]); - } + Ok(_) => notify(&element, &["sessions", "connection-stats"]), Err(_) => return, }, } } } +/// The connection's state at once the first time, then once it changes from revision `after`. +async fn next_state(monitor: &Monitor, after: Option) -> moq_tokio::Result { + match after { + None => Ok(monitor.state()), + Some(after) => monitor.state_changed(after).await, + } +} + /// Emit a GObject `notify` for each named property, on the connect/disconnect/bitrate edges, never per /// sample. pub(super) fn notify(element: &glib::WeakRef, props: &[&str]) { diff --git a/rs/moq-mux/src/catalog/producer.rs b/rs/moq-mux/src/catalog/producer.rs index 9ecd387fa38..7a2e1d0b7f7 100644 --- a/rs/moq-mux/src/catalog/producer.rs +++ b/rs/moq-mux/src/catalog/producer.rs @@ -515,13 +515,17 @@ impl Producer { // Compressed, as `default_track_info` sets: catalog JSON is small and repetitive. Fresh as // long as the media, so a reader as far behind holds each update until its timestamp. let info = hang::Catalog::default_track_info().with_max_age(config.max_age); - let hang_track = broadcast.create_track(hang::Catalog::DEFAULT_NAME, info.clone())?; + let hang_track = broadcast + .create_track(hang::Catalog::DEFAULT_NAME, info.clone()) + .ok_or_else(|| hang::Error::Duplicate(hang::Catalog::DEFAULT_NAME.to_string()))?; // The MSF track is the same catalog in another encoding, so it takes the same // priority. Leaving it at the default would rank a subscriber reading MSF // below every media track on a relay's upstream leg. It stays uncompressed: MSF is // read by other implementations, which hang's compression decisions don't cover. let msf_info = info.with_compression(moq_net::track::Compression::None); - let msf_track = broadcast.create_track(moq_msf::DEFAULT_NAME, msf_info)?; + let msf_track = broadcast + .create_track(moq_msf::DEFAULT_NAME, msf_info) + .ok_or_else(|| hang::Error::Duplicate(moq_msf::DEFAULT_NAME.to_string()))?; // Disable deltas for now to stay byte-compatible with consumers that only read snapshots. let json_config = moq_json::snapshot::Config::default().with_deltas(false); @@ -889,7 +893,7 @@ impl Producer { &self, name: &str, info: moq_net::track::Info, - ) -> crate::Result { + ) -> moq_net::track::Producer { let mut state = take(&self.current); let base = match name.rsplit_once('/') { Some((base, n)) if n.parse::().is_ok() && state.revisions.contains_key(base) => base, @@ -898,14 +902,13 @@ impl Producer { let revision = state.revisions.entry(base.to_string()).or_default(); loop { *revision += 1; - match self + // None when someone else published that name explicitly; try the next. + if let Some(track) = self .outputs .broadcast .create_track(format!("{base}/{revision}"), info.clone()) { - // Someone else published that name explicitly; try the next. - Err(moq_net::Error::Duplicate) => continue, - track => return Ok(track?), + return track; } } } diff --git a/rs/moq-mux/src/catalog/tracks.rs b/rs/moq-mux/src/catalog/tracks.rs index aa3aa93a369..428aa42c6f1 100644 --- a/rs/moq-mux/src/catalog/tracks.rs +++ b/rs/moq-mux/src/catalog/tracks.rs @@ -610,7 +610,7 @@ impl> Rendition { info: moq_net::track::Info, interval: Option, ) -> crate::Result> { - let track = self.catalog.fresh_track(&self.name, info)?; + let track = self.catalog.fresh_track(&self.name, info); let rendition = self.catalog.rendition(track.name())?; self.catalog.media(track, container, rendition, None, interval) } diff --git a/rs/moq-mux/src/container/flv/import.rs b/rs/moq-mux/src/container/flv/import.rs index cbf923e9ca4..d8e18cea5e7 100644 --- a/rs/moq-mux/src/container/flv/import.rs +++ b/rs/moq-mux/src/container/flv/import.rs @@ -739,7 +739,7 @@ impl Import { } Ok(self .broadcast - .unique_track(".flv-v", self.catalog.track_info(hang::catalog::PRIORITY.video))?) + .unique_track(".flv-v", self.catalog.track_info(hang::catalog::PRIORITY.video))) } /// Retire any existing audio track `track_id` and allocate a fresh one. @@ -749,7 +749,7 @@ impl Import { } Ok(self .broadcast - .unique_track(".flv-a", self.catalog.track_info(hang::catalog::PRIORITY.audio))?) + .unique_track(".flv-a", self.catalog.track_info(hang::catalog::PRIORITY.audio))) } /// Close the current group on every track and reopen at `start`. diff --git a/rs/moq-mux/src/container/fmp4/import.rs b/rs/moq-mux/src/container/fmp4/import.rs index adee5f6f85b..88cada2b367 100644 --- a/rs/moq-mux/src/container/fmp4/import.rs +++ b/rs/moq-mux/src/container/fmp4/import.rs @@ -607,10 +607,8 @@ impl Import { // Declare the track at the fMP4's native timescale, which the moq-hang draft requires // of a CMAF track: frame timestamps are emitted at this same scale (see `extract`), so // each one carries its fragment's earliest presentation time exactly. - let track = self.broadcast.create_track( - self.broadcast.unique_name(".m4s"), - self.catalog.track_info(kind.priority()).with_timescale(timescale), - )?; + let track = self.broadcast.unique_track(".m4s", + self.catalog.track_info(kind.priority()).with_timescale(timescale)); // Join the broadcast's join interval, measured: an fMP4 declares no GOP. let member = Some(self.catalog.join(None)); @@ -657,10 +655,8 @@ impl Import { Kind::Video => (".mp4-v", crate::container::Kind::Video), Kind::Audio => (".mp4-a", crate::container::Kind::Audio), }; - let track = self.broadcast.create_track( - self.broadcast.unique_name(suffix), - self.catalog.track_info(kind.priority()), - )?; + let track = self.broadcast.unique_track(suffix, + self.catalog.track_info(kind.priority())); let wire = crate::catalog::hang::Container::new(&Container::Legacy, wire_kind)?; Ok(match kind { Kind::Video => Output::Video(reserved.video(track, wire, self.init_video(trak, moov)?)?), @@ -690,10 +686,8 @@ impl Import { // The picker label is the HandlerBox name; `vlab` is an opaque source identifier. config.label = (!trak.mdia.hdlr.name.is_empty()).then(|| trak.mdia.hdlr.name.clone()); let wire = crate::catalog::hang::Container::new(&config.container, crate::container::Kind::Data)?; - let track = self.broadcast.create_track( - self.broadcast.unique_name(".mp4-t"), - self.catalog.track_info(hang::catalog::PRIORITY.text), - )?; + let track = self.broadcast.unique_track(".mp4-t", + self.catalog.track_info(hang::catalog::PRIORITY.text)); let producer = reserved.text(track, wire, config)?; self.text.insert( trak.tkhd.track_id, diff --git a/rs/moq-mux/src/container/mkv/import.rs b/rs/moq-mux/src/container/mkv/import.rs index ed5052ff84c..0297806204c 100644 --- a/rs/moq-mux/src/container/mkv/import.rs +++ b/rs/moq-mux/src/container/mkv/import.rs @@ -655,10 +655,8 @@ impl Import { return Err(Error::StreamedCmaf.into()); } - let track = self.broadcast.create_track( - self.broadcast.unique_name(suffix), - self.catalog.track_info(kind.priority()), - )?; + let track = self.broadcast.unique_track(suffix, + self.catalog.track_info(kind.priority())); // Build the media producer before publishing the rendition. It is fallible (its // timeline track can collide), and a rendition published for a track we then fail // to produce would be advertised to consumers but never served. diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index 89ad03d5029..9fea380a753 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -1768,8 +1768,7 @@ async fn export_scte35_roundtrip() { // `Import` (which consumes it); the producer stays alive so the exporter can // subscribe to the retained track. let scte = broadcast - .unique_track(".scte35", hang::container::track_info(hang::catalog::PRIORITY.video)) - .unwrap(); + .unique_track(".scte35", hang::container::track_info(hang::catalog::PRIORITY.video)); let scte_name = scte.name().to_string(); { let track = tscat::Track { @@ -1909,8 +1908,7 @@ async fn assert_unknown_stream_type(pes: bool) { .unwrap(); let reserved = catalog.reserve(); let track = broadcast - .unique_track(".opaque", hang::container::track_info(hang::catalog::PRIORITY.video)) - .unwrap(); + .unique_track(".opaque", hang::container::track_info(hang::catalog::PRIORITY.video)); let mut entry = tscat::Track::new(PID); let payload = match pes { true => { @@ -2013,8 +2011,7 @@ async fn export_pes_packet_roundtrip() { // Build the PES track BEFORE moving `broadcast` into `Import`; the // producer stays alive so the exporter can subscribe to the retained track. let data_track = broadcast - .unique_track(".data", hang::container::track_info(hang::catalog::PRIORITY.video)) - .unwrap(); + .unique_track(".data", hang::container::track_info(hang::catalog::PRIORITY.video)); let data_name = data_track.name().to_string(); { let mut track = tscat::Track::new(DATA_PID); diff --git a/rs/moq-mux/src/container/ts/import.rs b/rs/moq-mux/src/container/ts/import.rs index 3cd3040fb46..1905ccb748e 100644 --- a/rs/moq-mux/src/container/ts/import.rs +++ b/rs/moq-mux/src/container/ts/import.rs @@ -1013,7 +1013,7 @@ impl Import { Some(StreamType::H264) => { let track = self .broadcast - .unique_track(".avc3", self.catalog.track_info(hang::catalog::PRIORITY.video))?; + .unique_track(".avc3", self.catalog.track_info(hang::catalog::PRIORITY.video)); Stream::H264 { split: h264::Split::new(), assembly: { @@ -1027,7 +1027,7 @@ impl Import { Some(StreamType::H265) => { let track = self .broadcast - .unique_track(".hev1", self.catalog.track_info(hang::catalog::PRIORITY.video))?; + .unique_track(".hev1", self.catalog.track_info(hang::catalog::PRIORITY.video)); Stream::H265 { split: h265::Split::new(), assembly: video::Assembly::new(video::Codec::Hevc), @@ -1068,7 +1068,7 @@ impl Import { Ok(config) => { let track = self .broadcast - .unique_track(".opus", self.catalog.track_info(hang::catalog::PRIORITY.audio))?; + .unique_track(".opus", self.catalog.track_info(hang::catalog::PRIORITY.audio)); let mut config: hang::catalog::AudioConfig = config.into(); config.container = self.container.clone(); Stream::Opus(Box::new(OpusStream { @@ -2251,7 +2251,7 @@ fn register_verbatim( // stream (SCTE-35 cues, teletext, DVB subtitles) is tiny and timing-critical, so // it should never queue behind a media backlog, and it's too small to starve // anything by sitting above one. - let track = broadcast.unique_track(".ts", catalog.track_info(hang::catalog::PRIORITY.text))?; + let track = broadcast.unique_track(".ts", catalog.track_info(hang::catalog::PRIORITY.text)); let name = track.name().to_string(); // Build the media producer before advertising the track. It is fallible (its @@ -4106,7 +4106,7 @@ impl AacStream { let reserved = self.reserved.take().unwrap_or_else(|| self.timebase.reserve()); let track = self .broadcast - .unique_track(".aac", reserved.track_info(hang::catalog::PRIORITY.audio))?; + .unique_track(".aac", reserved.track_info(hang::catalog::PRIORITY.audio)); let aac = aac::Import::new(track, reserved, config)?; self.asc = asc; self.format = format; @@ -4726,7 +4726,7 @@ impl LegacyStream { let track = self.broadcast.unique_track( self.descriptor.track_suffix, reserved.track_info(hang::catalog::PRIORITY.audio), - )?; + ); let legacy = legacy::Import::new(self.descriptor, track, reserved, config)?; self.format = format; self.import.insert(legacy) diff --git a/rs/moq-mux/src/container/ts/passthrough.rs b/rs/moq-mux/src/container/ts/passthrough.rs index 43f00a7f369..9c8fccdb018 100644 --- a/rs/moq-mux/src/container/ts/passthrough.rs +++ b/rs/moq-mux/src/container/ts/passthrough.rs @@ -304,7 +304,7 @@ impl Passthrough { // replaces, or clears it. let measured = mpegts.mux_rate; catalog.count_ext_tracks(|ext: &mut E| ext.mpegts_mut().is_some_and(|mpegts| mpegts.has_track())); - let track = broadcast.unique_track(".m2ts", catalog.track_info(hang::catalog::PRIORITY.video))?; + let track = broadcast.unique_track(".m2ts", catalog.track_info(hang::catalog::PRIORITY.video)); let media = catalog.media_raw( track, crate::catalog::hang::Container::Legacy(crate::container::Kind::Data), diff --git a/rs/moq-mux/src/container/ts/release_test.rs b/rs/moq-mux/src/container/ts/release_test.rs index 03cb4cdef03..bc30691d2c0 100644 --- a/rs/moq-mux/src/container/ts/release_test.rs +++ b/rs/moq-mux/src/container/ts/release_test.rs @@ -127,8 +127,7 @@ fn republish_cut( let mut broadcast = moq_net::broadcast::Info::new().produce(); let mut catalog = crate::catalog::Producer::new(&mut broadcast, config()).unwrap(); let track = broadcast - .unique_track(".m2ts", catalog.track_info(hang::catalog::PRIORITY.video)) - .unwrap(); + .unique_track(".m2ts", catalog.track_info(hang::catalog::PRIORITY.video)); let name = track.name().to_string(); catalog .mutate(|catalog| catalog.ext.mpegts.passthrough = Some(PassthroughTrack::new(name))) diff --git a/rs/moq-mux/src/container/ts/revision_test.rs b/rs/moq-mux/src/container/ts/revision_test.rs index 3014b1281fc..a91eed9fe9c 100644 --- a/rs/moq-mux/src/container/ts/revision_test.rs +++ b/rs/moq-mux/src/container/ts/revision_test.rs @@ -1475,8 +1475,7 @@ async fn a_revision_out_before_the_one_it_follows_takes_its_version() { // A cue and an AAC track start together, the cue muxed first, on the lower PID: its // revision waits with it for its placement, the AAC track's goes out now. let track = broadcast - .unique_track(".scte35", hang::container::track_info(hang::catalog::PRIORITY.video)) - .unwrap(); + .unique_track(".scte35", hang::container::track_info(hang::catalog::PRIORITY.video)); let entry = super::catalog::Track { pid: DATA_PID, descriptors: Vec::new(), @@ -1558,8 +1557,7 @@ async fn a_stream_taking_a_pid_over_leaves_the_buffer_before_it() { live(&mut export, &mut frames, start, &mut [(&mut first, 0x21)], 3_000, 6_000).await; let track = broadcast - .unique_track(".private", hang::container::track_info(hang::catalog::PRIORITY.video)) - .unwrap(); + .unique_track(".private", hang::container::track_info(hang::catalog::PRIORITY.video)); let entry = super::catalog::Track { pid: DATA_PID, descriptors: Vec::new(), diff --git a/rs/moq-mux/src/container/ts/si.rs b/rs/moq-mux/src/container/ts/si.rs index c0aca90af28..a766d6b1e75 100644 --- a/rs/moq-mux/src/container/ts/si.rs +++ b/rs/moq-mux/src/container/ts/si.rs @@ -441,10 +441,9 @@ impl Entry { None => { let info = track_info(max_age); self.track.insert( - match broadcast.create_track(format!("{pid:#06x}-{table_id:#04x}.si"), info.clone()) { - Ok(track) => track, - Err(_) => broadcast.unique_track(".si", info)?, - }, + broadcast + .create_track(format!("{pid:#06x}-{table_id:#04x}.si"), info.clone()) + .unwrap_or_else(|| broadcast.unique_track(".si", info)), ) } }; diff --git a/rs/moq-net/benches/group.rs b/rs/moq-net/benches/group.rs index b2ced6deae8..b975e86f0b9 100644 --- a/rs/moq-net/benches/group.rs +++ b/rs/moq-net/benches/group.rs @@ -1121,7 +1121,7 @@ fn replay_flights(ctx: &Flights, payloads: &[Bytes], readers: usize, apart: usiz } while let Poll::Ready(Ok(track::Fill::Groups(fill))) = ctx.requests.poll_requested_fill(&waiter) { let start = fill.start(); - let group = fill.accept(start.group, None).unwrap(); + let group = fill.accept(start.group, None).unwrap().expect("a fresh group"); let demand = group.demand(); served += 1; flights.push(Flight { diff --git a/rs/moq-net/benches/track.rs b/rs/moq-net/benches/track.rs index 5bc20ded3dc..ac09c385146 100644 --- a/rs/moq-net/benches/track.rs +++ b/rs/moq-net/benches/track.rs @@ -2176,7 +2176,7 @@ impl RangeFills { continue; }; while let Some(key) = fill.wanted() { - let mut group = fill.accept(key, None).unwrap(); + let mut group = fill.accept(key, None).unwrap().expect("a fresh group"); group .write_frame(Timestamp::from_millis(key).unwrap(), Bytes::from_static(b"x")) .unwrap(); diff --git a/rs/moq-net/src/coding/writer.rs b/rs/moq-net/src/coding/writer.rs index 4765f3b29c0..8927d7625c0 100644 --- a/rs/moq-net/src/coding/writer.rs +++ b/rs/moq-net/src/coding/writer.rs @@ -351,8 +351,6 @@ enum Ack { /// when no offset is outstanding, so they never outnumber the frames waiting plus one. A reset /// then bills every frame acknowledged before it. Asking(std::collections::VecDeque<(O, u64)>), - /// The transport cannot see acknowledgments, so the bytes the stream took bill instead. - Unsupported, /// The transport will acknowledge no more, as after a reset, so nothing more bills. Ended, } @@ -394,31 +392,19 @@ impl Billing { written: u64, waiter: &kio::Waiter, ) { - use crate::transport::poll::Acked; - loop { - let asked = match &mut self.ack { - Ack::Asking(asked) => asked, - Ack::Unsupported => { - self.delivery.deliver(written); - return; - } - Ack::Ended => return, + let Ack::Asking(asked) = &mut self.ack else { + return; }; // The oldest first: a transport acknowledges a prefix, so the rest wait behind a // pending one. while let Some((offset, through)) = asked.front() { match stream.poll_acked(waiter, offset) { Poll::Pending => break, - // Bytes a reliable link took bill too: a reset can no longer discard them. - Poll::Ready(Ok(Acked::Delivered | Acked::Sent)) => { + Poll::Ready(Ok(())) => { self.delivery.deliver(*through); asked.pop_front(); } - Poll::Ready(Ok(_)) => { - self.ack = Ack::Unsupported; - break; - } Poll::Ready(Err(_)) => { self.ack = Ack::Ended; break; @@ -627,7 +613,6 @@ mod tests { /// A stream that takes every write, acknowledging a prefix the test moves, or that cannot /// see acknowledgments. It counts the polls waiting on acknowledgment, which stay pending. - /// With `sent`, it answers for the prefix as a reliable link that took it. #[derive(Clone, Default)] struct Acking(std::sync::Arc>); @@ -636,7 +621,6 @@ mod tests { written: u64, acked: u64, unsupported: bool, - sent: bool, reset: bool, waits: usize, } @@ -648,12 +632,6 @@ mod tests { stream } - fn sent() -> Self { - let stream = Self::default(); - stream.0.lock().unwrap().sent = true; - stream - } - fn ack(&self, through: u64) { self.0.lock().unwrap().acked = through; } @@ -676,12 +654,11 @@ mod tests { &self, _: &kio::Waiter, offset: &u64, - ) -> Poll> { + ) -> Poll> { let mut state = self.0.lock().unwrap(); match () { - _ if state.unsupported => Poll::Ready(Ok(crate::transport::poll::Acked::Unsupported)), - _ if *offset <= state.acked && state.sent => Poll::Ready(Ok(crate::transport::poll::Acked::Sent)), - _ if *offset <= state.acked => Poll::Ready(Ok(crate::transport::poll::Acked::Delivered)), + // As the trait's default answers. + _ if state.unsupported || *offset <= state.acked => Poll::Ready(Ok(())), _ if state.reset => Poll::Ready(Err(Stopped(0))), _ => { state.waits += 1; @@ -744,15 +721,10 @@ mod tests { /// A frame bills once the transport acknowledges an offset past it, not as the stream takes /// it: each write that ends a frame asks about its own offset, so a frame acknowledged before /// a reset still bills, and nothing the reset discarded does. A park with nothing else to ask - /// about asks about a frame still being written, billing its acknowledged bytes. Bytes a - /// reliable link took bill the same way. + /// about asks about a frame still being written, billing its acknowledged bytes. #[test] fn egress_bills_acknowledged_payload() { - egress_bills_payload(Acking::default()); - egress_bills_payload(Acking::sent()); - } - - fn egress_bills_payload(stream: Acking) { + let stream = Acking::default(); let (mut writer, registry) = billing(&stream); let waiter = &kio::Waiter::noop(); diff --git a/rs/moq-net/src/fuzz/ingest.rs b/rs/moq-net/src/fuzz/ingest.rs index cee67865b45..effa0490273 100644 --- a/rs/moq-net/src/fuzz/ingest.rs +++ b/rs/moq-net/src/fuzz/ingest.rs @@ -214,7 +214,7 @@ fn run(session: Session, info: &track::Info, body: &[u8], chunk: usize) -> Optio // Unbounded, so eviction never aborts a group mid-frame. broadcast.pool = cache::Pool::unbounded(); let broadcast = broadcast.produce(); - let track = broadcast.create_track("ingest", info.clone()).ok()?; + let track = broadcast.create_track("ingest", info.clone())?; let (end, fin, group) = match session { Session::Lite { diff --git a/rs/moq-net/src/fuzz/session.rs b/rs/moq-net/src/fuzz/session.rs index e7889211e5c..d2fa1865c39 100644 --- a/rs/moq-net/src/fuzz/session.rs +++ b/rs/moq-net/src/fuzz/session.rs @@ -981,7 +981,7 @@ impl poll::SendStream for Recorded { self.inner.offset() } - fn poll_acked(&self, waiter: &kio::Waiter, offset: &u64) -> Poll> { + fn poll_acked(&self, waiter: &kio::Waiter, offset: &u64) -> Poll> { self.inner.poll_acked(waiter, offset) } diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 863b169f825..d5d8c8f3fbc 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -1657,7 +1657,8 @@ impl Serving { track::Info::default() .with_timescale(info.timescale) .with_priority(info.priority), - )?; + ) + .expect("a fresh broadcast holds no track"); let cache = producer.consume(); let mut serve = TrackServe::new( request.publisher.session.clone(), @@ -7292,7 +7293,7 @@ impl crate::transport::poll::SendStream f &self, waiter: &kio::Waiter, offset: &Self::Offset, - ) -> Poll> { + ) -> Poll> { self.inner.lock().unwrap().stream.poll_acked(waiter, offset) } @@ -15174,7 +15175,7 @@ mod serve_tests { let request = h._broadcast.broadcast().reserve_track("cam").unwrap(); let dynamic = request.requests(); let fetching = request.consume().fetch_group(4, None); - let mut fetched = dynamic.requested_fill_group().await.unwrap().accept(None).unwrap(); + let mut fetched = dynamic.requested_fill_group().await.unwrap().accept(None).unwrap().expect("a fresh group"); for object in 0..2 { fetched .write_frame( diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index d696d623abe..b1d5939e786 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -587,12 +587,8 @@ impl RangeWriter { fill.drop_groups(key..key + 1); None } - false => match fill.accept(key, None) { - Ok(producer) => Some(crate::recv::Group::new(producer)), - // Delivered since it was asked: this fetch's copy is a duplicate. - Err(Error::Duplicate) => None, - Err(err) => return Err(err), - }, + // None once delivered since it was asked: this fetch's copy is a duplicate. + false => fill.accept(key, None)?.map(crate::recv::Group::new), }; if let Some(producer) = &producer { let handle = producer.handle().clone(); diff --git a/rs/moq-net/src/ietf/subscriber/datagrams.rs b/rs/moq-net/src/ietf/subscriber/datagrams.rs index 45f5b0fdc8d..60e1cd9a66f 100644 --- a/rs/moq-net/src/ietf/subscriber/datagrams.rs +++ b/rs/moq-net/src/ietf/subscriber/datagrams.rs @@ -108,7 +108,7 @@ impl Shared { let pending = this.state.lock().datagram_requests.remove(&key); let producer = match pending { Some((_, request)) => request.accept(info), - None => source.create_unlisted_datagrams(key.1, info).ok()?, + None => source.create_unlisted_datagrams(key.1, info)?, }; Some(Self { producer, diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs index 2077eb05beb..c0ce3a9ae49 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -11404,8 +11404,7 @@ impl SharedDatagrams { let producer = serve .source .as_ref()? - .create_unlisted_datagrams(serve.name.as_str(), info) - .ok()?; + .create_unlisted_datagrams(serve.name.as_str(), info)?; let key = (serve.path.clone(), serve.name.clone()); serve.subscriber.legacy_datagrams.lock().insert( key.clone(), @@ -13491,10 +13490,15 @@ impl kio::Task for FetchServeRun { end: frame_end, }, ) { - Ok(producer) => producer, + Ok(Some(producer)) => producer, + // Already served, as by a concurrent fetch. + Ok(None) => { + tracing::debug!(track = %self.serve.name, group = self.group, "fetch already served"); + cancel(stream); + return Poll::Ready(()); + } Err(err) => { - // Already served (a concurrent fetch) or the track closed. Nothing failed - // upstream: we only stopped wanting the answer. + // The track closed. Nothing failed upstream: we only stopped wanting the answer. tracing::debug!(track = %self.serve.name, group = self.group, %err, "fetch not served"); cancel(stream); return Poll::Ready(()); diff --git a/rs/moq-net/src/lite/subscriber/fills.rs b/rs/moq-net/src/lite/subscriber/fills.rs index 8eda571c896..659913cb6fa 100644 --- a/rs/moq-net/src/lite/subscriber/fills.rs +++ b/rs/moq-net/src/lite/subscriber/fills.rs @@ -876,7 +876,7 @@ mod tests { // The lowered start asks for them again, and they arrive. let (mut reader, fill) = ask(&producer, &requests); for key in 0..3 { - let mut group = fill.accept(key, None).unwrap(); + let mut group = fill.accept(key, None).unwrap().expect("a fresh group"); group .write_frame(crate::Timestamp::from_millis(key * 1000).unwrap(), b"x".as_slice()) .unwrap(); diff --git a/rs/moq-net/src/lite/test_transport.rs b/rs/moq-net/src/lite/test_transport.rs index a3f895d2b63..f75d76bcd6c 100644 --- a/rs/moq-net/src/lite/test_transport.rs +++ b/rs/moq-net/src/lite/test_transport.rs @@ -330,15 +330,15 @@ impl poll::SendStream for SinkSend { self.written } - /// Unsupported until the test acknowledges a prefix with [`Log::ack`]. - fn poll_acked(&self, waiter: &kio::Waiter, offset: &u64) -> Poll> { + /// Ready at once, as a transport without acknowledgments, until the test acknowledges a + /// prefix with [`Log::ack`]. + fn poll_acked(&self, waiter: &kio::Waiter, offset: &u64) -> Poll> { let answer = |acked: Option| match acked { - None => Poll::Ready(poll::Acked::Unsupported), - Some(acked) if acked >= *offset => Poll::Ready(poll::Acked::Delivered), - Some(_) => Poll::Pending, + Some(acked) if acked < *offset => Poll::Pending, + _ => Poll::Ready(()), }; - match self.log.acked.poll(waiter, |acked| answer(**acked).map(drop)) { - Poll::Ready(acked) => answer(*acked).map(Ok), + match self.log.acked.poll(waiter, |acked| answer(**acked)) { + Poll::Ready(_) => Poll::Ready(Ok(())), Poll::Pending => Poll::Pending, } } diff --git a/rs/moq-net/src/model/broadcast.rs b/rs/moq-net/src/model/broadcast.rs index 0e9bce5a483..b65a244f635 100644 --- a/rs/moq-net/src/model/broadcast.rs +++ b/rs/moq-net/src/model/broadcast.rs @@ -139,12 +139,26 @@ struct BroadcastState { } impl BroadcastState { - /// Insert a track weak handle into the lookup, returning an error if a live - /// track already holds the name. A closed entry under the name is reclaimed. - fn insert_track(&mut self, weak: track::TrackWeak) -> Result<(), Error> { - match self.cache_track(weak) { - Some(_) => Err(Error::Duplicate), - None => Ok(()), + /// Insert a track weak handle into the lookup, returning false if a live track + /// already holds the name. A closed entry under the name is reclaimed. + fn insert_track(&mut self, weak: track::TrackWeak) -> bool { + self.cache_track(weak).is_none() + } + + /// Mint a name no live track holds, as [`Producer::unique_name`] documents. + fn unique_name(&mut self, suffix: &str) -> String { + let separator = if suffix.starts_with(|c: char| c.is_ascii_digit()) { + "-" + } else { + "" + }; + loop { + let id = self.unique; + self.unique = id.checked_add(1).expect("unique track IDs exhausted"); + let name = format!("{id}{separator}{suffix}"); + if !self.tracks.contains_key(name.as_str()) { + return name; + } } } @@ -305,7 +319,8 @@ impl Producer { Demand::new(self.alive.token.consume().weak(), self.state.clone()) } - /// Produce a new track and insert it into the broadcast. + /// Produce a new track and insert it into the broadcast, or `None` while a live track + /// holds the name. /// /// Pass a name and an optional [`track::Info`], so a bare name works: /// `create_track("video", None)` creates an untimed track. @@ -313,10 +328,17 @@ impl Producer { &self, name: impl Into>, info: impl Into>, - ) -> Result { - let name = name.into(); - let info = info.into().unwrap_or_default(); - let mut state = self.state.lock(); + ) -> Option { + let state = self.state.lock(); + self.insert_created(state, name.into(), info.into().unwrap_or_default()) + } + + fn insert_created( + &self, + mut state: kio::Mut<'_, BroadcastState>, + name: Arc, + info: track::Info, + ) -> Option { // A consumer may have requested this name before it existed (a live // [`Requests`] queues such requests). Creating the track fulfills that @@ -330,20 +352,21 @@ impl Producer { // the request from queuing). let _ = state.cache_track(track.weak()); let unlist = Unlist::list(&self.state, &mut state.listing, name, Listed::Track(info)); - return Ok(track.listed(unlist)); + return Some(track.listed(unlist)); } let track = track::Producer::new(self.info.clone(), name.clone(), info.clone()).with_stats(self.stats.clone()); - state.insert_track(track.weak())?; + if !state.insert_track(track.weak()) { + return None; + } let unlist = Unlist::list(&self.state, &mut state.listing, name, Listed::Track(info)); - Ok(track.listed(unlist)) + Some(track.listed(unlist)) } /// Produce a new datagram track and insert it into the broadcast, listed until it ends. /// /// Datagram tracks are a namespace apart from stream tracks, so this never conflicts with - /// [`Self::create_track`]. Fails with [`Error::Duplicate`] while a live datagram track - /// holds the name. + /// [`Self::create_track`]. Returns `None` while a live datagram track holds the name. /// /// Moq-lite 05 and 06 carry it on its name's stream track subscriptions, but only those /// that start once it exists: create it before, or with, a stream track of the same name. @@ -352,7 +375,7 @@ impl Producer { &self, name: impl Into>, info: datagram::Info, - ) -> Result { + ) -> Option { self.insert_datagrams(name.into(), info, true) } @@ -364,7 +387,7 @@ impl Producer { &self, name: impl Into>, info: datagram::Info, - ) -> Result { + ) -> Option { self.insert_datagrams(name.into(), info, false) } @@ -373,7 +396,7 @@ impl Producer { name: Arc, info: datagram::Info, listed: bool, - ) -> Result { + ) -> Option { let mut state = self.state.lock(); let producer = match state.datagrams.get(name.as_ref()) { Some(live) => { @@ -383,9 +406,7 @@ impl Producer { .datagram_requests .iter() .position(|request| live.same_channel(&request.weak())); - let Some(queued) = queued else { - return Err(Error::Duplicate); - }; + let queued = queued?; let request = state.datagram_requests.remove(queued).expect("found above"); request.with_stats(self.stats.clone()).accept(info) } @@ -396,10 +417,10 @@ impl Producer { } }; if !listed { - return Ok(producer); + return Some(producer); } let unlist = Unlist::list(&self.state, &mut state.listing, name, Listed::Datagrams(info)); - Ok(producer.listed(unlist)) + Some(producer.listed(unlist)) } /// Answer datagram lookups from `source`, the broadcast an origin's front serves from, @@ -408,7 +429,8 @@ impl Producer { self.state.lock().datagram_source = Some(source); } - /// Reserve a track by name without finalizing its [`track::Info`]. + /// Reserve a track by name without finalizing its [`track::Info`], or `None` while a + /// live track holds the name. /// /// Returns a [`track::Request`] already discoverable by consumers; call /// [`track::Request::accept`] to set its info and start producing. Use this when @@ -419,12 +441,14 @@ impl Producer { /// Subscribers wait on the name until it is accepted, so a reservation the producer /// ends up never filling has to be dropped or rejected. Ending the broadcast /// resolves whatever is left. - pub fn reserve_track(&self, name: impl Into>) -> Result { + pub fn reserve_track(&self, name: impl Into>) -> Option { let name = name.into(); let mut state = self.state.lock(); let request = track::Request::new(self.info.clone(), name.clone()).with_stats(self.stats.clone()); - state.insert_track(request.weak())?; - Ok(request.listed(ListOnAccept { + if !state.insert_track(request.weak()) { + return None; + } + Some(request.listed(ListOnAccept { state: self.state.clone(), name, })) @@ -436,19 +460,21 @@ impl Producer { /// /// Unlisted controls discovery, not authorization: anyone allowed to subscribe to the /// broadcast can read the track by name. - pub fn reserve_unlisted_track(&self, name: impl Into>) -> Result { + pub fn reserve_unlisted_track(&self, name: impl Into>) -> Option { let mut state = self.state.lock(); let request = track::Request::new(self.info.clone(), name.into()).with_stats(self.stats.clone()); - state.insert_track(request.weak())?; - Ok(request) + state.insert_track(request.weak()).then_some(request) } /// Create a track with a unique name using the given suffix. /// /// Uses [`Self::unique_name`]; minted names are never reused, even after closure. - pub fn unique_track(&self, suffix: &str, info: impl Into>) -> Result { - let name = self.unique_name(suffix); - self.create_track(name, info) + pub fn unique_track(&self, suffix: &str, info: impl Into>) -> track::Producer { + let mut state = self.state.lock(); + let name = state.unique_name(suffix); + // Minted under the same lock, so no live track can hold the name. + self.insert_created(state, name.into(), info.into().unwrap_or_default()) + .expect("a minted name is free") } /// Generate a unique track name from a suffix without creating the track. @@ -463,20 +489,7 @@ impl Producer { /// /// Panics if the broadcast exhausts its `u64` IDs. pub fn unique_name(&self, suffix: &str) -> String { - let mut state = self.state.lock(); - let separator = if suffix.starts_with(|c: char| c.is_ascii_digit()) { - "-" - } else { - "" - }; - loop { - let id = state.unique; - state.unique = id.checked_add(1).expect("unique track IDs exhausted"); - let name = format!("{id}{separator}{suffix}"); - if !state.tracks.contains_key(name.as_str()) { - return name; - } - } + self.state.lock().unique_name(suffix) } /// Create a dynamic producer that handles on-demand track requests from consumers. @@ -1584,7 +1597,7 @@ mod test { fn unique_names_survive_closed_track_pruning() { let producer = Info::new().produce(); let consumer = producer.consume(); - let track = producer.unique_track(".opus", crate::track::Info::timed()).unwrap(); + let track = producer.unique_track(".opus", crate::track::Info::timed()); assert_eq!(track.name(), "0.opus"); drop(track); assert!(matches!(consumer.track("0.opus"), Err(Error::NotFound))); @@ -2336,7 +2349,7 @@ mod test { let track = consumer.track("track1").unwrap(); let pending_fetch = track.fetch_group(0, None); let fetch = dynamic.requested_fill_group().await.unwrap(); - let group = fetch.accept(crate::track::Info::timed()).unwrap(); + let group = fetch.accept(crate::track::Info::timed()).unwrap().expect("a fresh group"); group.finish().unwrap(); pending_fetch.await.unwrap(); @@ -2541,10 +2554,7 @@ mod test { let consumer = producer.consume(); let _track = producer.create_track("audio", crate::track::Info::timed()).unwrap(); let mut datagrams = producer.create_datagrams("audio", datagram::Info::default()).unwrap(); - assert!(matches!( - producer.create_datagrams("audio", datagram::Info::default()), - Err(Error::Duplicate) - )); + assert!(producer.create_datagrams("audio", datagram::Info::default()).is_none()); let mut reader = consumer.datagrams("audio").unwrap(); datagrams.append(crate::Timestamp::unscaled(0), "x").unwrap(); diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 8959392598f..8fec6adc87f 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -10115,7 +10115,7 @@ mod tests { let fetch = track.consume().fetch_group(0, None); let fill = requests.requested_fill_group().await.unwrap(); - let mut fetched = fill.accept(crate::track::Info::timed()).unwrap(); + let mut fetched = fill.accept(crate::track::Info::timed()).unwrap().expect("a fresh group"); fetched .write_frame(crate::Timestamp::ZERO, b"fetched".as_ref()) .unwrap(); @@ -12240,7 +12240,7 @@ mod tests { let serving = fetched.clone(); let _fetching = kio::clock::sim::spawn(async move { while let Ok(request) = fetches.requested_fill_group().await { - let mut group = request.accept(crate::track::Info::timed()).unwrap(); + let mut group = request.accept(crate::track::Info::timed()).unwrap().expect("a fresh group"); for frame in [b"a", b"b", b"c"] { group.write_frame(group.key_time(), frame.as_ref()).unwrap(); } diff --git a/rs/moq-net/src/model/resume.rs b/rs/moq-net/src/model/resume.rs index 39d62c1943d..2b090a5e1ab 100644 --- a/rs/moq-net/src/model/resume.rs +++ b/rs/moq-net/src/model/resume.rs @@ -3913,7 +3913,7 @@ mod test { assert!(reading.read_frame().now_or_never().is_none()); let request = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); assert_eq!((request.key(), request.frame_start()), (0, 2)); - let mut rest = request.accept(None).unwrap(); + let mut rest = request.accept(None).unwrap().expect("a fresh group"); rest.write_frame(ts(2), frames[2].clone()).unwrap(); rest.finish().unwrap(); assert_eq!(read(&mut reading).as_ref(), Some(&frames[2])); @@ -4001,7 +4001,7 @@ mod test { filler.finish().unwrap(); assert!(handoff.head().is_none(), "the shrink reclaimed the head"); - let mut rest = request.accept(None).unwrap(); + let mut rest = request.accept(None).unwrap().expect("a fresh group"); rest.write_frame(ts(1), frame()).unwrap(); rest.finish().unwrap(); let res = reading.read_frame().now_or_never().expect("fails instead of spinning"); @@ -4203,7 +4203,7 @@ mod test { let request = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); assert_eq!((request.key(), request.frame_start()), (0, 1)); - let mut rest = request.accept(None).unwrap(); + let mut rest = request.accept(None).unwrap().expect("a fresh group"); rest.write_frame(ts(1), b"b".as_ref()).unwrap(); rest.finish().unwrap(); a.abort(Error::Stream(StreamError::App(5))).unwrap(); @@ -4379,7 +4379,7 @@ mod test { assert!(fetched.read_frame().now_or_never().is_none()); let pending = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); assert!(fetched.read_frame().now_or_never().is_none()); - let mut rest = pending.accept(None).unwrap(); + let mut rest = pending.accept(None).unwrap().expect("a fresh group"); rest.write_frame(ts(1), b"b".as_ref()).unwrap(); rest.finish().unwrap(); assert_eq!(read(&mut fetched), Some(b"b".to_vec())); @@ -4536,7 +4536,7 @@ mod test { .unwrap(); let copy = request.accept(crate::track::Info::timed()); - let mut group = fill.accept(0, crate::track::Info::timed()).unwrap(); + let mut group = fill.accept(0, crate::track::Info::timed()).unwrap().expect("a fresh group"); group.write_frame(ts(0), b"early".as_ref()).unwrap(); group.finish().unwrap(); assert!( @@ -4563,7 +4563,7 @@ mod test { assert!((&mut fetching).now_or_never().is_none()); let fill = refused_dynamic.requested_groups().now_or_never().unwrap().unwrap(); let wrong = refused.accept(crate::track::Info::timed()); - let mut group = fill.accept(0, crate::track::Info::timed()).unwrap(); + let mut group = fill.accept(0, crate::track::Info::timed()).unwrap().expect("a fresh group"); group.write_frame(ts(0), b"wrong".as_ref()).unwrap(); group.finish().unwrap(); drop(staged); @@ -4578,7 +4578,7 @@ mod test { .expect("asked again of the next route") .unwrap(); let copy = request.accept(crate::track::Info::timed()); - let mut group = fill.accept(0, crate::track::Info::timed()).unwrap(); + let mut group = fill.accept(0, crate::track::Info::timed()).unwrap().expect("a fresh group"); group.write_frame(ts(0), b"right".as_ref()).unwrap(); group.finish().unwrap(); let _logical = logical.accept(crate::track::Info::timed()); @@ -4686,7 +4686,7 @@ mod test { assert!((&mut fetching).now_or_never().is_none()); let fill = dynamic.requested_groups().now_or_never().unwrap().unwrap(); let _staged_copy = request.accept(crate::track::Info::timed()); - let mut group = fill.accept(0, crate::track::Info::timed()).unwrap(); + let mut group = fill.accept(0, crate::track::Info::timed()).unwrap().expect("a fresh group"); group.write_frame(ts(0), b"x".as_ref()).unwrap(); group.finish().unwrap(); assert!((&mut fetching).now_or_never().is_none()); @@ -4704,7 +4704,7 @@ mod test { .now_or_never() .expect("asked of the serving copy") .unwrap(); - let mut group = fill.accept(0, crate::track::Info::timed()).unwrap(); + let mut group = fill.accept(0, crate::track::Info::timed()).unwrap().expect("a fresh group"); group.write_frame(ts(0), b"x".as_ref()).unwrap(); group.finish().unwrap(); let mut fetched = fetching.now_or_never().expect("answered").unwrap(); @@ -4967,7 +4967,7 @@ mod test { assert!(reading.read_frame().now_or_never().is_none()); let request = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); assert_eq!((request.key(), request.frame_start()), (0, 2)); - let mut rest = request.accept(None).unwrap(); + let mut rest = request.accept(None).unwrap().expect("a fresh group"); rest.write_frame(ts(2), b"c".as_ref()).unwrap(); rest.finish().unwrap(); assert_eq!(read(&mut reading), Some(b"c".to_vec())); @@ -5003,7 +5003,7 @@ mod test { assert!(reading.read_frame().now_or_never().is_none()); let request = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); assert_eq!(request.frame_start(), 1); - let mut rest = request.accept(None).unwrap(); + let mut rest = request.accept(None).unwrap().expect("a fresh group"); rest.write_frame(ts(1), b"b".as_ref()).unwrap(); rest.finish().unwrap(); assert_eq!(read(&mut reading), Some(b"b".to_vec())); @@ -5036,7 +5036,7 @@ mod test { assert!(fetched.read_frame().now_or_never().is_none()); let request = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); assert_eq!(request.frame_start(), 1); - let mut rest = request.accept(None).unwrap(); + let mut rest = request.accept(None).unwrap().expect("a fresh group"); rest.write_frame(ts(1), b"b".as_ref()).unwrap(); rest.finish().unwrap(); assert_eq!(read(&mut fetched), Some(b"b".to_vec())); @@ -6634,7 +6634,7 @@ mod test { assert!(reading.read_frame().now_or_never().is_none()); let request = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); assert_eq!((request.key(), request.frame_start()), (8, 1)); - let mut rest = request.accept(None).unwrap(); + let mut rest = request.accept(None).unwrap().expect("a fresh group"); assert!(reading.read_frame().now_or_never().is_none()); // The serving copy's first group bounds the replaced one, which is let go. @@ -8125,7 +8125,7 @@ mod test { assert!(kio::Task::poll(&mut *fetching, &waiter).is_pending()); let request = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); assert_eq!(request.frame_start(), 0, "the cold copy fills from the head"); - let mut group = request.accept(None).unwrap(); + let mut group = request.accept(None).unwrap().expect("a fresh group"); for frame in 0..4u8 { group.write_frame(ts(0), vec![frame]).unwrap(); } @@ -8442,7 +8442,7 @@ mod test { let request = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); assert_eq!((request.key(), request.frame_start()), (0, 1)); - let mut rest = request.accept(None).unwrap(); + let mut rest = request.accept(None).unwrap().expect("a fresh group"); rest.write_frame(ts(1), b"b".as_ref()).unwrap(); rest.finish().unwrap(); assert_eq!(read(&mut fetched), Some(b"b".to_vec())); @@ -8570,7 +8570,7 @@ mod test { open.abort(Error::Stream(code.clone())).unwrap(); assert!(reading.read_frame().now_or_never().is_none(), "{code:?}"); let request = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); - let mut rest = request.accept(None).unwrap(); + let mut rest = request.accept(None).unwrap().expect("a fresh group"); rest.write_frame(ts(1), b"b".as_ref()).unwrap(); rest.finish().unwrap(); assert_eq!(read(&mut reading), Some(b"b".to_vec()), "{code:?}"); diff --git a/rs/moq-net/src/model/resume_model.rs b/rs/moq-net/src/model/resume_model.rs index 52d2f716966..22b7ee51d75 100644 --- a/rs/moq-net/src/model/resume_model.rs +++ b/rs/moq-net/src/model/resume_model.rs @@ -569,7 +569,7 @@ impl Model { fill.refuse_groups(group..group + 1, Error::Stream(GIVE_UP)); } else if written == 0 || written < from || held.into_iter().any(|part| part.from <= from) { fill.refuse_groups(group..group + 1, Error::NotFound); - } else if let Ok(writer) = fill.accept(group, None) { + } else if let Ok(Some(writer)) = fill.accept(group, None) { // The fill starts at the frame its readers want, which may not exist yet. copy.groups.entry(group).or_default().push(Part { from, diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 924219ae02f..5022b6f5f63 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -3864,13 +3864,13 @@ impl TrackState { /// if it isn't accepted yet. The group's timescale comes from that info, so a /// fetch can serve an as-yet-unaccepted track (e.g. a relay with no live /// subscription). The group lands in the cache so a waiting - /// [`Fetching`] resolves via [`Self::poll_fetch`]. + /// [`Fetching`] resolves via [`Self::poll_fetch`]. `None` when a copy already covers it. pub(super) fn insert_group_request( &mut self, key: u64, frames: group::Bounds, info: Option, - ) -> Result { + ) -> Result> { if let Some(err) = self.outcome.aborted() { return Err(err.clone()); } @@ -3895,7 +3895,7 @@ impl TrackState { let info = self.info.clone().unwrap(); if self.covering_range(key, frames).is_some() { - return Err(Error::Duplicate); + return Ok(None); } let content = self.content_for_copy(key)?; @@ -3953,7 +3953,7 @@ impl TrackState { None => self.insert_group(&group.handle(), false), } self.evict_expired(); - Ok(group) + Ok(Some(group)) } } @@ -12204,7 +12204,7 @@ mod test { .unwrap(); let fetch = consumer.fetch_group(key, None); let request = dynamic.requested_fill_group().await.unwrap(); - let mut head = request.accept(Info::timed()).unwrap(); + let mut head = request.accept(Info::timed()).unwrap().expect("a fresh group"); for payload in [&b"snapshot"[..], b"delta"] { head.write_frame(head.key_time(), bytes::Bytes::from_static(payload)) .unwrap(); @@ -12239,7 +12239,7 @@ mod test { .unwrap(); let _fetch = consumer.fetch_group(0, None); let request = dynamic.requested_fill_group().await.unwrap(); - let mut head = request.accept(Info::timed()).unwrap(); + let mut head = request.accept(Info::timed()).unwrap().expect("a fresh group"); head.write_frame(head.key_time(), bytes::Bytes::from_static(b"snapshot")) .unwrap(); (live, head) @@ -12530,7 +12530,8 @@ mod test { .await .unwrap() .accept(Info::timed()) - .unwrap(); + .unwrap() + .expect("a fresh group"); bounded.write_frame(bounded.key_time(), &b"a"[..]).unwrap(); bounded.finish().unwrap(); fetch.await.unwrap(); @@ -14608,7 +14609,8 @@ mod test { .ok() .unwrap() .insert_group_request(0, group::Bounds::default(), None) - .unwrap(); + .unwrap() + .expect("a fresh group"); let state = state.read(); assert_eq!(state.info.as_ref().unwrap().max_age, None); assert_eq!(state.max_age_bound(), None); @@ -14620,7 +14622,7 @@ mod test { fn a_refusal_releases_the_live_edge_a_fill_cached() { let state = TrackState::spawn(Arc::new(broadcast::Info::default())); let mut guard = state.write().ok().unwrap(); - let _group = guard.insert_group_request(0, group::Bounds::default(), None).unwrap(); + let _group = guard.insert_group_request(0, group::Bounds::default(), None).unwrap().expect("a fresh group"); assert!(guard.protects(0)); guard.reject(Error::NotFound, None); assert!(!guard.protects(0)); @@ -14943,7 +14945,7 @@ mod test { assert_eq!(read_now(&mut reader, false), None, "the fill is still owed"); assert_eq!(fill.wanted(), Some(5), "the fresh suffix stays wanted"); for key in 3..6 { - let mut group = fill.accept(key, None).unwrap(); + let mut group = fill.accept(key, None).unwrap().expect("a fresh group"); group .write_frame(crate::Timestamp::unscaled(group.start), &b"x"[..]) .unwrap(); @@ -15008,7 +15010,7 @@ mod test { ); assert!(fill.wanted().is_some(), "the fresh suffix stays wanted"); for key in 3..6 { - let mut group = fill.accept(key, None).unwrap(); + let mut group = fill.accept(key, None).unwrap().expect("a fresh group"); group .write_frame(crate::Timestamp::unscaled(group.start), &b"x"[..]) .unwrap(); @@ -16822,7 +16824,7 @@ mod test { let Poll::Ready(Ok(req)) = dynamic.poll_requested_fill_group(&waiter) else { panic!("fetch request should be ready"); }; - let mut fetched = req.accept(None).unwrap(); + let mut fetched = req.accept(None).unwrap().expect("a fresh group"); fetched .write_frame(crate::Timestamp::unscaled(fetched.start), b"2-0".as_ref()) .unwrap(); @@ -16866,7 +16868,7 @@ mod test { .now_or_never() .expect("fetch request is ready") .unwrap(); - let mut fetched = req.accept(Info::timed()).unwrap(); + let mut fetched = req.accept(Info::timed()).unwrap().expect("a fresh group"); fetched .write_frame( Timestamp::from_millis(100_000).unwrap(), @@ -16902,7 +16904,7 @@ mod test { .now_or_never() .expect("fill request is ready") .unwrap(); - req.accept(None).unwrap().abort(error.clone()).unwrap(); + req.accept(None).unwrap().expect("a fresh group").abort(error.clone()).unwrap(); drop(pending); let waiter = kio::Waiter::noop(); assert!( @@ -17742,7 +17744,7 @@ mod test { let _fetch = consumer.fetch_group(0, None); let request = dynamic.requested_fill_group().await.unwrap(); - let mut head = request.accept(Info::timed()).unwrap(); + let mut head = request.accept(Info::timed()).unwrap().expect("a fresh group"); head.write_frame(head.key_time(), bytes::Bytes::from_static(b"snapshot")) .unwrap(); let mut reading = consumer.peek_group(0).expect("the head serves group 0"); @@ -18600,7 +18602,7 @@ mod test { let _pending = consumer.fetch_group(0, None); let req = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); - req.accept(None).unwrap().finish().unwrap(); + req.accept(None).unwrap().expect("a fresh group").finish().unwrap(); assert!( arrival.recv_group().now_or_never().is_none(), "the live group 0 is still owed" @@ -19495,7 +19497,8 @@ mod test { .ok() .unwrap() .insert_group_request(3, group::Bounds { start: 0, end: Some(3) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); for (millis, payload) in [(300, b"a"), (301, b"b"), (302, b"c")] { head.write_frame(at(millis), &payload[..]).unwrap(); } @@ -19521,7 +19524,8 @@ mod test { .ok() .unwrap() .insert_group_request(3, group::Bounds { start: 0, end: Some(3) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); let mut reader = head.consume().with_range(..3); for (millis, payload) in [(300, b"a"), (301, b"b"), (302, b"c")] { head.write_frame(at(millis), &payload[..]).unwrap(); @@ -19567,7 +19571,8 @@ mod test { .ok() .unwrap() .insert_group_request(3, group::Bounds { start: 2, end: Some(3) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); drop(hold); cut.write_frame(at(302), &b"c"[..]).unwrap(); let waiter = kio::Waiter::noop(); @@ -19656,7 +19661,8 @@ mod test { .ok() .unwrap() .insert_group_request(3, group::Bounds { start: 0, end: Some(3) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); for (millis, payload) in [(300, b"a"), (301, b"b"), (302, b"c")] { head.write_frame(at(millis), &payload[..]).unwrap(); } @@ -21321,7 +21327,7 @@ mod test { assert_eq!(req.priority(), 7); // Serve it by accepting the request; the fetch then resolves. - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"hi")) .unwrap(); @@ -21400,7 +21406,7 @@ mod test { .unwrap(); drop(req); assert!(fresh.poll_unwanted(&kio::Waiter::noop()).is_pending()); - fresh.accept(Info::timed()).unwrap().finish().unwrap(); + fresh.accept(Info::timed()).unwrap().expect("a fresh group").finish().unwrap(); assert_eq!(retry.await.unwrap().start, 5); } @@ -21445,7 +21451,7 @@ mod test { .now_or_never() .expect("the retry queues a fresh request") .unwrap(); - fresh.accept(Info::timed()).unwrap().finish().unwrap(); + fresh.accept(Info::timed()).unwrap().expect("a fresh group").finish().unwrap(); assert_eq!(retry.await.unwrap().start, 5); } @@ -21473,7 +21479,7 @@ mod test { .expect("the retry queues a fresh request") .unwrap(); - let mut group = req.accept(Info::timed()).expect("a withdrawn request still accepts"); + let mut group = req.accept(Info::timed()).expect("a withdrawn request still accepts").expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"hi")) .unwrap(); @@ -21482,7 +21488,7 @@ mod test { let mut fetched = retry.await.unwrap(); assert_eq!(&fetched.read_frame().await.unwrap().unwrap().payload[..], b"hi"); assert!(!fresh.is_wanted(), "the retry left the fresh request"); - assert!(matches!(fresh.accept(Info::timed()), Err(Error::Duplicate))); + assert!(matches!(fresh.accept(Info::timed()), Ok(None))); } /// Dropping an auto trait from a published type is a semver break, so the group @@ -21509,7 +21515,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"head")) .unwrap(); @@ -21541,7 +21547,7 @@ mod test { let bounded = consumer.fetch_range(0, request(2, Some(4))); let fill = dynamic.requested_fill_group().await.unwrap(); assert_eq!((fill.frame_start(), fill.frame_end()), (0, Some(4))); - let mut prefix = fill.accept(Info::timed()).unwrap(); + let mut prefix = fill.accept(Info::timed()).unwrap().expect("a fresh group"); for _ in 0..4 { prefix.write_frame(prefix.key_time(), b"prefix".as_slice()).unwrap(); } @@ -21568,7 +21574,7 @@ mod test { assert!(kio::Task::poll(&mut *whole, &kio::Waiter::noop()).is_pending()); let fill = dynamic.requested_fill_group().await.unwrap(); assert_eq!((fill.frame_start(), fill.frame_end()), (0, None)); - let mut complete = fill.accept(Info::timed()).unwrap(); + let mut complete = fill.accept(Info::timed()).unwrap().expect("a fresh group"); for _ in 0..6 { complete.write_frame(complete.key_time(), b"prefix".as_slice()).unwrap(); } @@ -21604,7 +21610,7 @@ mod test { ); let fill = dynamic.requested_fill_group().await.unwrap(); assert_eq!((fill.frame_start(), fill.frame_end()), (start, Some(start + 1))); - let mut tail = fill.accept(Info::timed()).unwrap(); + let mut tail = fill.accept(Info::timed()).unwrap().expect("a fresh group"); tail.write_frame(tail.key_time(), b"tail".as_slice()).unwrap(); tail.finish().unwrap(); assert_eq!(fetched.await.unwrap().index(), start); @@ -21643,7 +21649,7 @@ mod test { let fill = async |frames: std::ops::Range| { let fill = dynamic.requested_fill_group().await.unwrap(); assert_eq!((fill.frame_start(), fill.frame_end()), (frames.start, Some(frames.end))); - let mut group = fill.accept(Info::timed()).unwrap(); + let mut group = fill.accept(Info::timed()).unwrap().expect("a fresh group"); for _ in frames { group.write_frame(group.key_time(), b"tail".as_slice()).unwrap(); } @@ -21671,7 +21677,7 @@ mod test { let fill = async |start: u64, end: Option| { let fill = dynamic.requested_fill_group().await.unwrap(); assert_eq!((fill.frame_start(), fill.frame_end()), (start, end)); - let mut group = fill.accept(Info::timed()).unwrap(); + let mut group = fill.accept(Info::timed()).unwrap().expect("a fresh group"); group.write_frame(group.key_time(), b"tail".as_slice()).unwrap(); group }; @@ -21718,7 +21724,7 @@ mod test { (fill.frame_start(), fill.frame_end()), (frames.options.frame_start, frames.end) ); - let mut group = fill.accept(Info::timed()).unwrap(); + let mut group = fill.accept(Info::timed()).unwrap().expect("a fresh group"); group.write_frame(group.key_time(), b"copy".as_slice()).unwrap(); group }; @@ -21774,7 +21780,8 @@ mod test { .await .unwrap() .accept(Info::timed()) - .unwrap(); + .unwrap() + .expect("a fresh group"); for _ in 0..2 { group.write_frame(group.key_time(), b"copy".as_slice()).unwrap(); } @@ -21804,7 +21811,7 @@ mod test { ); let fill = dynamic.requested_fill_group().await.unwrap(); assert_eq!(fill.frame_end(), Some(1)); - let mut group = fill.accept(Info::timed()).unwrap(); + let mut group = fill.accept(Info::timed()).unwrap().expect("a fresh group"); group.write_frame(group.key_time(), b"copy".as_slice()).unwrap(); // The end is reached while the copy is still being written, so only the abort // can find it settled. @@ -21846,7 +21853,8 @@ mod test { .await .unwrap() .accept(Info::timed()) - .unwrap(); + .unwrap() + .expect("a fresh group"); group.write_frame(group.key_time(), b"head".as_slice()).unwrap(); group.finish().unwrap(); fetch.await.unwrap(); @@ -21925,7 +21933,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let _group = req.accept(Info::timed()).unwrap(); + let _group = req.accept(Info::timed()).unwrap().expect("a fresh group"); let mut whole = consumer.fetch_group(5, None); let req = dynamic @@ -21952,7 +21960,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let group = req.accept(Info::timed()).unwrap(); + let group = req.accept(Info::timed()).unwrap().expect("a fresh group"); drop(first.await.unwrap()); assert!(group.handle().abort_unwanted(Error::Cancel)); @@ -21962,7 +21970,7 @@ mod test { .now_or_never() .expect("the retry queues a fresh request") .unwrap(); - req.accept(Info::timed()).unwrap().finish().unwrap(); + req.accept(Info::timed()).unwrap().expect("a fresh group").finish().unwrap(); assert!(retry.await.unwrap().read_frame().await.unwrap().is_none()); } @@ -21988,7 +21996,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"retry")) .unwrap(); @@ -22039,7 +22047,7 @@ mod test { assert_eq!((request.key(), request.frame_start()), (0, 0)); // Serving it replaces the too-narrow entry rather than colliding with it. - let mut whole = request.accept(Info::timed()).unwrap(); + let mut whole = request.accept(Info::timed()).unwrap().expect("a fresh group"); whole .write_frame(whole.key_time(), bytes::Bytes::from_static(b"head")) .unwrap(); @@ -22070,7 +22078,7 @@ mod test { let fetch = consumer.fetch_group(0, None); let request = dynamic.requested_fill_group().await.unwrap(); - let mut head = request.accept(Info::timed()).unwrap(); + let mut head = request.accept(Info::timed()).unwrap().expect("a fresh group"); for payload in [&b"snapshot"[..], b"delta"] { head.write_frame(head.key_time(), bytes::Bytes::from_static(payload)) .unwrap(); @@ -22128,7 +22136,7 @@ mod test { .expect("the head is asked") .unwrap(); assert_eq!(request.frame_start(), 0); - let mut head = request.accept(Info::timed()).unwrap(); + let mut head = request.accept(Info::timed()).unwrap().expect("a fresh group"); for payload in [&b"snapshot"[..], b"delta"] { head.write_frame(head.key_time(), bytes::Bytes::from_static(payload)) .unwrap(); @@ -22167,7 +22175,7 @@ mod test { .await .expect("the head is asked") .unwrap(); - let mut head = request.accept(Info::timed()).unwrap(); + let mut head = request.accept(Info::timed()).unwrap().expect("a fresh group"); for payload in [&b"snapshot"[..], b"delta"] { head.write_frame(head.key_time(), bytes::Bytes::from_static(payload)) .unwrap(); @@ -22249,7 +22257,7 @@ mod test { } assert_eq!(requests.len(), 2, "{order:?}: both heads are asked"); for request in requests { - let mut head = request.accept(Info::default()).unwrap(); + let mut head = request.accept(Info::default()).unwrap().expect("a fresh group"); head.write_frame( crate::Timestamp::unscaled(head.start), bytes::Bytes::from_static(b"snapshot"), @@ -22295,7 +22303,7 @@ mod test { assert_eq!(request.key(), 0); sub.update(replay().with_range(1..2)).unwrap(); - let mut head = request.accept(Info::default()).unwrap(); + let mut head = request.accept(Info::default()).unwrap().expect("a fresh group"); head.write_frame( crate::Timestamp::unscaled(head.start), bytes::Bytes::from_static(b"snapshot"), @@ -22363,7 +22371,8 @@ mod test { .await .unwrap() .accept(Info::timed()) - .unwrap(); + .unwrap() + .expect("a fresh group"); for index in 0..3 { let payload = if index == 0 { b"x".as_slice() @@ -22395,7 +22404,7 @@ mod test { let fetch = consumer.fetch_group(0, None); let request = dynamic.requested_fill_group().await.unwrap(); - let mut head = request.accept(Info::timed()).unwrap(); + let mut head = request.accept(Info::timed()).unwrap().expect("a fresh group"); for payload in [&b"snapshot"[..], b"delta"] { head.write_frame(head.key_time(), bytes::Bytes::from_static(payload)) .unwrap(); @@ -22424,7 +22433,8 @@ mod test { .await .unwrap() .accept(Info::timed()) - .unwrap(); + .unwrap() + .expect("a fresh group"); for payload in [&b"snapshot"[..], b"delta"] { head.write_frame(head.key_time(), bytes::Bytes::from_static(payload)) .unwrap(); @@ -22559,7 +22569,8 @@ mod test { .await .unwrap() .accept(Info::timed()) - .unwrap(); + .unwrap() + .expect("a fresh group"); fetched .write_frame(fetched.key_time(), bytes::Bytes::from_static(b"backfill")) .unwrap(); @@ -22614,7 +22625,7 @@ mod test { let _fetch = consumer.fetch_group(0, None); let request = dynamic.requested_fill_group().await.unwrap(); - let mut head = request.accept(Info::timed()).unwrap(); + let mut head = request.accept(Info::timed()).unwrap().expect("a fresh group"); for payload in [&b"snapshot"[..], b"delta"] { head.write_frame(head.key_time(), bytes::Bytes::from_static(payload)) .unwrap(); @@ -22724,7 +22735,8 @@ mod test { .await .unwrap() .accept(Info::timed()) - .unwrap(); + .unwrap() + .expect("a fresh group"); head.write_frame(head.key_time(), bytes::Bytes::from(vec![0u8; 10_000])) .unwrap(); head.finish().unwrap(); @@ -22795,7 +22807,7 @@ mod test { // A handler may keep tracking the group's readers past the accept, as the lite // subscriber does, which holds the result channel open. let _readers = request.readers(); - let mut group = request.accept(Info::timed()).unwrap(); + let mut group = request.accept(Info::timed()).unwrap().expect("a fresh group"); // A handler numbers the frames from where it was asked to start, as `serve_fetch` // does; that offset is what makes the cached group too narrow for `widest`. group.start_at(2).unwrap(); @@ -22810,7 +22822,7 @@ mod test { assert!(futures::poll!(widest.as_mut()).is_pending()); group.finish().unwrap(); - let mut group = whole.accept(None).unwrap(); + let mut group = whole.accept(None).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"from0")) .unwrap(); @@ -22858,7 +22870,7 @@ mod test { let third = consumer.fetch_group(5, None); // One accept resolves all of them. - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"hi")) .unwrap(); @@ -22890,7 +22902,7 @@ mod test { let req = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); assert_eq!(req.max_delay(), None); - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"hi")) .unwrap(); @@ -23268,7 +23280,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut backfill = req.accept(Info::timed()).unwrap(); + let mut backfill = req.accept(Info::timed()).unwrap().expect("a fresh group"); pending.await.unwrap(); backfill .write_frame(backfill.key_time(), bytes::Bytes::from(vec![0u8; 30_000])) @@ -23467,7 +23479,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut backfill = req.accept(Info::timed()).unwrap(); + let mut backfill = req.accept(Info::timed()).unwrap().expect("a fresh group"); pending.await.unwrap(); // Accept, then demote the backfill with a live group. @@ -23529,7 +23541,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from(vec![0u8; 100])) .unwrap(); @@ -23654,7 +23666,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"backfill")) .unwrap(); @@ -23700,7 +23712,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from(vec![0u8; 100])) .unwrap(); @@ -23764,7 +23776,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from(vec![0u8; 1000])) .unwrap(); @@ -23807,7 +23819,7 @@ mod test { .unwrap(); assert_eq!(req.key(), 0); - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"refetched")) .unwrap(); @@ -23872,7 +23884,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut fetched = req.accept(Info::timed()).unwrap(); + let mut fetched = req.accept(Info::timed()).unwrap().expect("a fresh group"); fetched .write_frame(fetched.key_time(), bytes::Bytes::from_static(b"backfill")) .unwrap(); @@ -23920,7 +23932,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"backfill")) .unwrap(); @@ -23962,7 +23974,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut fetching = req.accept(Info::timed()).unwrap(); + let mut fetching = req.accept(Info::timed()).unwrap().expect("a fresh group"); fetching .write_frame(fetching.key_time(), bytes::Bytes::from_static(b"snapshot")) .unwrap(); @@ -24008,7 +24020,7 @@ mod test { .now_or_never() .expect("should not block") .unwrap(); - let mut group = req.accept(Info::timed()).unwrap(); + let mut group = req.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from(vec![0u8; 1000])) .unwrap(); @@ -24571,8 +24583,8 @@ mod test { let Poll::Ready(Ok(fill)) = dynamic.poll_requested_groups(&waiter) else { panic!("the fill is ready"); }; - let group = fill.accept(3, Info::timed()).unwrap(); - assert!(matches!(fill.accept(3, None), Err(Error::Duplicate))); + let group = fill.accept(3, Info::timed()).unwrap().expect("a fresh group"); + assert!(matches!(fill.accept(3, None), Ok(None))); assert!(matches!(fill.accept(4, None), Err(Error::InvalidRange))); assert!( matches!(kio::Task::poll(&mut *fetch, &waiter), Poll::Ready(Ok(_))), @@ -24593,8 +24605,8 @@ mod test { (producer, dynamic, subscriber) } - fn write_filled(group: Result, millis: u64) { - let mut group = group.unwrap(); + fn write_filled(group: Result>, millis: u64) { + let mut group = group.unwrap().expect("a fresh group"); group .write_frame(Timestamp::from_millis(millis).unwrap(), &b"x"[..]) .unwrap(); @@ -24872,7 +24884,7 @@ mod test { let Poll::Ready(Ok(first)) = dynamic.poll_requested_groups(&waiter) else { panic!("below the start is a miss"); }; - let group = first.accept(3, None).unwrap(); + let group = first.accept(3, None).unwrap().expect("a fresh group"); drop(fetch); group.abort(Error::Cancel).unwrap(); drop(first); @@ -24984,7 +24996,8 @@ mod test { .ok() .unwrap() .insert_group_request(3, group::Bounds::default(), None) - .unwrap(); + .unwrap() + .expect("a fresh group"); assert!(subscriber.poll_recv_group(&waiter).is_pending()); assert!(fill.is_wanted(3), "the answer has not reached the reader yet"); } @@ -25007,7 +25020,7 @@ mod test { let Poll::Ready(Ok(fill)) = dynamic.poll_requested_groups(&waiter) else { panic!("below the start is a miss"); }; - let _writing = fill.accept(0, None).unwrap(); + let _writing = fill.accept(0, None).unwrap().expect("a fresh group"); let Poll::Ready(Ok(Some(group))) = subscriber.poll_next_group(&waiter) else { panic!("the filled group is read"); }; @@ -25152,7 +25165,7 @@ mod test { let Poll::Ready(Ok(fill)) = dynamic.poll_requested_groups(&waiter) else { panic!("below the start is a miss"); }; - let _writing = [fill.accept(0, None).unwrap(), fill.accept(1, None).unwrap()]; + let _writing = [fill.accept(0, None).unwrap().expect("a fresh group"), fill.accept(1, None).unwrap().expect("a fresh group")]; for key in 2..10 { fill.group(key).reject(Error::NotFound); } @@ -25188,7 +25201,7 @@ mod test { }; let group = fill.group(9); let readers = group.readers(); - let _writing = group.accept(None).unwrap(); + let _writing = group.accept(None).unwrap().expect("a fresh group"); assert!(readers.poll_unwanted(&waiter).is_pending()); subscriber.update(descending(Range::groups(0..9))).unwrap(); @@ -25707,8 +25720,8 @@ mod test { let (producer, _pool) = pooled_producer((cached * size) as u64); let dynamic = producer.requests(); let mut subscriber = producer.subscribe(replay().with_order(Order::Ascending)); - let write = |group: Result, key: u64| { - let mut group = group.unwrap(); + let write = |group: Result>, key: u64| { + let mut group = group.unwrap().expect("a fresh group"); group .write_frame(Timestamp::from_millis(key).unwrap(), vec![0u8; size]) .unwrap(); @@ -25748,7 +25761,7 @@ mod test { taken }; for key in 0..GROUPS { - write(producer.create_group(group::Info { start: key }), key); + write(producer.create_group(group::Info { start: key }).map(Some), key); if key % 4 < pace { take(&mut subscriber); } @@ -25809,15 +25822,15 @@ mod test { let (mut producer, _pool) = pooled_producer(4 * size as u64); let dynamic = producer.requests(); let mut subscriber = producer.subscribe(replay().with_range(0..).with_order(Order::Ascending)); - let write = |group: Result, key: u64| { - let mut group = group.unwrap(); + let write = |group: Result>, key: u64| { + let mut group = group.unwrap().expect("a fresh group"); group .write_frame(Timestamp::from_millis(key).unwrap(), vec![0u8; size]) .unwrap(); group.finish().unwrap(); }; producer.start_at(GROUPS).unwrap(); - write(producer.create_group(group::Info { start: GROUPS }), GROUPS); + write(producer.create_group(group::Info { start: GROUPS }).map(Some), GROUPS); let waiter = kio::Waiter::noop(); assert!(subscriber.poll_next_group(&waiter).is_pending(), "group 0 is a miss"); let Poll::Ready(Ok(mut fill)) = dynamic.poll_requested_groups(&waiter) else { @@ -26736,7 +26749,7 @@ mod test { let mut early = producer.subscribe(replay().with_ranges([Range::live()])); let _fetching = consumer.fetch_group(5, None); let req = dynamic.requested_fill_group().now_or_never().unwrap().unwrap(); - req.accept(None).unwrap().finish().unwrap(); + req.accept(None).unwrap().expect("a fresh group").finish().unwrap(); producer .create_group(group::Info { start: 0 }) .unwrap() @@ -27506,7 +27519,7 @@ mod test { let mut joined = reader(); assert!(joined.poll_recv_group(&waiter).is_pending(), "it joins the taken fill"); for key in 0..2 { - let mut group = fill.accept(key, None).unwrap(); + let mut group = fill.accept(key, None).unwrap().expect("a fresh group"); group .write_frame(Timestamp::from_millis(key).unwrap(), &b"x"[..]) .unwrap(); @@ -28252,7 +28265,7 @@ mod test { live.write_frame(live.key_time(), &b"delta"[..]).unwrap(); let _fetch = consumer.fetch_group(0, None); let fill = dynamic.requested_groups().await.unwrap(); - let mut head = fill.accept(0, Info::timed()).unwrap(); + let mut head = fill.accept(0, Info::timed()).unwrap().expect("a fresh group"); head.write_frame(head.key_time(), &b"snapshot"[..]).unwrap(); producer.drop_groups(0..1, StreamError::App(5)); @@ -28764,7 +28777,7 @@ mod test { }, ); let fill = dynamic.requested_fill_group().await.unwrap(); - let mut tail = fill.accept(Info::timed()).unwrap(); + let mut tail = fill.accept(Info::timed()).unwrap().expect("a fresh group"); for frame in start..end { tail.write_frame(tail.key_time(), vec![frame as u8; size]).unwrap(); } @@ -28843,7 +28856,8 @@ mod test { }, None, ) - .unwrap(); + .unwrap() + .expect("a fresh group"); tail.write_frame(tail.key_time(), vec![start as u8; 4]).unwrap(); let tail = tail.finish().unwrap(); held.push(tail.consume().with_range(start..)); @@ -28868,7 +28882,8 @@ mod test { .ok() .unwrap() .insert_group_request(0, group::Bounds { start: 0, end: Some(1) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); assert!(Arc::ptr_eq(&owner, &refill.handle().content().unwrap())); refill.write_frame(refill.key_time(), b"zero".as_slice()).unwrap(); let refill = refill.finish().unwrap(); @@ -28888,7 +28903,8 @@ mod test { .ok() .unwrap() .insert_group_request(0, group::Bounds { start: 0, end: Some(1) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); new.write_frame(new.key_time(), b"new zero".as_slice()).unwrap(); assert!(!Arc::ptr_eq(&owner, &new.handle().content().unwrap())); assert_eq!(held[0].read_frame().await.unwrap().unwrap().payload.as_ref(), &[4; 4]); @@ -28925,7 +28941,8 @@ mod test { .ok() .unwrap() .insert_group_request(0, group::Bounds { start: 3, end: Some(5) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); second.write_frame(second.key_time(), b"three".as_slice()).unwrap(); let mut second_read = second.consume().with_range(4..); let mut second = second @@ -29037,7 +29054,8 @@ mod test { .ok() .unwrap() .insert_group_request(0, group::Bounds { start: 1, end: Some(3) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); head.set_wire(wire(90)).unwrap(); let head = write(head, 90, b"b"); let head = write(head, 100, b"a"); @@ -29053,7 +29071,8 @@ mod test { .ok() .unwrap() .insert_group_request(0, group::Bounds { start: 0, end: Some(2) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); earlier.set_wire(wire(90)).unwrap(); let earlier = write(earlier, 90, b"b"); let earlier = write(earlier, 95, b"c"); @@ -29176,7 +29195,7 @@ mod test { ); let fill = requests.requested_fill_group().await.unwrap(); assert_eq!((fill.frame_start(), fill.frame_end()), (0, None)); - let mut head = fill.accept(info).unwrap(); + let mut head = fill.accept(info).unwrap().expect("a fresh group"); for object in &stored[..8] { head = ingest(head, object); } @@ -29270,7 +29289,8 @@ mod test { .ok() .unwrap() .insert_group_request(0, group::Bounds { start: 3, end: Some(4) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); head.write_frame(head.key_time(), b"three".as_slice()).unwrap(); head.finish().unwrap(); let identity = Arc::downgrade(&observing.content().unwrap()); @@ -29293,7 +29313,8 @@ mod test { .ok() .unwrap() .insert_group_request(0, group::Bounds { start: 4, end: Some(5) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); assert!(Arc::ptr_eq( &identity.upgrade().unwrap(), &refill.handle().content().unwrap() @@ -29333,7 +29354,8 @@ mod test { .ok() .unwrap() .insert_group_request(0, group::Bounds { start: 0, end: Some(1) }, None) - .unwrap(); + .unwrap() + .expect("a fresh group"); head.write_frame(head.key_time(), bytes::Bytes::new()).unwrap(); let head = head.finish().unwrap(); assert_eq!(live.handle().content().unwrap().cost().0, FRAMES + 1); @@ -29464,7 +29486,7 @@ mod test { Poll::Pending => panic!("a flight is asked"), }; assert_eq!(fill.start(), Position { group: 0, frame: 0 }); - let mut flight = fill.accept(0, None).unwrap(); + let mut flight = fill.accept(0, None).unwrap().expect("a fresh group"); assert_eq!(read_numbered(&mut late), None, "aboard, waiting on the handler"); let unwanted = |flight: &group::Producer| flight.handle().poll_unwanted(&kio::Waiter::noop()).is_ready(); assert!(!unwanted(&flight), "ridden"); @@ -29527,7 +29549,7 @@ mod test { assert_eq!(read_numbered(&mut behind), None); let fill = asked(&requests).expect("a flight"); assert_eq!(fill.start(), Position { group: 0, frame: 0 }, "from frame 0"); - let mut flight = fill.accept(0, None).unwrap(); + let mut flight = fill.accept(0, None).unwrap().expect("a fresh group"); let unwanted = |flight: &group::Producer| flight.handle().poll_unwanted(&kio::Waiter::noop()).is_ready(); for index in 0..10 { flight @@ -29602,7 +29624,7 @@ mod test { assert_eq!(read_numbered(&mut second), None); let fill = asked(&requests).expect("a flight"); assert!(asked(&requests).is_none(), "the second joiner shares it"); - let mut flight = fill.accept(0, None).unwrap(); + let mut flight = fill.accept(0, None).unwrap().expect("a fresh group"); // 8 MiB in, half the reach. for index in 0..500 { flight @@ -29653,7 +29675,7 @@ mod test { .unwrap(); } assert_eq!(read_numbered(&mut late), None); - let mut flight = asked(&requests).expect("a flight").accept(0, None).unwrap(); + let mut flight = asked(&requests).expect("a flight").accept(0, None).unwrap().expect("a fresh group"); assert_eq!(read_numbered(&mut late), None); for index in 0..1_000 { flight @@ -29761,7 +29783,7 @@ mod test { assert_eq!(read_numbered(&mut loose), None, "asks again"); let req = requests.requested_fill_group().now_or_never().unwrap().unwrap(); assert_eq!(req.max_delay(), Some(Duration::from_secs(10))); - let mut flight = req.accept(None).unwrap(); + let mut flight = req.accept(None).unwrap().expect("a fresh group"); flight .write_frame(crate::Timestamp::unscaled(flight.start), numbered(0)) .unwrap(); @@ -29793,7 +29815,7 @@ mod test { .unwrap(); } assert_eq!(read_numbered(&mut late), None); - let mut flight = asked(&requests).expect("a flight").accept(0, None).unwrap(); + let mut flight = asked(&requests).expect("a flight").accept(0, None).unwrap().expect("a fresh group"); assert_eq!(read_numbered(&mut late), None); // A newer group leaves group 0 cold, and its cached copy goes whole. let mut newer = producer.append_next().unwrap(); @@ -29853,7 +29875,7 @@ mod test { let (mut fast, mut slow) = (live.consume(), live.consume()); assert_eq!(read_numbered(&mut fast), None); assert_eq!(read_numbered(&mut slow), None); - let mut flight = asked(&requests).unwrap().accept(0, None).unwrap(); + let mut flight = asked(&requests).unwrap().accept(0, None).unwrap().expect("a fresh group"); assert_eq!(read_numbered(&mut fast), None); assert_eq!(read_numbered(&mut slow), None); assert_eq!(read_numbered(&mut slow), None); @@ -30048,7 +30070,7 @@ mod test { .expect("the miss asks a fill") .unwrap(); assert_eq!(fill.key(), 1); - let mut group = fill.accept(Info::timed()).unwrap(); + let mut group = fill.accept(Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"filled")) .unwrap(); @@ -30159,7 +30181,7 @@ mod test { .expect("the holes are asked at once") .unwrap(); assert_eq!((fill.start(), fill.end()), (Position::group(0), 2)); - let mut group = fill.accept(0, Info::timed()).unwrap(); + let mut group = fill.accept(0, Info::timed()).unwrap().expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"filled")) .unwrap(); diff --git a/rs/moq-net/src/model/track/fill.rs b/rs/moq-net/src/model/track/fill.rs index fab777aefc5..cfce50eb7a1 100644 --- a/rs/moq-net/src/model/track/fill.rs +++ b/rs/moq-net/src/model/track/fill.rs @@ -947,9 +947,9 @@ impl FillLookup { /// handing it to the readers waiting on the lookup, and return a [`group::Producer`] to fill. /// /// `info` sets the track's [`Info`] if it hasn't been accepted yet, and is ignored otherwise. - /// Errors with [`Error::Duplicate`] if the group was already answered or cached, + /// Returns `None` if the group was already answered or cached. Errors with /// [`Error::Skipped`] if the track skipped it, or the track's abort error. - pub fn accept(&self, key: u64, info: impl Into>) -> Result { + pub fn accept(&self, key: u64, info: impl Into>) -> Result> { self.inner.accept(key, info.into()) } @@ -1012,10 +1012,10 @@ impl FillGroups { /// The group starts at [`start`](Self::start)'s frame when it is the first group, so the /// frames written keep the indices they have in the group. `info` sets the track's /// [`Info`] if it hasn't been accepted yet (a fetch with no live subscription), and is - /// ignored otherwise. Errors with [`Error::InvalidRange`] outside the fill, - /// [`Error::Duplicate`] if the group was already answered or cached, [`Error::Skipped`] if - /// the track skipped it, or the track's abort error. - pub fn accept(&self, key: u64, info: impl Into>) -> Result { + /// ignored otherwise. Returns `None` if the group was already answered or cached. Errors + /// with [`Error::InvalidRange`] outside the fill, [`Error::Skipped`] if the track skipped + /// it, or the track's abort error. + pub fn accept(&self, key: u64, info: impl Into>) -> Result> { self.inner.accept(key, info.into()) } @@ -1359,11 +1359,11 @@ impl Inner { } } - fn accept(&self, key: u64, info: Option) -> Result { + fn accept(&self, key: u64, info: Option) -> Result> { self.accept_from(key, info, self.bounds(key)) } - fn accept_from(&self, key: u64, info: Option, frames: group::Bounds) -> Result { + fn accept_from(&self, key: u64, info: Option, frames: group::Bounds) -> Result> { if !self.contains(key) { return Err(Error::InvalidRange); } @@ -1371,7 +1371,7 @@ impl Inner { return Err(Error::InvalidRange); }; if self.result.read().resolved.contains(&key) { - return Err(Error::Duplicate); + return Ok(None); } // Written for a reader that has yet to pick it up, which the next group waits on. // Recorded before the group is cached, since a reader may take it from the cache and @@ -1389,7 +1389,7 @@ impl Inner { // Cache the group before answering: readers resolve an accept through the cache. let res = TrackState::modify(&self.state).and_then(|mut state| { let res = match self.flight { - true => state.insert_flight(key, frames, info), + true => state.insert_flight(key, frames, info).map(Some), false => state.insert_group_request(key, frames, info), }; let deferred = state.deferred(); @@ -1398,14 +1398,14 @@ impl Inner { res }); if unseen - && res.is_err() + && !matches!(res, Ok(Some(_))) && let Some(pending) = self.fills.lock().pending.get_mut(&self.id) { pending.unseen.remove(key..end); } if let Ok(mut outcome) = self.result.write() { outcome.accept(key..end); - if let Ok(group) = &res + if let Ok(Some(group)) = &res && (self.flight || frames.start > 0 || frames.end.is_some()) { outcome.partial.insert(key, group.handle()); @@ -1652,7 +1652,7 @@ impl GroupFill { } /// Accept the actual wire range, which an older or compressed upstream may have widened. - pub(crate) fn accept_from(&self, info: Info, frames: group::Bounds) -> Result { + pub(crate) fn accept_from(&self, info: Info, frames: group::Bounds) -> Result> { self.inner.accept_from(self.key, Some(info), frames) } @@ -1680,7 +1680,7 @@ impl GroupFill { /// Insert the group into the cache, as [`FillGroups::accept`]. #[cfg(test)] - pub(crate) fn accept(self, info: impl Into>) -> Result { + pub(crate) fn accept(self, info: impl Into>) -> Result> { self.inner.accept(self.key, info.into()) } diff --git a/rs/moq-net/src/transport.rs b/rs/moq-net/src/transport.rs index 1c6da6e9e54..0ed13b38394 100644 --- a/rs/moq-net/src/transport.rs +++ b/rs/moq-net/src/transport.rs @@ -683,20 +683,6 @@ pub mod poll { } } - /// What [`SendStream::poll_acked`] learned about the bytes below an offset. - #[derive(Clone, Copy, Debug, PartialEq, Eq)] - #[non_exhaustive] - pub enum Acked { - /// The peer acknowledged every byte below the offset. - Delivered, - /// The transport cannot see acknowledgments, so delivery is unknown, never assumed. - Unsupported, - /// The transport handed every byte below the offset to a reliable link, such as qmux's - /// TCP, which delivers it unless the link fails. Not an acknowledgment: it says nothing of - /// when the peer got it, but a reset can no longer discard it. - Sent, - } - /// An outgoing stream with partial writes, priorities, and reset codes. pub trait SendStream: 'static { /// The error type for every operation on this stream. @@ -712,17 +698,17 @@ pub mod poll { /// The position just past every byte written so far. fn offset(&self) -> Self::Offset; - /// Poll until the peer acknowledged every byte below `offset`. + /// Poll until every byte below `offset` reaches the peer unless the session fails. /// - /// Errors once those bytes can never be acknowledged: the stream was reset by either - /// side or the session closed. Bytes already acknowledged stay so after a reset or stop. - /// A transport over a reliable link answers [`Acked::Sent`] once the link took them. - /// A transport that cannot see acknowledgments is ready with [`Acked::Unsupported`] - /// immediately, the default, on every stream, so a caller can decide once per session. An - /// offset minted by another stream may panic. - fn poll_acked(&self, waiter: &kio::Waiter, offset: &Self::Offset) -> Poll> { + /// That is once the peer acknowledged them, or, over a reliable link such as qmux's TCP, + /// once the link took them, so a reset can no longer discard them. Errors once those + /// bytes can never get there: the stream was reset by either side or the session closed. + /// Bytes already acknowledged stay so after a reset or stop. The default, for a transport + /// that cannot see acknowledgments, is ready at once: the bytes it took are all it knows. + /// An offset minted by another stream may panic. + fn poll_acked(&self, waiter: &kio::Waiter, offset: &Self::Offset) -> Poll> { let _ = (waiter, offset); - Poll::Ready(Ok(Acked::Unsupported)) + Poll::Ready(Ok(())) } /// Poll to write some of the buffer to the stream, returning how many bytes were diff --git a/rs/moq-net/src/transport/boxed.rs b/rs/moq-net/src/transport/boxed.rs index 45610a0e408..5e65e8d34ac 100644 --- a/rs/moq-net/src/transport/boxed.rs +++ b/rs/moq-net/src/transport/boxed.rs @@ -402,7 +402,7 @@ impl Listed { let offset = state.stream.offset(); matches!( state.stream.poll_acked(&kio::Waiter::noop(), &offset), - Poll::Ready(Ok(poll::Acked::Delivered)) + Poll::Ready(Ok(())) ) } @@ -605,7 +605,7 @@ trait ErasedSend: Send + Sync { fn reset(&mut self, code: u32); fn poll_closed(&self, waiter: &kio::Waiter) -> Poll>; fn offset(&self) -> Offset; - fn poll_acked(&self, waiter: &kio::Waiter, offset: &Offset) -> Poll>; + fn poll_acked(&self, waiter: &kio::Waiter, offset: &Offset) -> Poll>; } trait ErasedRecv: Send + Sync { @@ -783,7 +783,7 @@ impl + Send + Sync> Offset(Box::new(poll::SendStream::offset(self))) } - fn poll_acked(&self, waiter: &kio::Waiter, offset: &Offset) -> Poll> { + fn poll_acked(&self, waiter: &kio::Waiter, offset: &Offset) -> Poll> { let offset = offset .0 .downcast_ref::() @@ -948,7 +948,7 @@ impl poll::SendStream for SendStream { self.get().offset() } - fn poll_acked(&self, waiter: &kio::Waiter, offset: &Offset) -> Poll> { + fn poll_acked(&self, waiter: &kio::Waiter, offset: &Offset) -> Poll> { self.get().poll_acked(waiter, offset) } @@ -1195,9 +1195,9 @@ mod test { self.written } - fn poll_acked(&self, _: &kio::Waiter, offset: &u64) -> Poll> { + fn poll_acked(&self, _: &kio::Waiter, offset: &u64) -> Poll> { match *offset <= self.acked { - true => Poll::Ready(Ok(poll::Acked::Delivered)), + true => Poll::Ready(Ok(())), false => Poll::Pending, } } @@ -1224,8 +1224,8 @@ mod test { } } - /// A boxed stream hands back the transport's own offset, and reports a transport - /// without acknowledgments as unsupported, listed or not. + /// A boxed stream hands back the transport's own offset, and a transport without + /// acknowledgments answers at once, listed or not. #[test] fn a_boxed_stream_forwards_acknowledgment() { let waiter = kio::Waiter::noop(); @@ -1242,7 +1242,7 @@ mod test { let five = poll::SendStream::offset(&stream); assert!(matches!( poll::SendStream::poll_acked(&stream, &waiter, &three), - Poll::Ready(Ok(poll::Acked::Delivered)) + Poll::Ready(Ok(())) )); assert!(poll::SendStream::poll_acked(&stream, &waiter, &five).is_pending()); @@ -1251,7 +1251,7 @@ mod test { let offset = poll::SendStream::offset(&listed); assert!(matches!( poll::SendStream::poll_acked(&listed, &waiter, &offset), - Poll::Ready(Ok(poll::Acked::Unsupported)) + Poll::Ready(Ok(())) )); } diff --git a/rs/moq-net/src/transport/memory.rs b/rs/moq-net/src/transport/memory.rs index 2cebb878d8d..59d36e88ca5 100644 --- a/rs/moq-net/src/transport/memory.rs +++ b/rs/moq-net/src/transport/memory.rs @@ -557,9 +557,9 @@ impl Channel { /// Whether the reader took every byte before `offset`, which stands in for an /// acknowledgement, failing once a reset or stop means it never will. - fn acked(&self, offset: u64) -> Poll> { + fn acked(&self, offset: u64) -> Poll> { if offset <= self.taken { - return Poll::Ready(Ok(poll::Acked::Delivered)); + return Poll::Ready(Ok(())); } match self.end { Some(End::Reset(_)) => Poll::Ready(Err(Error::Closed)), @@ -603,7 +603,7 @@ impl poll::SendStream for SendStream { /// Delivered once the reader took every byte before `offset`, which stands in for an /// acknowledgement as it does for [`poll_closed`](poll::SendStream::poll_closed). - fn poll_acked(&self, waiter: &kio::Waiter, offset: &u64) -> Poll> { + fn poll_acked(&self, waiter: &kio::Waiter, offset: &u64) -> Poll> { // Check the close first, so bytes taken before it still count below. let closed = poll_close(&self.close, waiter); if let Poll::Ready(channel) = self.channel.poll(waiter, |channel| channel.acked(*offset).map(drop)) { @@ -1215,7 +1215,7 @@ mod tests { let (mut send, mut recv) = uni(&a, &b); assert!(matches!( acked(&send, send.offset()), - Poll::Ready(Ok(poll::Acked::Delivered)) + Poll::Ready(Ok(())) )); ready(write(&mut send, &Bytes::from_static(b"one"))).unwrap(); @@ -1231,11 +1231,11 @@ mod tests { assert!(send.poll_acked(&waiter, &one).is_pending()); assert_eq!(text(read(&mut recv, 4)), "one"); assert!(count.0.load(Ordering::Relaxed) > 0, "the read did not wake the writer"); - assert!(matches!(acked(&send, one), Poll::Ready(Ok(poll::Acked::Delivered)))); + assert!(matches!(acked(&send, one), Poll::Ready(Ok(())))); assert!(acked(&send, two).is_pending()); send.reset(1); - assert!(matches!(acked(&send, one), Poll::Ready(Ok(poll::Acked::Delivered)))); + assert!(matches!(acked(&send, one), Poll::Ready(Ok(())))); assert!(matches!(acked(&send, two), Poll::Ready(Err(Error::Closed)))); let (mut send, mut recv) = uni(&a, &b); diff --git a/rs/moq-net/tests/integration/fetch_cancel.rs b/rs/moq-net/tests/integration/fetch_cancel.rs index 77e5d399464..d9b7cc7f13e 100644 --- a/rs/moq-net/tests/integration/fetch_cancel.rs +++ b/rs/moq-net/tests/integration/fetch_cancel.rs @@ -81,7 +81,7 @@ async fn abandoned_fetch_reaches_the_publisher(version: &str, relays: u64, stage .unwrap_or_else(|_| panic!("{ctx}: the publisher's fetch is still wanted")); } Stage::MidResponse => { - let mut group = request.accept(0, timed()).unwrap(); + let mut group = request.accept(0, timed()).unwrap().expect("a fresh group"); group .write_frame(group.at_start(), Bytes::from_static(b"head")) .unwrap(); @@ -118,7 +118,7 @@ async fn abandoned_fetch_reaches_the_publisher(version: &str, relays: u64, stage assert_eq!(payloads, [&b"head"[..], &b"tail"[..]], "{ctx}"); } Stage::Drained => { - let mut group = request.accept(0, timed()).unwrap(); + let mut group = request.accept(0, timed()).unwrap().expect("a fresh group"); group .write_frame(group.at_start(), Bytes::from_static(b"head")) .unwrap(); @@ -204,7 +204,7 @@ async fn a_refetch_within_the_linger_stays_on_the_relay(version: &str) { } futures::future::Either::Right(_) => panic!("nothing answered the fetch"), }; - let mut group = request.accept(0, timed()).unwrap(); + let mut group = request.accept(0, timed()).unwrap().expect("a fresh group"); group .write_frame(group.at_start(), Bytes::from_static(b"segment")) .unwrap(); diff --git a/rs/moq-net/tests/integration/fetch_pipeline.rs b/rs/moq-net/tests/integration/fetch_pipeline.rs index bc0aa1eee00..20cfc198a73 100644 --- a/rs/moq-net/tests/integration/fetch_pipeline.rs +++ b/rs/moq-net/tests/integration/fetch_pipeline.rs @@ -102,7 +102,7 @@ async fn the_first_fetch_goes_out_with_the_info_request() { for relays in [0, 1] { let (request, fill, fetching, _held) = fetch_ahead(version, relays).await; let _track = request.accept(timed()); - let mut group = fill.accept(0, timed()).unwrap(); + let mut group = fill.accept(0, timed()).unwrap().expect("a fresh group"); group.write_frame(group.at_start(), b"early".as_ref()).unwrap(); group.finish().unwrap(); let mut fetched = kio::clock::timeout(TIMEOUT, fetching) diff --git a/rs/moq-net/tests/integration/flights.rs b/rs/moq-net/tests/integration/flights.rs index b39b37367a6..a995b586e75 100644 --- a/rs/moq-net/tests/integration/flights.rs +++ b/rs/moq-net/tests/integration/flights.rs @@ -85,7 +85,7 @@ fn serve(requests: track::Requests, written: Arc, ended: Arc Poll> { + fn poll_acked(&self, waiter: &kio::Waiter, offset: &u64) -> Poll> { self.inner.poll_acked(waiter, offset) } diff --git a/rs/moq-net/tests/integration/untimed.rs b/rs/moq-net/tests/integration/untimed.rs index 6cbc04f32e3..b88b1beb721 100644 --- a/rs/moq-net/tests/integration/untimed.rs +++ b/rs/moq-net/tests/integration/untimed.rs @@ -304,7 +304,7 @@ async fn a_fetched_untimed_frame_arrives_untimed() { } futures::future::Either::Right(_) => panic!("nothing answered the fetch"), }; - let mut group = request.accept(3, timed()).unwrap(); + let mut group = request.accept(3, timed()).unwrap().expect("a fresh group"); group .write_frame( moq_net::Timestamp::unscaled(group.start), diff --git a/rs/moq-relay/src/relay.rs b/rs/moq-relay/src/relay.rs index 0d858761378..bb4497678a0 100644 --- a/rs/moq-relay/src/relay.rs +++ b/rs/moq-relay/src/relay.rs @@ -249,20 +249,12 @@ impl Relay { false => server_config.init()?, }; - // `None` for a stream-only server (no QUIC); any other error is real. + // `None` for a stream-only server (no QUIC). #[cfg(uring)] let uring_addr = uring.as_ref().map(crate::uring::Workers::local_addr); #[cfg(not(uring))] let uring_addr: Option = None; - let addr = match (workers_addr, uring_addr) { - (Some(addr), _) => Some(addr), - (None, Some(addr)) => Some(addr), - (None, None) => match server.local_addr() { - Ok(addr) => Some(addr), - Err(moq_tokio::Error::NoBackend(_)) => None, - Err(err) => return Err(err).context("failed to resolve the QUIC bind address"), - }, - }; + let addr = workers_addr.or(uring_addr).or_else(|| server.local_addr()); // The io_uring workers serve QUIC without the demux, and a stream-only relay // has no UDP port at all. diff --git a/rs/moq-relay/tests/drills.rs b/rs/moq-relay/tests/drills.rs index 73901be9076..9d1ffc2149a 100644 --- a/rs/moq-relay/tests/drills.rs +++ b/rs/moq-relay/tests/drills.rs @@ -30,6 +30,7 @@ use std::time::Duration; use futures::FutureExt; use moq_relay::{Config, Relay}; +use moq_tokio::connection::Phase; /// A millisecond track with no publisher max age: the frames written here carry timestamps, /// and superseded groups stay readable. @@ -595,11 +596,11 @@ async fn relay_killed_mid_group_aborts_then_resumes(lane: Lane) { .broadcast() .create_track(TRACK, timed()) .expect("create track"); - let mut publish_loop = client(&url).publish(publisher.consume()).expect("no connect url"); + let publish_loop = client(&url).publish(publisher.consume()).expect("no connect url"); let subscriber = moq_tokio::origin::spawn(); let subscribed = subscriber.consume(); - let mut subscribe_loop = client(&url).consume(subscriber).expect("no connect url"); + let subscribe_loop = client(&url).consume(subscriber).expect("no connect url"); write_group(&mut track, b"before"); let mut reader = subscribe(&subscribed, "live").await; @@ -640,14 +641,14 @@ async fn relay_killed_mid_group_aborts_then_resumes(lane: Lane) { println!("fault activated: interrupted group aborted with {err}"); // Fault activation: both loops noticed they lost the relay. - expect_status(&mut subscribe_loop, moq_tokio::Status::Disconnected, "subscriber").await; - expect_status(&mut publish_loop, moq_tokio::Status::Disconnected, "publisher").await; + expect_phase(&subscribe_loop, disconnected, "subscriber").await; + expect_phase(&publish_loop, disconnected, "publisher").await; let relay = replacement; path.retarget(&relay); - expect_status(&mut subscribe_loop, moq_tokio::Status::Connected, "subscriber").await; - expect_status(&mut publish_loop, moq_tokio::Status::Connected, "publisher").await; + expect_phase(&subscribe_loop, connected, "subscriber").await; + expect_phase(&publish_loop, connected, "publisher").await; // The outage is observed, not hidden: the broadcast the dead session fed closed // with it, so the old subscription ends rather than reading from a stale route. @@ -677,16 +678,23 @@ async fn relay_killed_mid_group_aborts_then_resumes(lane: Lane) { lanes!(relay_killed_mid_group_aborts_then_resumes); -/// Wait for a reconnect loop to report `want`, failing with what it said instead. -async fn expect_status(reconnect: &mut moq_tokio::Connection, want: moq_tokio::Status, who: &str) { - loop { - let status = kio::clock::timeout(TIMEOUT, reconnect.status()) +fn connected(phase: &Phase) -> bool { + matches!(phase, Phase::Connected { .. }) +} + +fn disconnected(phase: &Phase) -> bool { + matches!(phase, Phase::Disconnected { .. }) +} + +/// Wait for a reconnect loop's phase to match `want`, failing with what it reached instead. +async fn expect_phase(reconnect: &moq_tokio::Connection, want: fn(&Phase) -> bool, who: &str) { + let monitor = reconnect.monitor(); + let mut seen = monitor.state(); + while !want(&seen.phase) { + seen = kio::clock::timeout(TIMEOUT, monitor.state_changed(seen.revision)) .await - .unwrap_or_else(|_| panic!("{who}: no status change within {TIMEOUT:?}, wanted {want:?}")) + .unwrap_or_else(|_| panic!("{who}: still {:?} after {TIMEOUT:?}", seen.phase)) .unwrap_or_else(|err| panic!("{who}: reconnect loop gave up: {err}")); - if status == want { - return; - } } } diff --git a/rs/moq-relay/tests/integration/handoff.rs b/rs/moq-relay/tests/integration/handoff.rs index d241ee1d125..29b7b30511f 100644 --- a/rs/moq-relay/tests/integration/handoff.rs +++ b/rs/moq-relay/tests/integration/handoff.rs @@ -510,13 +510,17 @@ async fn a_killed_relay_s_clients_are_reset_by_the_one_it_replaced() { let mut new = relay(dir.path(), &cert, &key, port, ¬ify_path); ready(¬ify).await; - let mut orphan = established(dial().init(quic).unwrap(), &url).await; + let orphan = established(dial().init(quic).unwrap(), &url).await; // Past the default healthy bar, so the reset reconnects rather than ending the loop. kio::clock::sleep(Duration::from_secs(1)).await; new.kill().await.unwrap(); + let monitor = orphan.monitor(); kio::clock::timeout(TIMEOUT, async { - while orphan.status().await.unwrap() != moq_tokio::Status::Disconnected {} + let mut seen = monitor.state(); + while !matches!(seen.phase, moq_tokio::connection::Phase::Disconnected { .. }) { + seen = monitor.state_changed(seen.revision).await.unwrap(); + } }) .await .expect("the killed relay's client was never reset"); diff --git a/rs/moq-relay/tests/integration/smoke.rs b/rs/moq-relay/tests/integration/smoke.rs index 242c34453f0..3208206a778 100644 --- a/rs/moq-relay/tests/integration/smoke.rs +++ b/rs/moq-relay/tests/integration/smoke.rs @@ -689,7 +689,7 @@ async fn spawn_accept_relay( let cluster = crate::spawn_cluster(cluster::Options::default()); let mut server = server.listen().await.expect("listen"); - let quic = server.local_addr().ok(); + let quic = server.local_addr(); let tcp = server.tcp_local_addr(); let handle = tokio::spawn(async move { diff --git a/rs/moq-rtsp/src/client.rs b/rs/moq-rtsp/src/client.rs index 1db1a493888..e29844e6481 100644 --- a/rs/moq-rtsp/src/client.rs +++ b/rs/moq-rtsp/src/client.rs @@ -175,7 +175,7 @@ impl Client { let track = match kind { Kind::H264 => { let track = - broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video))?; + broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)); Track::Video(Box::new(Video::H264 { split: h264::Split::new(), import: h264::Import::new(track, reserved.clone(), Default::default())?, @@ -183,7 +183,7 @@ impl Client { } Kind::H265 => { let track = - broadcast.unique_track(".hev1", catalog.track_info(hang::catalog::PRIORITY.video))?; + broadcast.unique_track(".hev1", catalog.track_info(hang::catalog::PRIORITY.video)); Track::Video(Box::new(Video::H265 { split: h265::Split::new(), import: h265::Import::new(track, reserved.clone(), Default::default())?, @@ -195,7 +195,7 @@ impl Client { }; let config = aac::config(params.extra_data())?; let track = - broadcast.unique_track(".aac", catalog.track_info(hang::catalog::PRIORITY.audio))?; + broadcast.unique_track(".aac", catalog.track_info(hang::catalog::PRIORITY.audio)); Track::Aac(Box::new(aac::Import::new(track, reserved.clone(), config)?)) } }; diff --git a/rs/moq-stats/src/produce.rs b/rs/moq-stats/src/produce.rs index 1e89e76ae79..6dac3696aec 100644 --- a/rs/moq-stats/src/produce.rs +++ b/rs/moq-stats/src/produce.rs @@ -631,7 +631,7 @@ fn config() -> moq_json::snapshot::Config { impl Output { fn create(broadcast: &broadcast::Producer, name: &str) -> Result { - Ok(Self::new(broadcast.create_track(name, info())?)) + Ok(Self::new(broadcast.create_track(name, info()).ok_or(moq_net::Error::Duplicate)?)) } /// Publish on the track `request` asked for, or create `name` without one. @@ -931,7 +931,7 @@ impl BucketTrack { // an earlier epoch's, and its first MoQ group is where they start. let epoch = Epoch::mint(); let name = crate::bucket_track(bucket, &epoch); - let track = broadcast.create_track(name.as_str(), info())?; + let track = broadcast.create_track(name.as_str(), info()).ok_or(moq_net::Error::Duplicate)?; Ok(Self { name, snapshot: Snapshot::new(track, config()).fresh(), diff --git a/rs/moq-tokio/examples/chat.rs b/rs/moq-tokio/examples/chat.rs index b78167ef08b..1cdc0508644 100644 --- a/rs/moq-tokio/examples/chat.rs +++ b/rs/moq-tokio/examples/chat.rs @@ -53,7 +53,7 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> // Frames are stamped with this host's wall clock in milliseconds, so the track declares that // timescale. let info = moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI); - let mut track = route.broadcast().create_track("chat", info)?; + let mut track = route.broadcast().create_track("chat", info).context("the track already exists")?; // Create a group, which starts at its first frame's timestamp. // Each group is independent and the newest group(s) will be prioritized. diff --git a/rs/moq-tokio/examples/clock.rs b/rs/moq-tokio/examples/clock.rs index 09fc3c12152..6b9c8032e52 100644 --- a/rs/moq-tokio/examples/clock.rs +++ b/rs/moq-tokio/examples/clock.rs @@ -70,7 +70,7 @@ async fn main() -> anyhow::Result<()> { .route(&config.broadcast, moq_net::origin::RouteOptions::hidden()) .context("failed to create broadcast")?; let info = moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI); - let track = route.broadcast().create_track(track, info)?; + let track = route.broadcast().create_track(track, info).context("the track already exists")?; route.announce().context("failed to announce broadcast")?; let clock = Publisher::new(track); diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index 6e476b5b75f..9053871a2b5 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -252,22 +252,6 @@ impl Backoff { } } -/// A connection lifecycle transition reported by [`Connection::status`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub enum Status { - /// A session connected and its peer accepted the connection credential (the first - /// connect, or a reconnect after a drop). On moq-lite 03/04, which never answer the - /// credential, the session must stay up past [`Backoff::healthy`] instead. A session the - /// peer refuses never reports it. - Connected, - /// An established session dropped; a reconnect attempt follows. - Disconnected, - /// The peer sent a GOAWAY; a replacement session is coming up while the old one - /// keeps serving. - Migrating, -} - /// What to do with the URI a peer names in its GOAWAY, as `--connect-goaway-redirect` /// spells it. See [`moq_net::reconnect::Redirect`] for what each one risks. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, usage_rs::ValueEnum, serde::Serialize, serde::Deserialize)] @@ -463,16 +447,6 @@ struct Draining { } impl Lifecycle { - /// What [`Connection::status`] reports: `None` before the first connect and once closed. - fn status(&self) -> Option { - match self { - Self::Live(live) if live.migrating.is_some() => Some(Status::Migrating), - Self::Live(_) => Some(Status::Connected), - Self::Offline { .. } => Some(Status::Disconnected), - Self::Connecting { .. } | Self::Closed(_) => None, - } - } - fn live(&self) -> Option<&Live> { match self { Self::Live(live) => Some(live), @@ -860,8 +834,8 @@ impl Monitor { /// Wait until either presence counter moves past what this handle last reported. /// - /// Unlike [`Connection::status`], a connect and disconnect that both land before the caller polls - /// are not coalesced away: the counters still moved. + /// Unlike [`Self::state_changed`], a connect and disconnect that both land before the caller + /// polls are not coalesced away: the counters still moved. pub async fn presence_changed(&mut self) -> crate::Result { kio::wait(|waiter| self.poll_presence(waiter)).await } @@ -874,8 +848,8 @@ impl Monitor { /// Why the loop is retrying: the error that ended the last session or failed the /// latest dial, or `None` once a session connects. /// - /// Read it while [`Connection::status`] reports [`Status::Disconnected`]: a redial - /// that keeps failing never changes the status, so this is where its reason shows. + /// Read it while the phase is [`Phase::Disconnected`]: a redial that keeps failing + /// never changes the phase, so this is where its reason shows. /// The loop giving up reports through [`Connection::closed`] instead. pub fn failure(&self) -> Option { self.state.read().lifecycle.failure().cloned() @@ -934,9 +908,6 @@ pub struct Connection { recv_bandwidth: moq_net::bandwidth::Weak, /// Divides `recv_bandwidth`, and every session the loop dials sends its viewers' target. viewers: moq_net::bandwidth::Viewers, - /// The last status returned by [`status`](Self::status), for change detection. - /// Per-clone: a clone starts from its parent's cursor and diverges from there. - last_reported: Option, } /// The connection loop, shared by every [`Connection`] clone and aborted when the @@ -1034,7 +1005,6 @@ impl Connection { recv_bandwidth, bandwidth, viewers, - last_reported: None, } } @@ -1291,7 +1261,7 @@ impl Connection { /// Wait until a session is established, handing the connection back. /// - /// Returns once a session reports [`Status::Connected`], so the first call waits out the + /// Returns once a session reports [`Phase::Connected`], so the first call waits out the /// initial dial and the peer's answer to its credential. If the loop gives up before any /// session did, as when the peer refuses the credential, it returns that error instead. /// Useful when a caller wants dial errors up front rather than through @@ -1306,43 +1276,18 @@ impl Connection { Ok(self) } - /// The connection status, once it changes from what this handle last reported, or the error - /// once the loop has stopped (the give-up error, or a generic one when the handle is dropped). - /// The error comes next once the loop stops, even if a status change went unreported. - /// - /// The loop moves between `Connected`, `Disconnected`, and `Migrating` (a GOAWAY handover, where - /// the old session is still serving), so successive calls report changes rather than a fixed - /// alternation; a status that flips and flips back before the caller polls is reported once. - /// This tracks the *current* state, not every edge. - #[kio::wrapper] - pub fn poll_status(&mut self, waiter: &kio::Waiter) -> Poll> { - let last = self.last_reported; - let status = match ready!(self.state.poll(waiter, |state| match state.lifecycle.status() { - _ if state.lifecycle.is_closed() => Poll::Ready(Err(terminal(state))), - Some(status) if Some(status) != last => Poll::Ready(Ok(status)), - _ => Poll::Pending, - })) { - Ok(res) => res?, - Err(state) => return Poll::Ready(Err(terminal(&state))), - }; - - self.last_reported = Some(status); - Poll::Ready(Ok(status)) - } - - /// Whether a session is currently connected. + /// Whether a session is serving and no GOAWAY is migrating it, as [`Phase::Connected`]. /// - /// The synchronous read behind [`status`](Self::status), for callers that just want the current - /// state rather than the next change. + /// [`Monitor::state_changed`] waits for the next change instead. pub fn connected(&self) -> bool { - self.state.read().lifecycle.status() == Some(Status::Connected) + matches!(&self.state.read().lifecycle, Lifecycle::Live(live) if live.migrating.is_none()) } /// How many sessions have been live on this handle: 1 after the first connect, /// one more per reconnect (and per GOAWAY migration, which is a new session too). /// - /// Advanced in the same write that publishes [`Status::Connected`], so reading - /// after a `Connected` status never returns a stale count. Zero only if no + /// Advanced in the same write that publishes [`Phase::Connected`], so reading + /// after a `Connected` phase never returns a stale count. Zero only if no /// session has connected yet, which [`established`](Self::established) rules out. pub fn connects(&self) -> u64 { self.state.read().connects @@ -1366,7 +1311,7 @@ impl Connection { /// Observe a GOAWAY from the peer, or `None` while between sessions. /// /// The reconnect loop reads the same GOAWAY to drive migration, reported as - /// [`Status::Migrating`], and a GOAWAY is a latch rather than a queue, so watching + /// [`Phase::Migrating`], and a GOAWAY is a latch rather than a queue, so watching /// it here doesn't take it from the loop. Reach for this when you need the message /// itself: its redirect URI and deadline, or (in one-shot mode, where the loop /// ignores GOAWAY entirely) the fact that one arrived at all. @@ -1607,6 +1552,24 @@ mod tests { use super::*; use url::Url; + /// Wait until the connection's phase matches `want`, or the error once the loop stops. + async fn reaches(connection: &Connection, want: fn(&Phase) -> bool) -> crate::Result { + let monitor = connection.monitor(); + let mut seen = monitor.state(); + while !want(&seen.phase) { + seen = monitor.state_changed(seen.revision).await?; + } + Ok(seen.phase) + } + + fn connected(phase: &Phase) -> bool { + matches!(phase, Phase::Connected { .. }) + } + + fn disconnected(phase: &Phase) -> bool { + matches!(phase, Phase::Disconnected { .. }) + } + /// A millisecond track: the frames written here carry timestamps. fn timed() -> moq_net::track::Info { moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI) @@ -2229,7 +2192,7 @@ mod tests { /// A first walk that fails ends the loop rather than retrying, so a test of the retry /// loop starts from a healthy session: this serves one past a [`FAST`] healthy bar, /// repoints `host` at a dead address, and ends the session from the server. Returns the connection, already reporting - /// [`Status::Disconnected`], the live server's address and its later sessions, and the + /// [`Phase::Disconnected`], the live server's address and its later sessions, and the /// server task. async fn redialing( host: &str, @@ -2243,11 +2206,11 @@ mod tests { let (live, mut accepted, task) = serve(crate::origin::spawn()).await; crate::resolve::hosts::point(host, [live]); config.backoff.healthy = Some((FAST).into()); - let mut connection = config + let connection = config .init(Default::default()) .unwrap() .connect(url(&format!("tcp://{host}:1/"))); - assert_eq!(connection.status().await.unwrap(), Status::Connected); + reaches(&connection, connected).await.unwrap(); let session = accepted.recv().await.unwrap(); // Hold the failing listener until the runtime ends: a released port can @@ -2260,7 +2223,7 @@ mod tests { crate::resolve::hosts::point(host, failing); outlast_fast().await; drop(session); - assert_eq!(connection.status().await.unwrap(), Status::Disconnected); + reaches(&connection, disconnected).await.unwrap(); (connection, live, accepted, task) } @@ -2276,7 +2239,7 @@ mod tests { config.backoff.initial = Some((FAST).into()); config.backoff.max = Some((FAST).into()); config.backoff.timeout = Some(crate::cli::Bound::NONE); - let (mut connection, live, mut accepted, _task) = redialing(HOST, config).await; + let (connection, live, mut accepted, _task) = redialing(HOST, config).await; let monitor = connection.monitor(); // The session's end may be reported first; wait for a failed redial's reason. @@ -2299,11 +2262,13 @@ mod tests { matches!(&failure, Error::Tcp(err) if matches!(err.as_ref(), crate::tcp::Error::Connect(reason) if !reason.is_empty())), "{failure}" ); - let transition = futures::FutureExt::now_or_never(connection.status()); - assert!(transition.is_none(), "a failed redial is no status transition"); + assert!( + disconnected(&connection.monitor().state().phase), + "a failed redial changes no phase" + ); crate::resolve::hosts::point(HOST, [live]); - assert_eq!(connection.status().await.unwrap(), Status::Connected); + reaches(&connection, connected).await.unwrap(); assert!(monitor.failure().is_none(), "the connect must clear the failure"); let _session = accepted.recv().await.unwrap(); } @@ -2424,14 +2389,16 @@ mod tests { config.backoff.initial = Some((FAST).into()); config.backoff.max = Some((FAST).into()); config.backoff.healthy = Some((FAST).into()); - let mut connection = config + let connection = config .init(Default::default()) .unwrap() .connect(url(&format!("tcp://{addr}/"))); let session = kio::clock::timeout(WAIT, accepted.recv()).await.unwrap().unwrap(); - let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); - assert_eq!(status.unwrap(), Status::Connected); + kio::clock::timeout(WAIT, reaches(&connection, connected)) + .await + .unwrap() + .unwrap(); outlast_fast().await; connection.auth().abort(moq_net::Error::App(9)); session.abort(moq_net::Error::Cancel); @@ -2491,19 +2458,21 @@ mod tests { }; // The only dial fails, which ends the loop before anything connected. - let mut connection = once().connect(dead().await); - let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); - assert!(status.is_err(), "{status:?}"); + let connection = once().connect(dead().await); + let closed = kio::clock::timeout(WAIT, connection.closed()).await.unwrap(); + assert!(closed.is_err(), "{closed:?}"); // The session ending in one-shot mode ends the loop. let (addr, mut accepted, _task) = serve(crate::origin::spawn()).await; - let mut connection = once().connect(url(&format!("tcp://{addr}/"))); - let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); - assert_eq!(status.unwrap(), Status::Connected); + let connection = once().connect(url(&format!("tcp://{addr}/"))); + kio::clock::timeout(WAIT, reaches(&connection, connected)) + .await + .unwrap() + .unwrap(); let session = kio::clock::timeout(WAIT, accepted.recv()).await.unwrap().unwrap(); session.abort(moq_net::Error::App(7)); - let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); - assert!(status.is_err(), "{status:?}"); + let closed = kio::clock::timeout(WAIT, connection.closed()).await.unwrap(); + assert!(closed.is_err(), "{closed:?}"); } /// A settled answer from one candidate ends the walk instead of being buried. @@ -2963,7 +2932,6 @@ mod tests { /// Its close then reconnects like any drop. #[tokio::test] async fn a_handoff_restart_of_a_young_session_redials_only_once_it_closes() { - use futures::FutureExt; const WAIT: Duration = Duration::from_secs(10); let origin = crate::origin::spawn(); @@ -2978,9 +2946,11 @@ mod tests { .unwrap() .with_subscriber(subscriber.clone()) .with_restart(Restart::Handoff); - let mut connection = client.connect(url(&format!("tcp://{addr}/"))); - let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); - assert_eq!(status.unwrap(), Status::Connected); + let connection = client.connect(url(&format!("tcp://{addr}/"))); + kio::clock::timeout(WAIT, reaches(&connection, connected)) + .await + .unwrap() + .unwrap(); let session = kio::clock::timeout(WAIT, accepted.recv()).await.unwrap().unwrap(); session.goaway(moq_net::goaway::Goaway::new()).unwrap(); @@ -2998,19 +2968,19 @@ mod tests { .is_some_and(|goaway| matches!(goaway.poll(&kio::Waiter::noop()), Poll::Ready(Ok(_)))), "the GOAWAY never arrived" ); - assert_eq!( - connection.status().now_or_never().transpose().unwrap(), - None, - "the loop left the session" - ); + assert!(connection.connected(), "the loop left the session"); assert!(accepted.try_recv().is_err(), "redialed while the session served"); outlast_fast().await; session.abort(moq_net::Error::GoawayTimeout); - let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); - assert_eq!(status.unwrap(), Status::Disconnected); - let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); - assert_eq!(status.unwrap(), Status::Connected); + kio::clock::timeout(WAIT, reaches(&connection, disconnected)) + .await + .unwrap() + .unwrap(); + kio::clock::timeout(WAIT, reaches(&connection, connected)) + .await + .unwrap() + .unwrap(); kio::clock::timeout(WAIT, accepted.recv()) .await .expect("never redialed after the close") @@ -3210,7 +3180,7 @@ mod tests { let (accepted, mut sessions) = tokio::sync::mpsc::unbounded_channel(); let client = fallback_client(crate::origin::spawn(), blocked, accepted); let url = url("https://fallback-ends.test/"); - let mut connection = kio::clock::timeout(WAIT, client.connect(url.clone()).established()) + let connection = kio::clock::timeout(WAIT, client.connect(url.clone()).established()) .await .unwrap() .unwrap(); @@ -3220,10 +3190,10 @@ mod tests { // Past the default healthy bar, so the end redials rather than ending the loop. kio::clock::sleep(Duration::from_secs(1)).await; server.abort(moq_net::Error::Cancel); - let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); - assert_eq!(status.unwrap(), Status::Connected); - let status = kio::clock::timeout(WAIT, connection.status()).await.unwrap(); - assert_eq!(status.unwrap(), Status::Disconnected); + kio::clock::timeout(WAIT, reaches(&connection, disconnected)) + .await + .unwrap() + .unwrap(); assert!(!crate::websocket::won(&url), "the redial would skip QUIC's head start"); } diff --git a/rs/moq-tokio/src/lib.rs b/rs/moq-tokio/src/lib.rs index 7d2543a584d..77595c50e13 100644 --- a/rs/moq-tokio/src/lib.rs +++ b/rs/moq-tokio/src/lib.rs @@ -83,7 +83,7 @@ fn spawn_qmux( // new `pub` item in these modules doesn't silently join it. pub use client::Client; pub use connect::{Addrs, ConnectError}; -pub use connection::{Backoff, Connection, Redirect, Restart, Status}; +pub use connection::{Backoff, Connection, Redirect, Restart}; pub use error::{Error, Result}; pub use log::{Log, RedactedUrl}; pub use server::{Listener, Server}; diff --git a/rs/moq-tokio/src/listen.rs b/rs/moq-tokio/src/listen.rs index bf054aae12d..b4839c6d9d0 100644 --- a/rs/moq-tokio/src/listen.rs +++ b/rs/moq-tokio/src/listen.rs @@ -879,7 +879,7 @@ peers = "peers.toml" }; let server = config.init_streams().unwrap(); - assert!(matches!(server.local_addr(), Err(crate::Error::NoBackend(_)))); + assert!(server.local_addr().is_none()); } /// A stream-only server refuses each setting only QUIC reads rather than @@ -950,7 +950,7 @@ peers = "peers.toml" config.tls.generate = vec!["localhost".to_string()]; let server = config.init(Default::default()).unwrap(); - assert!(server.local_addr().is_ok()); + assert!(server.local_addr().is_some()); } /// The handshake deadline defaults on, from the parser and in code alike, and diff --git a/rs/moq-tokio/src/quic/web/send.rs b/rs/moq-tokio/src/quic/web/send.rs index f76a809465f..3951a1fa214 100644 --- a/rs/moq-tokio/src/quic/web/send.rs +++ b/rs/moq-tokio/src/quic/web/send.rs @@ -344,7 +344,7 @@ impl moq_net::transport::poll::SendStream for Stream { &self, waiter: &kio::Waiter, offset: &send::Offset, - ) -> Poll> { + ) -> Poll> { let acked = match &self.state { State::Open(stream) => stream.poll_acked(waiter, *offset), State::Finished(stream) => stream.poll_acked(waiter, *offset), @@ -354,7 +354,7 @@ impl moq_net::transport::poll::SendStream for Stream { }, }; match std::task::ready!(acked) { - Ok(()) => Poll::Ready(Ok(moq_net::transport::poll::Acked::Delivered)), + Ok(()) => Poll::Ready(Ok(())), Err(err) => poll_error(&self.close, waiter, err).map(Err), } } diff --git a/rs/moq-tokio/src/quic/web/session.rs b/rs/moq-tokio/src/quic/web/session.rs index 60b01f9afd9..82ed1356144 100644 --- a/rs/moq-tokio/src/quic/web/session.rs +++ b/rs/moq-tokio/src/quic/web/session.rs @@ -1301,7 +1301,7 @@ mod tests { /// fail. #[tokio::test] async fn an_offset_stays_acknowledged_through_a_reset() { - use moq_net::transport::poll::{Acked, SendStream}; + use moq_net::transport::poll::SendStream; for (framed, finish) in [false, true] .into_iter() @@ -1322,7 +1322,7 @@ mod tests { }; let (acked, (recv, read)) = tokio::join!(kio::wait(|waiter| send.poll_acked(waiter, &payload)), recv); assert_eq!(read, b"payload", "framed: {framed}"); - assert!(matches!(acked, Ok(Acked::Delivered)), "framed: {framed}: {acked:?}"); + assert!(matches!(acked, Ok(())), "framed: {framed}: {acked:?}"); // The driver runs on this thread, so nothing acknowledges this before the reset. let cut = match finish { @@ -1347,7 +1347,7 @@ mod tests { SendStream::reset(&mut send, 1); let acked = |offset| SendStream::poll_acked(&send, &Waiter::noop(), offset); assert!( - matches!(acked(&payload), Poll::Ready(Ok(Acked::Delivered))), + matches!(acked(&payload), Poll::Ready(Ok(()))), "framed: {framed}, finished: {finish}: the reset forgot it" ); assert_eq!(SendStream::offset(&send), end, "framed: {framed}, finished: {finish}"); @@ -1364,7 +1364,7 @@ mod tests { /// acknowledged: the stop fails only the bytes it had not. #[tokio::test] async fn an_offset_stays_acknowledged_through_a_stop() { - use moq_net::transport::poll::{Acked, SendStream}; + use moq_net::transport::poll::SendStream; for framed in [false, true] { let (client, server, _endpoints) = pair().await; @@ -1381,7 +1381,7 @@ mod tests { recv }; let (acked, recv) = tokio::join!(kio::wait(|waiter| send.poll_acked(waiter, &payload)), recv); - assert!(matches!(acked, Ok(Acked::Delivered)), "framed: {framed}: {acked:?}"); + assert!(matches!(acked, Ok(())), "framed: {framed}: {acked:?}"); recv.stop(3); let stopped = kio::wait(|waiter| SendStream::poll_closed(&send, waiter)).await; @@ -1391,7 +1391,7 @@ mod tests { ); let acked = SendStream::poll_acked(&send, &Waiter::noop(), &payload); assert!( - matches!(acked, Poll::Ready(Ok(Acked::Delivered))), + matches!(acked, Poll::Ready(Ok(()))), "framed: {framed}: the stop forgot it: {acked:?}" ); } diff --git a/rs/moq-tokio/src/server.rs b/rs/moq-tokio/src/server.rs index 21100561e9b..5c185a8b42f 100644 --- a/rs/moq-tokio/src/server.rs +++ b/rs/moq-tokio/src/server.rs @@ -464,7 +464,7 @@ impl Server { /// would accept and handshake sessions that carry nothing. async fn serve(self) -> crate::Result<()> { let mut listener = self.listen().await?; - if let Ok(addr) = listener.local_addr() { + if let Some(addr) = listener.local_addr() { tracing::info!(%addr, "listening"); } loop { @@ -585,7 +585,7 @@ impl Server { self.streams.serve(&server, &self.admission); loop { // The QUIC endpoint address, reported as a QUIC session's local side. - let local = self.local_addr().ok(); + let local = self.local_addr(); let quic_tls = self.quic.as_ref().map(|quic| quic.tls.clone()); // tokio::select! does not support cfg directives on arms, so we need to create the futures here. @@ -697,16 +697,9 @@ impl Server { } /// The address the QUIC listener bound to, useful when the config asked for - /// port 0. - /// - /// Errors with [`Error::NoBackend`] on a stream-only server, which has no - /// QUIC listener. - pub fn local_addr(&self) -> crate::Result { - if let Some(quic) = self.quic.as_ref() { - return Ok(quic.local_addr()); - } - // No QUIC backend (e.g. a stream-only `--listen-tcp-bind`). - Err(Error::NoBackend("no QUIC listener configured")) + /// port 0, or `None` on a stream-only server, which has no QUIC listener. + pub fn local_addr(&self) -> Option { + self.quic.as_ref().map(crate::quic::Server::local_addr) } /// Closes the QUIC connections once this server has been handed away. @@ -786,11 +779,8 @@ impl Listener { } /// The address the QUIC listener bound to, useful when the config asked for - /// port 0. - /// - /// Errors with [`Error::NoBackend`] on a stream-only server, which has no - /// QUIC listener. - pub fn local_addr(&self) -> crate::Result { + /// port 0, or `None` on a stream-only server, which has no QUIC listener. + pub fn local_addr(&self) -> Option { self.server.local_addr() } diff --git a/rs/moq-tokio/src/worker/group.rs b/rs/moq-tokio/src/worker/group.rs index 4b9a0fea430..35e21210d51 100644 --- a/rs/moq-tokio/src/worker/group.rs +++ b/rs/moq-tokio/src/worker/group.rs @@ -789,7 +789,12 @@ fn run( let built = { let _guard = runtime.enter(); Server::build(server, crate::server::Parts::Member(member)) - .and_then(|server| server.local_addr().map(|addr| (server, addr))) + .and_then(|server| { + let addr = server + .local_addr() + .ok_or(crate::Error::NoBackend("no QUIC listener configured"))?; + Ok((server, addr)) + }) }; let (server, addr) = match built { diff --git a/rs/moq-tokio/tests/integration/backend.rs b/rs/moq-tokio/tests/integration/backend.rs index 36e0677de17..b9e4b3739df 100644 --- a/rs/moq-tokio/tests/integration/backend.rs +++ b/rs/moq-tokio/tests/integration/backend.rs @@ -786,7 +786,7 @@ async fn quic_client_close_drains_migrated_predecessor() { .init(quic) .expect("failed to init client") .with_publisher(origin.consume()); - let mut connection = client.connect(url).established().await.expect("client connect failed"); + let connection = client.connect(url).established().await.expect("client connect failed"); while track.subscription().is_none() { track.subscription_changed().await.expect("track closed"); @@ -794,8 +794,10 @@ async fn quic_client_close_drains_migrated_predecessor() { subscribed_tx.send(()).unwrap(); // Once the replacement is live, only the predecessor serves the subscription. - while connection.connects() < 2 || !connection.connected() { - connection.status().await.expect("connection stopped"); + let monitor = connection.monitor(); + let mut seen = monitor.state(); + while seen.connects < 2 || !matches!(seen.phase, moq_tokio::connection::Phase::Connected { .. }) { + seen = monitor.state_changed(seen.revision).await.expect("connection stopped"); } migrated_tx.send(()).unwrap(); @@ -932,7 +934,7 @@ async fn quic_client_close_keeps_predecessor_handover() { .init(quic) .expect("failed to init client") .with_publisher(origin.consume()); - let mut connection = client.connect(url).established().await.expect("client connect failed"); + let connection = client.connect(url).established().await.expect("client connect failed"); while track.subscription().is_none() { track.subscription_changed().await.expect("track closed"); @@ -940,7 +942,11 @@ async fn quic_client_close_keeps_predecessor_handover() { subscribed_tx.send(()).unwrap(); // Close while the old session is still inside its handover window. - while connection.status().await.expect("connection stopped") != moq_tokio::Status::Migrating {} + let monitor = connection.monitor(); + let mut seen = monitor.state(); + while !matches!(seen.phase, moq_tokio::connection::Phase::Migrating { .. }) { + seen = monitor.state_changed(seen.revision).await.expect("connection stopped"); + } let start = kio::clock::now(); let err = connection.close().await.expect_err("the predecessor cannot drain"); let elapsed = start.elapsed(); diff --git a/rs/moq-tokio/tests/integration/broadcast.rs b/rs/moq-tokio/tests/integration/broadcast.rs index 3a7be1066d8..3c5c135fea3 100644 --- a/rs/moq-tokio/tests/integration/broadcast.rs +++ b/rs/moq-tokio/tests/integration/broadcast.rs @@ -3548,9 +3548,11 @@ async fn reconnect_retries_a_rejection_after_a_healthy_session() { let mut config = moq_tokio::connect::Config::default(); config.tls.insecure = Some(true); config.backoff.healthy = Some(HEALTHY.into()); - let mut connection = config.init(Default::default()).unwrap().connect(url); - let status = kio::clock::timeout(TIMEOUT, connection.status()).await.unwrap(); - assert_eq!(status.unwrap(), moq_tokio::Status::Connected); + let connection = config.init(Default::default()).unwrap().connect(url); + let connection = kio::clock::timeout(TIMEOUT, connection.established()) + .await + .unwrap() + .unwrap(); kio::clock::timeout(TIMEOUT, accepts.recv()).await.unwrap().unwrap(); kio::clock::sleep(HEALTHY).await; end_first.send(()).unwrap(); diff --git a/rs/moq-tokio/tests/integration/max_age.rs b/rs/moq-tokio/tests/integration/max_age.rs index 450fa2e4b3f..645c6cc59fb 100644 --- a/rs/moq-tokio/tests/integration/max_age.rs +++ b/rs/moq-tokio/tests/integration/max_age.rs @@ -45,8 +45,9 @@ async fn relay(version: moq_net::Version, javascript: Option) -> anyhow::R broadcast .broadcast() .create_track(i.to_string(), moq_net::track::Info::default().with_max_age(age)) + .expect("a free name") }) - .collect::>()?; + .collect(); broadcast.announce()?; let subscriber = moq_tokio::origin::spawn(); let consumer = subscriber.consume(); diff --git a/rs/moq-tokio/tests/integration/reconnect.rs b/rs/moq-tokio/tests/integration/reconnect.rs index e7d36b6f1d5..263ede36bb1 100644 --- a/rs/moq-tokio/tests/integration/reconnect.rs +++ b/rs/moq-tokio/tests/integration/reconnect.rs @@ -88,13 +88,12 @@ async fn the_connect_count_advances_on_reconnect() { kio::clock::host_time(); // real TCP sockets let (port, mut sessions, _task) = spawn_server().await; let url: url::Url = format!("tcp://localhost:{port}/").parse().expect("parse url"); - let mut connection = quick_client(Default::default()).connect(url); + let connection = quick_client(Default::default()).connect(url); - let status = kio::clock::timeout(Duration::from_secs(10), connection.status()) + let connection = kio::clock::timeout(Duration::from_secs(10), connection.established()) .await - .expect("status timed out") - .expect("status failed"); - assert_eq!(status, moq_tokio::Status::Connected); + .expect("connect timed out") + .expect("connect failed"); assert_eq!(connection.connects(), 1, "the first connect counts 1"); // Dropping the server's handle closes the session once it was healthy, so the loop redials. @@ -180,12 +179,12 @@ fn quick_client(redirect: moq_tokio::Redirect) -> moq_tokio::Client { async fn a_protocol_violation_reconnects() { kio::clock::host_time(); // real TCP sockets let (port, mut sessions, task) = spawn_server().await; - let mut connection = + let connection = quick_client(Default::default()).connect(format!("tcp://127.0.0.1:{port}/").parse::().unwrap()); - let status = kio::clock::timeout(Duration::from_secs(10), connection.status()) + let connection = kio::clock::timeout(Duration::from_secs(10), connection.established()) .await + .unwrap() .unwrap(); - assert_eq!(status.unwrap(), moq_tokio::Status::Connected); let first = sessions.recv().await.unwrap(); kio::clock::sleep(HEALTHY).await; first.abort(moq_net::Error::ProtocolViolation); diff --git a/rs/moq-tokio/tests/integration/relay_fill.rs b/rs/moq-tokio/tests/integration/relay_fill.rs index b0108fd1b97..7c1c91e2ff3 100644 --- a/rs/moq-tokio/tests/integration/relay_fill.rs +++ b/rs/moq-tokio/tests/integration/relay_fill.rs @@ -162,7 +162,8 @@ async fn relay(version: Version) -> anyhow::Result<()> { let track = broadcast.broadcast().create_track( "video", Info::default().with_timescale(Timescale::MILLI).with_max_age(None), - )?; + ) + .expect("a free name"); for sequence in 0..GROUPS { let mut group = track.create_group(moq_net::group::Info { start: sequence })?; group.write_frame( diff --git a/rs/moq-transcode/src/lib.rs b/rs/moq-transcode/src/lib.rs index 391d08f6bc1..e6e5def7e15 100644 --- a/rs/moq-transcode/src/lib.rs +++ b/rs/moq-transcode/src/lib.rs @@ -949,7 +949,7 @@ mod tests { .await .map(groups) .expect("the source track closed"); - let mut group = request.accept(7, None).unwrap(); + let mut group = request.accept(7, None).unwrap().expect("a fresh group"); write_keyframe(&mut group); group.finish().unwrap(); @@ -1013,7 +1013,7 @@ mod tests { tokio::spawn(async move { while let Ok(request) = source_fetches.requested_fill().await.map(groups) { - let mut group = request.accept(request.start().group, None).unwrap(); + let mut group = request.accept(request.start().group, None).unwrap().expect("a fresh group"); write_keyframe(&mut group); group.finish().unwrap(); } @@ -1661,7 +1661,7 @@ mod tests { // Release the fetch: it opens its decoder and only now claims output group // 7, which retirement had to leave writable. - let mut group = request.accept(7, None).unwrap(); + let mut group = request.accept(7, None).unwrap().expect("a fresh group"); write_keyframe(&mut group); group.finish().unwrap(); @@ -1747,7 +1747,8 @@ mod tests { let mut group = fresh .accept(7, None) - .expect("the fresh request lost to the abandoned encode"); + .expect("the fresh request lost to the abandoned encode") + .expect("a fresh group"); write_keyframe(&mut group); group.finish().unwrap(); diff --git a/rs/moq-transcode/src/rung.rs b/rs/moq-transcode/src/rung.rs index 0bb63b4445c..f9f519d8098 100644 --- a/rs/moq-transcode/src/rung.rs +++ b/rs/moq-transcode/src/rung.rs @@ -773,9 +773,9 @@ async fn fetch(rung: &Rung, fill: &moq_net::track::FillGroups, sequence: u64, li return abandon(sequence); } - let output = match fill.accept(sequence, None) { - Ok(output) => output, - Err(err) => return Err(err.into()), + // Already written, as by the live path: nothing left to serve. + let Some(output) = fill.accept(sequence, None)? else { + return Ok(()); }; // A fetch builds its own pipeline, so it is billable work even when the // live path is idle. Reference counted, so overlapping the live session @@ -1230,7 +1230,7 @@ mod tests { panic!("a time lookup"); }; assert_eq!(lookup.time(), 7); - lookup.accept(6, None).unwrap().finish().unwrap(); + lookup.accept(6, None).unwrap().expect("a fresh group").finish().unwrap(); while let Poll::Ready(Ok(Some(_))) = reader.poll_recv_group(&waiter) {} let fill = fills.requested_fill().await.map(groups).unwrap(); assert_eq!((fill.start().group, fill.end()), (7, 10)); @@ -1373,7 +1373,7 @@ mod tests { panic!("a time lookup"); }; assert_eq!(lookup.time(), 1); - lookup.accept(0, None).unwrap().finish().unwrap(); + lookup.accept(0, None).unwrap().expect("a fresh group").finish().unwrap(); while let Poll::Ready(Ok(Some(_))) = reader.poll_recv_group(&waiter) {} let fill = fills.requested_fill().await.map(groups).unwrap(); assert_eq!((fill.start().group, fill.end()), (1, HOUR)); @@ -1441,13 +1441,13 @@ mod tests { panic!("a time lookup"); }; assert_eq!(lookup.time(), 7); - lookup.accept(6, None).unwrap().finish().unwrap(); + lookup.accept(6, None).unwrap().expect("a fresh group").finish().unwrap(); while let Poll::Ready(Ok(Some(_))) = reader.poll_recv_group(&waiter) {} let fill = fills.requested_fill().await.map(groups).unwrap(); assert_eq!((fill.start().group, fill.end()), (7, 10)); // Group 7 is served, and the reader never reads again to pick it up. - fill.clone().accept(7, None).unwrap().finish().unwrap(); + fill.clone().accept(7, None).unwrap().expect("a fresh group").finish().unwrap(); let mut tasks = tokio::task::JoinSet::new(); spawn_fill(&mut tasks, rung, fill, Arc::new(Semaphore::new(1))); let wait = std::time::Duration::from_secs(5); diff --git a/rs/moq-uring/src/quic/web/send.rs b/rs/moq-uring/src/quic/web/send.rs index 4b4c5ca9d9c..c3b6f5bb862 100644 --- a/rs/moq-uring/src/quic/web/send.rs +++ b/rs/moq-uring/src/quic/web/send.rs @@ -313,7 +313,7 @@ impl moq_net::transport::poll::SendStream for Stream { &self, waiter: &kio::Waiter, offset: &send::Offset, - ) -> Poll> { + ) -> Poll> { let acked = match &self.state { State::Open(stream) => stream.poll_acked(waiter, *offset), State::Finished(stream) => stream.poll_acked(waiter, *offset), @@ -323,7 +323,7 @@ impl moq_net::transport::poll::SendStream for Stream { }, }; match std::task::ready!(acked) { - Ok(()) => Poll::Ready(Ok(moq_net::transport::poll::Acked::Delivered)), + Ok(()) => Poll::Ready(Ok(())), Err(err) => poll_error(&self.close, waiter, err).map(Err), } } diff --git a/rs/moq-uring/src/transport/local.rs b/rs/moq-uring/src/transport/local.rs index a970affdc72..04395615f8d 100644 --- a/rs/moq-uring/src/transport/local.rs +++ b/rs/moq-uring/src/transport/local.rs @@ -128,7 +128,7 @@ impl poll::SendStream for Local { self.0.offset() } - fn poll_acked(&self, waiter: &kio::Waiter, offset: &Self::Offset) -> Poll> { + fn poll_acked(&self, waiter: &kio::Waiter, offset: &Self::Offset) -> Poll> { self.0.poll_acked(waiter, offset) } diff --git a/rs/moq-uring/tests/integration/web.rs b/rs/moq-uring/tests/integration/web.rs index 489f066e988..41112c4040d 100644 --- a/rs/moq-uring/tests/integration/web.rs +++ b/rs/moq-uring/tests/integration/web.rs @@ -289,7 +289,7 @@ fn a_clean_finish_closes_a_stream() { /// acknowledgment fail. #[test] fn an_offset_stays_acknowledged_through_a_reset() { - use moq_net::transport::poll::{Acked, SendStream}; + use moq_net::transport::poll::SendStream; let Some(mut worker) = worker() else { return }; let handle = worker.handle(); @@ -327,7 +327,7 @@ fn an_offset_stays_acknowledged_through_a_reset() { kio::wait(|waiter| send.poll_acked(waiter, &payload)), ) .await; - assert!(matches!(acked, Ok(Acked::Delivered)), "{acked:?}"); + assert!(matches!(acked, Ok(())), "{acked:?}"); // The connection is driven on this thread, so nothing acknowledges this before the reset. let written = SendStream::poll_write(&mut send, &kio::Waiter::noop(), b"more"); @@ -336,7 +336,7 @@ fn an_offset_stays_acknowledged_through_a_reset() { SendStream::reset(&mut send, 1); let acked = |offset| SendStream::poll_acked(&send, &kio::Waiter::noop(), offset); assert!( - matches!(acked(&payload), Poll::Ready(Ok(Acked::Delivered))), + matches!(acked(&payload), Poll::Ready(Ok(()))), "the reset forgot it" ); assert!(matches!(acked(&cut), Poll::Ready(Err(_))), "the reset cut it"); diff --git a/rs/moq-video/src/decode/consumer.rs b/rs/moq-video/src/decode/consumer.rs index 015dc47c15d..131e15d661b 100644 --- a/rs/moq-video/src/decode/consumer.rs +++ b/rs/moq-video/src/decode/consumer.rs @@ -503,8 +503,7 @@ mod tests { let rendition = config.probe().await.unwrap(); let reserved = source_catalog.reserve().with_interval(config.effective_join()); let track = source_broadcast - .unique_track(".avc3", reserved.track_info(hang::catalog::PRIORITY.video)) - .unwrap(); + .unique_track(".avc3", reserved.track_info(hang::catalog::PRIORITY.video)); let mut producer = EncodePublisher::new(track, reserved, rendition).unwrap(); let mut encoder = Encoder::new(&config).unwrap(); let rgba = vec![0x80u8; 320 * 240 * 4]; diff --git a/rs/moq-video/src/encode/capture.rs b/rs/moq-video/src/encode/capture.rs index a518a3e944a..a59c5a05ff1 100644 --- a/rs/moq-video/src/encode/capture.rs +++ b/rs/moq-video/src/encode/capture.rs @@ -416,7 +416,7 @@ fn capture_track( let ratio = super::backend::always_cuts(options.codec, &options.kind).then_some(REFRESH); let refresh = moq_net::track::Refresh::default().with_ratio(ratio); let info = catalog.track_info(hang::catalog::PRIORITY.video).with_refresh(refresh); - Ok(broadcast.unique_track(suffix(options.codec), info)?) + Ok(broadcast.unique_track(suffix(options.codec), info)) } /// Off macOS and iOS, [`Driver::run`]'s future must stay `Send` so a server can diff --git a/rs/moq-video/src/encode/producer.rs b/rs/moq-video/src/encode/producer.rs index 2d9de6e83a7..14246a3a0f2 100644 --- a/rs/moq-video/src/encode/producer.rs +++ b/rs/moq-video/src/encode/producer.rs @@ -187,8 +187,8 @@ impl Producer { .map_or(hang::catalog::PRIORITY.video, |lower| lower.priority.saturating_sub(1)); let info = catalog.track_info(priority); let track = match track { - Some(name) => broadcast.create_track(name, info)?, - None => broadcast.unique_track(suffix(config.codec), info)?, + Some(name) => broadcast.create_track(name, info).ok_or(moq_net::Error::Duplicate)?, + None => broadcast.unique_track(suffix(config.codec), info), }; let mut producer = Self::with_track(track, &catalog, config, rendition, bandwidth, lower)?; producer.encoding = Encoding::Open(sink); diff --git a/rs/moq-video/src/encode/publisher.rs b/rs/moq-video/src/encode/publisher.rs index 985c39e22fa..c42bec84fd1 100644 --- a/rs/moq-video/src/encode/publisher.rs +++ b/rs/moq-video/src/encode/publisher.rs @@ -456,8 +456,7 @@ mod tests { selected.preference = -1; let track = broadcast - .unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)) - .unwrap(); + .unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)); let _producer = Publisher::new(track, catalog.reserve(), selected).unwrap(); let (_, published) = rendition(&catalog).expect("the rendition publishes before any frame"); @@ -659,8 +658,7 @@ mod finished { let finished: Vec<_> = (0..sources) .map(|_| { let track = broadcast - .unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)) - .unwrap(); + .unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)); let mut producer = Publisher::new(track, catalog.reserve(), rendition.clone()).unwrap(); for pts in [0, 33_333] { let pts = moq_net::Timestamp::from_micros(pts).unwrap(); diff --git a/rs/moq-webrtc/src/codec/av1.rs b/rs/moq-webrtc/src/codec/av1.rs index aa90aa4e369..0c9c0c17c1e 100644 --- a/rs/moq-webrtc/src/codec/av1.rs +++ b/rs/moq-webrtc/src/codec/av1.rs @@ -15,7 +15,7 @@ pub struct Bridge { impl Bridge { /// Publish an `.av1` track on `broadcast`, adding the catalog rendition once config is known. pub fn new(broadcast: moq_net::broadcast::Producer, catalog: moq_mux::catalog::Producer) -> Result { - let track = broadcast.unique_track(".av1", catalog.track_info(hang::catalog::PRIORITY.video))?; + let track = broadcast.unique_track(".av1", catalog.track_info(hang::catalog::PRIORITY.video)); let import = moq_mux::codec::av1::Import::new(track, catalog.reserve(), Default::default())?; let split = moq_mux::codec::av1::Split::new(); Ok(Self { split, import }) diff --git a/rs/moq-webrtc/src/codec/h264.rs b/rs/moq-webrtc/src/codec/h264.rs index 5c660ee3e6f..5121f6a3ae3 100644 --- a/rs/moq-webrtc/src/codec/h264.rs +++ b/rs/moq-webrtc/src/codec/h264.rs @@ -14,7 +14,7 @@ pub struct Bridge { impl Bridge { pub fn new(broadcast: moq_net::broadcast::Producer, catalog: moq_mux::catalog::Producer) -> Result { - let track = broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video))?; + let track = broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)); let import = moq_mux::codec::h264::Import::new(track, catalog.reserve(), Default::default())?; let split = moq_mux::codec::h264::Split::new(); Ok(Self { split, import }) diff --git a/rs/moq-webrtc/src/codec/h265.rs b/rs/moq-webrtc/src/codec/h265.rs index 2dd84798786..cfe61af2799 100644 --- a/rs/moq-webrtc/src/codec/h265.rs +++ b/rs/moq-webrtc/src/codec/h265.rs @@ -16,7 +16,7 @@ pub struct Bridge { impl Bridge { /// Publish a `.hev1` track on `broadcast`, adding the catalog rendition once config is known. pub fn new(broadcast: moq_net::broadcast::Producer, catalog: moq_mux::catalog::Producer) -> Result { - let track = broadcast.unique_track(".hev1", catalog.track_info(hang::catalog::PRIORITY.video))?; + let track = broadcast.unique_track(".hev1", catalog.track_info(hang::catalog::PRIORITY.video)); let import = moq_mux::codec::h265::Import::new(track, catalog.reserve(), Default::default())?; let split = moq_mux::codec::h265::Split::new(); Ok(Self { split, import }) diff --git a/rs/moq-webrtc/src/codec/mod.rs b/rs/moq-webrtc/src/codec/mod.rs index d64f6196d28..47f5ef11f38 100644 --- a/rs/moq-webrtc/src/codec/mod.rs +++ b/rs/moq-webrtc/src/codec/mod.rs @@ -148,7 +148,7 @@ impl DeferredVideo { catalog: moq_mux::catalog::Producer, suffix: &str, ) -> Result { - let track = broadcast.unique_track(suffix, catalog.track_info(hang::catalog::PRIORITY.video))?; + let track = broadcast.unique_track(suffix, catalog.track_info(hang::catalog::PRIORITY.video)); Ok(Self { state: DeferredState::Pending(Box::new(PendingVideo { track, catalog })), }) diff --git a/rs/moq-webrtc/src/codec/opus.rs b/rs/moq-webrtc/src/codec/opus.rs index d119fcf0301..cec7bac368d 100644 --- a/rs/moq-webrtc/src/codec/opus.rs +++ b/rs/moq-webrtc/src/codec/opus.rs @@ -17,7 +17,7 @@ impl Bridge { channel_count: u32, ) -> Result { let config = moq_mux::codec::opus::Config::new(sample_rate, channel_count); - let track = broadcast.unique_track(".opus", catalog.track_info(hang::catalog::PRIORITY.audio))?; + let track = broadcast.unique_track(".opus", catalog.track_info(hang::catalog::PRIORITY.audio)); let import = moq_mux::codec::opus::Import::new(track, catalog.reserve(), config.into())?; Ok(Self { import }) } diff --git a/rs/qmux/src/session.rs b/rs/qmux/src/session.rs index f1fca37d4fc..90bd14abced 100644 --- a/rs/qmux/src/session.rs +++ b/rs/qmux/src/session.rs @@ -523,16 +523,16 @@ impl poll::SendStream for SendStream { self.inner.lock().conn.send_stream(self.id).offset() } - /// [`Acked::Sent`](poll::Acked::Sent) once the transport took the bytes, which is not the - /// peer acknowledging them. A reset or stop keeps the prefix that went out before it. - fn poll_acked(&self, waiter: &kio::Waiter, offset: &send::Offset) -> Poll> { + /// Ready once the transport took the bytes, which TCP then delivers unless the link fails. + /// A reset or stop keeps the prefix that went out before it. + fn poll_acked(&self, waiter: &kio::Waiter, offset: &send::Offset) -> Poll> { let mut state = self.inner.lock(); let mut stream = state.conn.send_stream(self.id); if u64::from(*offset) <= stream.acked_len() { - return Poll::Ready(Ok(poll::Acked::Sent)); + return Poll::Ready(Ok(())); } match ready!(stream.poll_acked(waiter, *offset)) { - Ok(()) => Poll::Ready(Ok(poll::Acked::Sent)), + Ok(()) => Poll::Ready(Ok(())), Err(send::Error::ConnectionLost) => Poll::Ready(Err(state.lost())), Err(_) => Poll::Ready(Err(Error::StreamClosed)), } diff --git a/rs/qmux/src/session/tests.rs b/rs/qmux/src/session/tests.rs index ce8ef9d32ef..c712d619f16 100644 --- a/rs/qmux/src/session/tests.rs +++ b/rs/qmux/src/session/tests.rs @@ -178,7 +178,7 @@ async fn read_exact(recv: &mut RecvStream, want: usize) -> Result } /// What `send` answers about the bytes below `offset`, without waiting. -fn acked(send: &SendStream, offset: &moq_quic::send::Offset) -> Poll> { +fn acked(send: &SendStream, offset: &moq_quic::send::Offset) -> Poll> { send.poll_acked(&kio::Waiter::noop(), offset) } @@ -198,7 +198,7 @@ async fn bytes_count_as_sent_once_the_link_takes_them() { assert_eq!(read_exact(&mut recv, first.len()).await.unwrap(), first, "{version:?}"); let went_out = send.offset(); assert!( - matches!(acked(&send, &went_out), Poll::Ready(Ok(poll::Acked::Sent))), + matches!(acked(&send, &went_out), Poll::Ready(Ok(()))), "{version:?}: the link took it" ); @@ -210,7 +210,7 @@ async fn bytes_count_as_sent_once_the_link_takes_them() { send.reset(1); assert!( - matches!(acked(&send, &went_out), Poll::Ready(Ok(poll::Acked::Sent))), + matches!(acked(&send, &went_out), Poll::Ready(Ok(()))), "{version:?}: what went out stays sent" ); assert!( diff --git a/test/interop/clients/rust/catalog.rs b/test/interop/clients/rust/catalog.rs index fd5cdb8cb78..02db823d93e 100644 --- a/test/interop/clients/rust/catalog.rs +++ b/test/interop/clients/rust/catalog.rs @@ -34,7 +34,7 @@ async fn main() -> anyhow::Result<()> { let route = origin.route(&args[2], moq_net::origin::RouteOptions::hidden())?; let track = route .broadcast() - .create_track(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info())?; + .create_track(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info()).context("the track already exists")?; ensure!( track.info().compression == moq_net::track::Compression::Deflate, "hang catalogs are compressed" diff --git a/test/interop/clients/rust/control.rs b/test/interop/clients/rust/control.rs index e6642607e36..d1f20586d4a 100644 --- a/test/interop/clients/rust/control.rs +++ b/test/interop/clients/rust/control.rs @@ -13,7 +13,7 @@ async fn main() -> anyhow::Result<()> { let route = origin.route("control", moq_net::origin::RouteOptions::hidden())?; let track = route .broadcast() - .create_track("video", moq_net::track::Info::default().with_priority(2))?; + .create_track("video", moq_net::track::Info::default().with_priority(2)).context("the track already exists")?; let mut group = track.create_group(moq_net::group::Info { start: 4 })?; for byte in [1, 2] { group.write_frame(moq_net::Timestamp::unscaled(group.start), vec![byte])?; diff --git a/test/interop/clients/rust/finish.rs b/test/interop/clients/rust/finish.rs index 57aa0f0f6f1..49669345ae1 100644 --- a/test/interop/clients/rust/finish.rs +++ b/test/interop/clients/rust/finish.rs @@ -79,7 +79,7 @@ async fn main() -> anyhow::Result<()> { let route = origin.route(&args.broadcast, moq_net::origin::RouteOptions::hidden())?; let mut catalog = moq_mux::catalog::Producer::<()>::new(&mut route.broadcast().clone(), Default::default())?; let mut stream = moq_mux::import::TrackStream::video( - route.broadcast().reserve_track("video")?, + route.broadcast().reserve_track("video").context("the track already exists")?, catalog.reserve(), moq_mux::import::VideoInit::new(moq_mux::import::VideoFormat::Avc3, Vec::new()), )?; @@ -100,7 +100,7 @@ async fn main() -> anyhow::Result<()> { )?; let track = health .broadcast() - .create_track("live", moq_net::track::Info::default())?; + .create_track("live", moq_net::track::Info::default()).context("the track already exists")?; let start = moq_net::Timestamp::unscaled(0); let mut group = track.append_group(start)?; group.write_frame(start, b"session-alive".to_vec())?; diff --git a/test/interop/clients/rust/goaway.rs b/test/interop/clients/rust/goaway.rs index 64a2d41b328..88d449f37cc 100644 --- a/test/interop/clients/rust/goaway.rs +++ b/test/interop/clients/rust/goaway.rs @@ -35,7 +35,7 @@ async fn main() -> anyhow::Result<()> { let route = origin.route("handover", moq_net::origin::RouteOptions::default())?; let mut track = route .broadcast() - .create_track("video", moq_net::track::Info::default())?; + .create_track("video", moq_net::track::Info::default()).context("the track already exists")?; let (mut first, first_url) = endpoint(&origin, version).await?; let (mut second, second_url) = endpoint(&origin, version).await?; let script = concat!( diff --git a/test/interop/clients/rust/hls.rs b/test/interop/clients/rust/hls.rs index 80e3fe17a8e..2cc8acf3104 100644 --- a/test/interop/clients/rust/hls.rs +++ b/test/interop/clients/rust/hls.rs @@ -75,11 +75,11 @@ async fn main() -> anyhow::Result<()> { let route = origin.route(path, moq_net::origin::RouteOptions::hidden())?; let mut broadcast = route.broadcast().clone(); let mut catalog = moq_mux::catalog::Producer::<()>::new(&mut broadcast, Default::default())?; - let track = broadcast.create_track("video", catalog.track_info(hang::catalog::PRIORITY.video))?; + let track = broadcast.create_track("video", catalog.track_info(hang::catalog::PRIORITY.video)).context("the track already exists")?; let config = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8); // Each producer owns its catalog entry, so both stay alive until the reader is done. let video_track = write(catalog.video(track, Container::Legacy(Kind::Video), config)?, video())?; - let track = broadcast.create_track("audio", catalog.track_info(hang::catalog::PRIORITY.audio))?; + let track = broadcast.create_track("audio", catalog.track_info(hang::catalog::PRIORITY.audio)).context("the track already exists")?; let config = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2); let audio_track = write(catalog.audio(track, Container::Legacy(Kind::Audio), config)?, audio())?; catalog.finish()?; diff --git a/test/interop/clients/rust/tail.rs b/test/interop/clients/rust/tail.rs index ad7b33d6228..5861ef4efaa 100644 --- a/test/interop/clients/rust/tail.rs +++ b/test/interop/clients/rust/tail.rs @@ -118,7 +118,7 @@ async fn main() -> anyhow::Result<()> { if datagram { // Untimed: the OBJECT_DATAGRAM carries no timestamp, so the subscriber can // check the payload alone. Stay open until each one is acknowledged. - let mut track = broadcast.create_datagrams("tail", moq_net::datagram::Info::default())?; + let mut track = broadcast.create_datagrams("tail", moq_net::datagram::Info::default()).context("the track already exists")?; route.announce()?; let session = client .clone() @@ -154,7 +154,7 @@ async fn main() -> anyhow::Result<()> { // `cached` and `late` read groups a newer one supersedes, which the default // zero max age would leave stale. .with_max_age(None), - )?; + ).context("the track already exists")?; route.announce()?; if cached { write(&mut track, mode)?; From b6702e74a8d6db93e376a807b619349399c122c2 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 18 Nov 2026 22:35:17 -0800 Subject: [PATCH 03/10] wip: js counterparts and call-site migration Co-Authored-By: Claude Opus 5.5 --- js/e2ee/bench/pump.ts | 11 +- js/e2ee/src/broadcast.ts | 24 ++-- js/e2ee/src/defined.test-util.ts | 5 + js/e2ee/src/e2ee.test.ts | 13 +- js/e2ee/src/transport.test.ts | 17 ++- js/hang/src/catalog/consumer.test.ts | 15 +- js/hang/src/defined.test-util.ts | 5 + js/hang/src/report.ts | 4 +- js/net/api/index.api.md | 8 +- js/net/bench/broadcasts.ts | 5 +- js/net/bench/fill-probe.ts | 3 +- js/net/bench/fills.ts | 3 +- js/net/bench/priority.ts | 3 +- js/net/bench/refresh.ts | 3 +- js/net/bench/resume-history.ts | 3 +- js/net/bench/resume.ts | 5 +- js/net/bench/serve-browser-entry.ts | 5 +- js/net/bench/subscribe-drop.ts | 4 +- js/net/examples/publish.ts | 5 +- js/net/src/auth.test.ts | 27 ++-- js/net/src/broadcast.test.ts | 71 +++++----- js/net/src/broadcast.ts | 26 ++-- js/net/src/connection/pool.test.ts | 3 +- js/net/src/connection/reload.test.ts | 9 +- js/net/src/consume.test.ts | 3 +- js/net/src/datagram.test.ts | 7 +- js/net/src/defined.test-util.ts | 5 + js/net/src/fill.test.ts | 63 ++++----- js/net/src/fill.ts | 21 ++- js/net/src/group-id.test.ts | 11 +- js/net/src/ietf/connection.test.ts | 5 +- js/net/src/ietf/datagram.test.ts | 19 +-- js/net/src/ietf/join.test.ts | 5 +- js/net/src/ietf/malformed.test.ts | 3 +- js/net/src/ietf/publisher.test.ts | 139 ++++++++++--------- js/net/src/ietf/subscriber.ts | 4 +- js/net/src/integration.test.ts | 69 ++++----- js/net/src/listing.test.ts | 97 ++++++------- js/net/src/lite/compression.test.ts | 5 +- js/net/src/lite/connection.test.ts | 17 +-- js/net/src/lite/copy_fill.test.ts | 23 +-- js/net/src/lite/datagram-tracks.test.ts | 41 +++--- js/net/src/lite/drop_record.test.ts | 3 +- js/net/src/lite/fills.test.ts | 20 +-- js/net/src/lite/publisher.test.ts | 77 +++++----- js/net/src/lite/refresh.test.ts | 11 +- js/net/src/lite/subscriber.ts | 51 +++---- js/net/src/lite/tracks.test.ts | 41 +++--- js/net/src/lite/widened_max_age.test.ts | 7 +- js/net/src/order.test.ts | 9 +- js/net/src/origin-request.test.ts | 12 +- js/net/src/origin.test.ts | 33 ++--- js/net/src/parked-expiry.test.ts | 5 +- js/net/src/priority.test.ts | 3 +- js/net/src/resume.model.test.ts | 3 +- js/net/src/resume.test-util.ts | 3 +- js/net/src/resume.test.ts | 73 +++++----- js/net/src/retention.test.ts | 3 +- js/net/src/subscribe_priority.test.ts | 9 +- js/net/src/tail.test.ts | 3 +- js/net/src/terminal.test.ts | 3 +- js/net/src/untimed.test.ts | 3 +- js/net/src/wire.ts | 2 +- js/publish/src/broadcast.ts | 2 + js/room/src/chat.test.ts | 3 +- js/room/src/chat.ts | 4 +- js/room/src/defined.test-util.ts | 5 + js/room/src/metadata.test.ts | 9 +- js/room/src/metadata.ts | 1 + js/stats/src/defined.test-util.ts | 5 + js/stats/src/stats.test.ts | 3 +- js/watch/src/audio/decoder.test.ts | 15 +- js/watch/src/broadcast.test.ts | 23 +-- js/watch/src/defined.test-util.ts | 5 + js/watch/src/include.test.ts | 38 ++--- js/watch/src/offline.test.ts | 3 +- js/watch/src/retention.test.ts | 3 +- js/watch/src/video/decoder.test.ts | 22 ++- rs/hang/examples/video.rs | 8 +- rs/moq-archive/src/consumer/mod.rs | 5 +- rs/moq-boy/src/status.rs | 17 +-- rs/moq-e2ee/src/tests.rs | 29 +++- rs/moq-e2ee/tests/transport.rs | 12 +- rs/moq-mux/src/catalog/producer.rs | 6 +- rs/moq-mux/src/container/fmp4/import.rs | 16 ++- rs/moq-mux/src/container/mkv/import.rs | 5 +- rs/moq-mux/src/container/ts/export_test.rs | 9 +- rs/moq-mux/src/container/ts/release_test.rs | 3 +- rs/moq-mux/src/container/ts/revision_test.rs | 6 +- rs/moq-net/src/coding/writer.rs | 6 +- rs/moq-net/src/ietf/publisher.rs | 29 ++-- rs/moq-net/src/model/broadcast.rs | 19 +-- rs/moq-net/src/model/origin.rs | 10 +- rs/moq-net/src/model/resume.rs | 25 +++- rs/moq-net/src/model/track.rs | 59 ++++++-- rs/moq-net/src/transport/memory.rs | 5 +- rs/moq-rtsp/src/client.rs | 9 +- rs/moq-stats/src/produce.rs | 8 +- rs/moq-tokio/examples/chat.rs | 5 +- rs/moq-tokio/examples/clock.rs | 5 +- rs/moq-tokio/src/quic/web/send.rs | 6 +- rs/moq-tokio/src/worker/group.rs | 13 +- rs/moq-tokio/tests/integration/relay_fill.rs | 12 +- rs/moq-transcode/src/lib.rs | 5 +- rs/moq-transcode/src/rung.rs | 28 +++- rs/moq-uring/src/quic/web/send.rs | 6 +- rs/moq-uring/tests/integration/web.rs | 5 +- rs/moq-video/src/decode/consumer.rs | 3 +- rs/moq-video/src/encode/publisher.rs | 6 +- test/interop/clients/rust/catalog.rs | 3 +- test/interop/clients/rust/control.rs | 3 +- test/interop/clients/rust/finish.rs | 8 +- test/interop/clients/rust/goaway.rs | 3 +- test/interop/clients/rust/hls.rs | 8 +- test/interop/clients/rust/tail.rs | 30 ++-- 115 files changed, 1023 insertions(+), 741 deletions(-) create mode 100644 js/e2ee/src/defined.test-util.ts create mode 100644 js/hang/src/defined.test-util.ts create mode 100644 js/net/src/defined.test-util.ts create mode 100644 js/room/src/defined.test-util.ts create mode 100644 js/stats/src/defined.test-util.ts create mode 100644 js/watch/src/defined.test-util.ts diff --git a/js/e2ee/bench/pump.ts b/js/e2ee/bench/pump.ts index 4aa6d12a8e5..bf975efd6b5 100644 --- a/js/e2ee/bench/pump.ts +++ b/js/e2ee/bench/pump.ts @@ -2,6 +2,7 @@ // Bun's WebCrypto stands in for the browser's, so compare runs on the same runtime. import { Duration } from "@moq/clock"; import { Broadcast, Time } from "@moq/net"; +import { defined } from "../src/defined.test-util.ts"; import { Credential } from "../src/index.ts"; const GROUP_FRAMES = 64; @@ -25,10 +26,12 @@ for (const bytes of [160, 1_160, 16_384, 262_144]) { for (let round = 0; round < 6; round++) { const generation = credential.produce(); // No publisher limit: every group is sealed before the first is read. - const net = new Broadcast.Producer().createTrack(await generation.name("video"), { - timescale: Time.Timescale.MILLI, - maxAge: null, - }); + const net = defined( + new Broadcast.Producer().createTrack(await generation.name("video"), { + timescale: Time.Timescale.MILLI, + maxAge: null, + }), + ); const consumer = credential .consume(generation.epoch) .consume(net.subscribe({ delay: { max: Duration.millis(60_000) } }), "video"); diff --git a/js/e2ee/src/broadcast.ts b/js/e2ee/src/broadcast.ts index d1c86bec62f..f0ae538b7de 100644 --- a/js/e2ee/src/broadcast.ts +++ b/js/e2ee/src/broadcast.ts @@ -39,19 +39,27 @@ export class Producer { /** * Create the track for `semantic` under its physical name. * - * Rejects with {@link Failure} `identity` past 65535 bytes, `reuse` if this generation already - * produced the name (even on another broadcast), or the net error if the broadcast already - * holds it. + * Resolves `undefined` while the broadcast already holds it. Rejects with {@link Failure} + * `identity` past 65535 bytes, or `reuse` if this generation already produced the name (even + * on another broadcast). */ - async createTrack(semantic: string, info: NetTrack.InfoInit = {}): Promise { + async createTrack(semantic: string, info: NetTrack.InfoInit = {}): Promise { const name = await this.generation.name(semantic); - return this.generation.produce(this.#inner.createTrack(name, info), semantic); + const track = this.#inner.createTrack(name, info); + return track && this.generation.produce(track, semantic); } - /** Create a protected datagram track in its own namespace and sequence space. */ - async createDatagrams(semantic: string, info: Partial = {}): Promise { + /** + * Create a protected datagram track in its own namespace and sequence space, or `undefined` + * while the broadcast already holds a live one of that name. + */ + async createDatagrams( + semantic: string, + info: Partial = {}, + ): Promise { const name = await this.generation.name(semantic); - return this.generation.produceDatagrams(this.#inner.createDatagrams(name, info), semantic); + const track = this.#inner.createDatagrams(name, info); + return track && this.generation.produceDatagrams(track, semantic); } /** End the wrapped broadcast, as `@moq/net`'s `close` does. Idempotent. */ diff --git a/js/e2ee/src/defined.test-util.ts b/js/e2ee/src/defined.test-util.ts new file mode 100644 index 00000000000..b66104d627b --- /dev/null +++ b/js/e2ee/src/defined.test-util.ts @@ -0,0 +1,5 @@ +/** `value`, failing the test when it is `undefined`, as a name or group already taken. @internal */ +export function defined(value: T | undefined): T { + if (value === undefined) throw new Error("expected a value"); + return value; +} diff --git a/js/e2ee/src/e2ee.test.ts b/js/e2ee/src/e2ee.test.ts index 8f45847ff03..831b2787aab 100644 --- a/js/e2ee/src/e2ee.test.ts +++ b/js/e2ee/src/e2ee.test.ts @@ -12,6 +12,7 @@ import { import * as Protected from "./broadcast.ts"; import { Credential } from "./credential.ts"; import type * as Datagram from "./datagram.ts"; +import { defined } from "./defined.test-util.ts"; import { DATAGRAM, GROUP } from "./derive.ts"; import { Failure } from "./failure.ts"; import type * as Generation from "./generation.ts"; @@ -46,7 +47,7 @@ const text = (value: string) => encoder.encode(value); // No publisher limit, since the tests read groups a later one has superseded. function netTrack(name: string, timed = true): NetTrack.Producer { const timescale = timed ? Time.Timescale.MILLI : undefined; - return new Broadcast.Producer().createTrack(name, { timescale, maxAge: null }); + return defined(new Broadcast.Producer().createTrack(name, { timescale, maxAge: null })); } function subscribe(net: NetTrack.Producer): NetTrack.Subscriber { @@ -247,7 +248,7 @@ test("a broadcast speaks semantic names and puts physical names on the wire", as const generation = credential().produce(); const net = new Broadcast.Producer(); const producer = new Protected.Producer(net, generation); - const video = await producer.createTrack("video", { timescale: Time.Timescale.MILLI }); + const video = defined(await producer.createTrack("video", { timescale: Time.Timescale.MILLI })); expect(video.name).toBe(await generation.name("video")); const consumer = await new Protected.Consumer( @@ -877,9 +878,11 @@ test("produce waits for an unaccepted track's timescale", async () => { test("a timestamp out of range at the track's timescale spends nothing", async () => { const generation = credential().produce(); - const net = new Broadcast.Producer().createTrack(await generation.name("video"), { - timescale: Time.Timescale.NANO, - }); + const net = defined( + new Broadcast.Producer().createTrack(await generation.name("video"), { + timescale: Time.Timescale.NANO, + }), + ); const consumer = generation.credential.consume(generation.epoch).consume(subscribe(net), "video"); const producer = await generation.produce(net, "video"); const huge = new Time.Timestamp(Number.MAX_SAFE_INTEGER, Time.Timescale.MILLI); diff --git a/js/e2ee/src/transport.test.ts b/js/e2ee/src/transport.test.ts index a30a57190e0..7e528aa1a78 100644 --- a/js/e2ee/src/transport.test.ts +++ b/js/e2ee/src/transport.test.ts @@ -6,6 +6,7 @@ import { type Broadcast, Connection, Origin, type Path, Time } from "@moq/net"; import { createMockTransportPair } from "../../net/src/mock.ts"; import * as Protected from "./broadcast.ts"; import { Credential } from "./credential.ts"; +import { defined } from "./defined.test-util.ts"; import * as Epoch from "./epoch.ts"; const encoder = new TextEncoder(); @@ -68,9 +69,11 @@ for (const [name, protocol, routed, keyed] of transports) { instance: { id: Epoch.instance(generation.epoch), epoch: 0n }, }); const broadcast = broadcastRoute.broadcast; - const video = await new Protected.Producer(broadcast, generation).createTrack("video", { - timescale: Time.Timescale.MILLI, - }); + const video = defined( + await new Protected.Producer(broadcast, generation).createTrack("video", { + timescale: Time.Timescale.MILLI, + }), + ); broadcastRoute.announce(); // Starts before its first frame, so a keyed frame's time (its group's key) tells apart. @@ -129,9 +132,11 @@ for (const [name, protocol] of [ instance: { id: Epoch.instance(generation.epoch), epoch: 0n }, }); const broadcast = broadcastRoute.broadcast; - const audio = await new Protected.Producer(broadcast, generation).createDatagrams("audio", { - timescale: Time.Timescale.MILLI, - }); + const audio = defined( + await new Protected.Producer(broadcast, generation).createDatagrams("audio", { + timescale: Time.Timescale.MILLI, + }), + ); broadcastRoute.announce(); const remote = await active(subscriber, path); diff --git a/js/hang/src/catalog/consumer.test.ts b/js/hang/src/catalog/consumer.test.ts index 1aa986b5dd1..d261596892b 100644 --- a/js/hang/src/catalog/consumer.test.ts +++ b/js/hang/src/catalog/consumer.test.ts @@ -2,6 +2,7 @@ import { expect, test } from "bun:test"; import { Duration } from "@moq/clock"; import * as Json from "@moq/json"; import * as Moq from "@moq/net"; +import { defined } from "../defined.test-util.ts"; import { TRACK } from "./format"; import { checkRenditions, @@ -56,7 +57,7 @@ test("the shared containment check covers every section carrying a broadcast ref test("watch yields a catalog with many renditions", async () => { const broadcast = new Moq.Broadcast.Producer(); - const track = broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI }); + const track = defined(broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI })); const producer = new Json.Snapshot.Producer({ track, deltas: false }); const consumer = watch(broadcast.consume())[Symbol.asyncIterator](); producer.update(catalog(1000), Moq.Time.Timestamp.now()); @@ -68,7 +69,7 @@ test("watch yields a catalog with many renditions", async () => { test("watch refuses a catalog needing a newer reader", async () => { const broadcast = new Moq.Broadcast.Producer(); - const track = broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI }); + const track = defined(broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI })); const producer = new Json.Snapshot.Producer({ track, deltas: false }); const consumer = watch(broadcast.consume())[Symbol.asyncIterator](); producer.update({ version: VERSION + 1 }, Moq.Time.Timestamp.now()); @@ -90,7 +91,7 @@ async function watchRequested(root: Root) { const origin = new Moq.Origin.Producer(); const broadcastRoute = origin.route(Moq.Path.from("room/alice"), { hidden: true }); const broadcast = broadcastRoute.broadcast; - const track = broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI }); + const track = defined(broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI })); const producer = new Json.Snapshot.Producer({ track, deltas: false }); broadcastRoute.announce(); const request = origin.request(Moq.Path.from("room/alice")); @@ -119,7 +120,7 @@ test("watch accepts a sibling reference under the same root and yields it unreso test("watch on a standalone broadcast refuses any parent reference", async () => { const broadcast = new Moq.Broadcast.Producer(); - const track = broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI }); + const track = defined(broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI })); const producer = new Json.Snapshot.Producer({ track, deltas: false }); const consumer = watch(broadcast.consume())[Symbol.asyncIterator](); producer.update(referencing("../bob"), Moq.Time.Timestamp.now()); @@ -130,7 +131,7 @@ test("watch on a standalone broadcast refuses any parent reference", async () => test("watch yields each catalog update with the timestamp it takes effect at", async () => { const broadcast = new Moq.Broadcast.Producer(); - const track = broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI }); + const track = defined(broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI })); const producer = new Json.Snapshot.Producer({ track, deltas: false }); const consumer = watch(broadcast.consume())[Symbol.asyncIterator](); for (const [count, ms] of [ @@ -156,7 +157,9 @@ test("a holding watcher reads every update it may still play, in order", async ( [Duration.millis(1001), [1000, 2000, 3000]], ] as const) { const broadcast = new Moq.Broadcast.Producer(); - const track = broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI, maxAge: Duration.secs(30) }); + const track = defined( + broadcast.createTrack(TRACK, { timescale: Moq.Time.Timescale.MILLI, maxAge: Duration.secs(30) }), + ); const producer = new Json.Snapshot.Producer({ track, deltas: false }); // Subscribed before the updates land, as a live reader is; all three arrive before it reads. const updates = watch(broadcast.consume(), { delay })[Symbol.asyncIterator](); diff --git a/js/hang/src/defined.test-util.ts b/js/hang/src/defined.test-util.ts new file mode 100644 index 00000000000..b66104d627b --- /dev/null +++ b/js/hang/src/defined.test-util.ts @@ -0,0 +1,5 @@ +/** `value`, failing the test when it is `undefined`, as a name or group already taken. @internal */ +export function defined(value: T | undefined): T { + if (value === undefined) throw new Error("expected a value"); + return value; +} diff --git a/js/hang/src/report.ts b/js/hang/src/report.ts index bf85ff66602..562ff11803a 100644 --- a/js/hang/src/report.ts +++ b/js/hang/src/report.ts @@ -39,7 +39,9 @@ export class Writer { * publisher passes the schema's input (plain numbers) and readers get its output. */ constructor(broadcast: Moq.Broadcast.Producer, name: string, schema: z.ZodMiniType) { - this.track = broadcast.createTrack(name, { priority: PRIORITY, compression: "deflate", refresh: REFRESH }); + const track = broadcast.createTrack(name, { priority: PRIORITY, compression: "deflate", refresh: REFRESH }); + if (!track) throw new Error(`the track ${name} already exists`); + this.track = track; this.#producer = new Json.Snapshot.Producer({ track: this.track }); this.#schema = schema; } diff --git a/js/net/api/index.api.md b/js/net/api/index.api.md index 2b726644379..601247189e0 100644 --- a/js/net/api/index.api.md +++ b/js/net/api/index.api.md @@ -108,8 +108,8 @@ export namespace Broadcast { close(): void; get closed(): Signals.GetPromise; consume(): Broadcast.Consumer; - createDatagrams(name: string, info?: Partial): Datagram.Producer; - createTrack(name: string, info?: Track.InfoInit): Track.Producer; + createDatagrams(name: string, info?: Partial): Datagram.Producer | undefined; + createTrack(name: string, info?: Track.InfoInit): Track.Producer | undefined; removeTrack(name: string): void; track(name: string): Track.Consumer; } @@ -698,7 +698,7 @@ export namespace Track { export type Fill = Track.FillGroups | Track.FillLookup; export class FillGroups { [Symbol.dispose](): void; - accept(start: bigint, info?: Track.Info): Group.Producer; + accept(start: bigint, info?: Track.Info): Group.Producer | undefined; close(): void; dropGroups(start: bigint, end: bigint): void; readonly end: bigint; @@ -715,7 +715,7 @@ export namespace Track { } export class FillLookup { [Symbol.dispose](): void; - accept(start: bigint, info?: Track.Info): Group.Producer; + accept(start: bigint, info?: Track.Info): Group.Producer | undefined; close(): void; readonly kind: "lookup"; get maxDelay(): Clock.Duration | null; diff --git a/js/net/bench/broadcasts.ts b/js/net/bench/broadcasts.ts index c439ac65e37..c2cfea9530b 100644 --- a/js/net/bench/broadcasts.ts +++ b/js/net/bench/broadcasts.ts @@ -5,6 +5,7 @@ import { Signal } from "@moq/signals"; import type { Grant } from "../src/auth.ts"; import { Producer as BroadcastProducer } from "../src/broadcast.ts"; import { BroadcastCache } from "../src/consume.ts"; +import { defined } from "../src/defined.test-util.ts"; import { toHop, WireRoute } from "../src/hop.ts"; import * as Instance from "../src/instance.ts"; import { Publisher } from "../src/lite/publisher.ts"; @@ -100,7 +101,7 @@ console.log("tracks,listings,create_remove_and_read_us"); for (const trackCount of [8, 128, 1024]) { for (const listingCount of [1, 8, 32]) { const broadcast = new BroadcastProducer(); - for (let index = 0; index < trackCount; index++) broadcast.createTrack(`held-${index}`); + for (let index = 0; index < trackCount; index++) defined(broadcast.createTrack(`held-${index}`)); const listings = Array.from({ length: listingCount }, () => broadcast.consume().tracks()); // Past each listing's initial set and SYNCED. for (const listing of listings) { @@ -108,7 +109,7 @@ for (const trackCount of [8, 128, 1024]) { } const start = performance.now(); for (let index = 0; index < listed; index++) { - broadcast.createTrack(`new-${index}`); + defined(broadcast.createTrack(`new-${index}`)); for (const listing of listings) { const event = await listing.next(); if (event?.kind !== "added" || event.name !== `new-${index}`) throw new Error("listing missed a track"); diff --git a/js/net/bench/fill-probe.ts b/js/net/bench/fill-probe.ts index a71c06c0342..ceae737024e 100644 --- a/js/net/bench/fill-probe.ts +++ b/js/net/bench/fill-probe.ts @@ -4,6 +4,7 @@ */ import { Duration } from "@moq/clock"; import { Producer as BroadcastProducer } from "../src/broadcast.ts"; +import { defined } from "../src/defined.test-util.ts"; import { hooks, staleHole } from "../src/internal.ts"; import { Timestamp } from "../src/time.ts"; @@ -12,7 +13,7 @@ console.log("runs,readers,step_us"); for (const runs of [250, 1000, 4000, 16000]) { for (const readers of [1, 8]) { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); // 2 and 3 are read up front, so the only gaps any fill is asked for are the drops below. for (const sequence of [2n, 3n]) { const live = track.createGroup(sequence); diff --git a/js/net/bench/fills.ts b/js/net/bench/fills.ts index 5c4d24d270a..4cdc560beff 100644 --- a/js/net/bench/fills.ts +++ b/js/net/bench/fills.ts @@ -1,5 +1,6 @@ /** Sweep cached groups against independent peers requesting draft-22 fills. */ import { Duration } from "@moq/clock"; +import { defined } from "../src/defined.test-util.ts"; import { FetchHeader } from "../src/ietf/fetch"; import * as Filter from "../src/ietf/filter"; import { Parameters } from "../src/ietf/parameters"; @@ -22,7 +23,7 @@ for (const groups of [2, 16, 128]) { for (const subscribers of [1, 8]) { const origin = new Producer(); const publication = origin.route(Path.from("fills")); - const track = publication.broadcast.createTrack("video", { maxAge: Duration.millis(60_000) }); + const track = defined(publication.broadcast.createTrack("video", { maxAge: Duration.millis(60_000) })); for (let i = 0; i < groups; i++) { const group = hooks.appendNext(track); group.writeFrame({ payload: new Uint8Array([i % 256]), timestamp: Timestamp.unscaled(group.start) }); diff --git a/js/net/bench/priority.ts b/js/net/bench/priority.ts index efd1e868d27..0e62c00ebfc 100644 --- a/js/net/bench/priority.ts +++ b/js/net/bench/priority.ts @@ -1,5 +1,6 @@ /** Sweep subscriptions and simultaneous streams when a group or joining fill changes rank. */ import { Producer } from "../src/broadcast.ts"; +import { defined } from "../src/defined.test-util.ts"; import { Priority } from "../src/priority.ts"; import type { Writer } from "../src/stream.ts"; @@ -9,7 +10,7 @@ for (const subscriptions of [1, 16, 128]) { for (const streams of [4, 16, 64]) { const broadcast = new Producer(); const queues = Array.from({ length: subscriptions }, (_, index) => { - const track = broadcast.createTrack(`track-${index}`); + const track = defined(broadcast.createTrack(`track-${index}`)); const subscriber = track.subscribe(); const priority = new Priority(subscriber); const writers = Array.from({ length: streams }, (_, stream) => { diff --git a/js/net/bench/refresh.ts b/js/net/bench/refresh.ts index b73653ddda7..43517c382d5 100644 --- a/js/net/bench/refresh.ts +++ b/js/net/bench/refresh.ts @@ -3,6 +3,7 @@ import { Duration } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import { accept } from "../src/connection/accept.ts"; import { connect } from "../src/connection/connect.ts"; +import { defined } from "../src/defined.test-util.ts"; import { hooks } from "../src/internal.ts"; import { ALPN_07_WIP } from "../src/lite/version.ts"; import { createMockTransportPair } from "../src/mock.ts"; @@ -22,7 +23,7 @@ for (const retained of [1, 64, 1024]) const broadcastRoute = source.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; const producers = Array.from({ length: tracks }, (_, i) => - broadcast.createTrack(`data${i}`, { refresh: { ratio: 1 } }), + defined(broadcast.createTrack(`data${i}`, { refresh: { ratio: 1 } })), ); const pair = createMockTransportPair(ALPN_07_WIP); const url = new URL("https://localhost/refresh"); diff --git a/js/net/bench/resume-history.ts b/js/net/bench/resume-history.ts index 5a6469be570..b347d30354b 100644 --- a/js/net/bench/resume-history.ts +++ b/js/net/bench/resume-history.ts @@ -22,6 +22,7 @@ import { Manual } from "@moq/clock/test"; import type { Producer as BroadcastProducer } from "../src/broadcast.ts"; import { accept } from "../src/connection/accept.ts"; import { connect } from "../src/connection/connect.ts"; +import { defined } from "../src/defined.test-util.ts"; import { hooks } from "../src/internal.ts"; import { ALPN_06 } from "../src/lite/version.ts"; import { createMockTransportPair } from "../src/mock.ts"; @@ -227,7 +228,7 @@ async function measureOn(clock: Manual, { fronts, names: perRoute, routes, histo for (const broadcast of broadcasts) { const all = new Set(Array.from({ length: routes }, (_, route) => names(history, route, perRoute)).flat()); for (const name of all) { - const track = broadcast.createTrack(name); + const track = defined(broadcast.createTrack(name)); const group = hooks.appendNext(track); group.writeFrame({ payload, timestamp: Timestamp.unscaled(group.start) }); group.finish(); diff --git a/js/net/bench/resume.ts b/js/net/bench/resume.ts index 0cbba94c6b8..c5f8411bd57 100644 --- a/js/net/bench/resume.ts +++ b/js/net/bench/resume.ts @@ -8,6 +8,7 @@ import { Duration } from "@moq/clock"; import { Producer as BroadcastProducer } from "../src/broadcast.ts"; +import { defined } from "../src/defined.test-util.ts"; import { Producer as GroupProducer } from "../src/group.ts"; import { hooks } from "../src/internal.ts"; import { Front } from "../src/resume.ts"; @@ -46,7 +47,7 @@ async function measure(readers: number, swaps: number | undefined, fork = false) const sources: { broadcast: BroadcastProducer; write: () => void }[] = []; const source = () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("seq"); + const track = defined(broadcast.createTrack("seq")); // Every route's copy holds the same groups under the same sequences. const write = () => { const group = track.createGroup(sequence); @@ -143,7 +144,7 @@ async function measureFlaps(readers: number, flaps: number): Promise { const front = new Front(); const sources = [new BroadcastProducer(), new BroadcastProducer()]; const handles = sources.map((source) => source.consume()); - const tracks = sources.map((source) => source.createTrack("seq")); + const tracks = sources.map((source) => defined(source.createTrack("seq"))); const groups = tracks.map((track) => { const group = hooks.appendNext(track); group.writeFrame({ payload, timestamp: Timestamp.unscaled(group.start) }); diff --git a/js/net/bench/serve-browser-entry.ts b/js/net/bench/serve-browser-entry.ts index 5ba9c865318..1de3c0b776d 100644 --- a/js/net/bench/serve-browser-entry.ts +++ b/js/net/bench/serve-browser-entry.ts @@ -1,6 +1,7 @@ /** Measure publisher fairness with memory-resident groups and an immediately writable transport. */ import { Duration } from "@moq/clock"; +import { defined } from "../src/defined.test-util.ts"; import { randomHop } from "../src/hop.ts"; import { Publisher as IetfPublisher } from "../src/ietf/publisher.ts"; import { NativeSession } from "../src/ietf/session.ts"; @@ -19,7 +20,9 @@ async function measure(protocol: string, groups: number, viewers: number) { const origin = new Origin(); const broadcastRoute = origin.route(Path.from("bench")); const broadcast = broadcastRoute.broadcast; - const track = broadcast.createTrack("data", { maxAge: Duration.millis(60_000), timescale: Timescale.MICRO }); + const track = defined( + broadcast.createTrack("data", { maxAge: Duration.millis(60_000), timescale: Timescale.MICRO }), + ); const pair = createMockTransportPair(protocol === "lite" ? ALPN_05 : ALPN.DRAFT_22); const version = protocol === "lite" ? LiteVersion.DRAFT_05 : IetfVersion.DRAFT_22; let written = 0, diff --git a/js/net/bench/subscribe-drop.ts b/js/net/bench/subscribe-drop.ts index 794aaca9b12..31c8af53c0d 100644 --- a/js/net/bench/subscribe-drop.ts +++ b/js/net/bench/subscribe-drop.ts @@ -1,4 +1,6 @@ /** Sweep failed group sends over independent publishers and subscribers. */ + +import { defined } from "../src/defined.test-util.ts"; import { randomHop } from "../src/hop.ts"; import { Publisher } from "../src/lite/publisher.ts"; import { decodeSubscribeResponseMaybe, Subscribe } from "../src/lite/subscribe.ts"; @@ -24,7 +26,7 @@ try { const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("bench")); const broadcast = broadcastRoute.broadcast; - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); for (let sequence = 0n; sequence < BigInt(groups); sequence++) { const group = track.createGroup(sequence); group.writeFrame(textFrame("frame")); diff --git a/js/net/examples/publish.ts b/js/net/examples/publish.ts index 948adbef6ee..8aa666d76f9 100644 --- a/js/net/examples/publish.ts +++ b/js/net/examples/publish.ts @@ -14,7 +14,10 @@ async function main() { // Create the "chat" track up front. A subscriber is served directly from this // track, no requested() round-trip needed. Mirrors Rust's create_track. // Each frame is stamped with the time it was written, so the track declares a timescale. - void publishTrack(broadcast.createTrack("chat", { timescale: Moq.Time.Timescale.MILLI })); + // Undefined only while another track holds the name, which a fresh broadcast never has. + const track = broadcast.createTrack("chat", { timescale: Moq.Time.Timescale.MILLI }); + if (!track) throw new Error("the chat track already exists"); + void publishTrack(track); console.log("Published broadcast: my-broadcast"); await connection.closed; diff --git a/js/net/src/auth.test.ts b/js/net/src/auth.test.ts index 9b71fb2bdd8..1339d5209cf 100644 --- a/js/net/src/auth.test.ts +++ b/js/net/src/auth.test.ts @@ -12,6 +12,7 @@ import { Unsupported, } from "./auth.ts"; import { accept as acceptSession, connect as connectSession, type Session } from "./connection/index.ts"; +import { defined } from "./defined.test-util.ts"; import { SessionCode, SessionError, StreamCode, StreamError, toStreamCode } from "./error.ts"; import { appendFrame } from "./frame.test-util.ts"; import * as Ietf from "./ietf/index.ts"; @@ -492,7 +493,7 @@ describe.each([Lite.ALPN_07_WIP])("%s", (protocol) => { const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room/x")); const broadcast = broadcastRoute.broadcast; - const published = broadcast.createTrack("video"); + const published = defined(broadcast.createTrack("video")); appendFrame(published, new Uint8Array([1])); const { client, server } = await connect({ serverPublish: origin, protocol }); const requests = server.auth.requests(); @@ -518,7 +519,7 @@ describe.each([Lite.ALPN_07_WIP])("%s", (protocol) => { const renewing = answered(client.auth.add("renewal")); const renewal = await requests.next(); if (!renewal) throw new Error("missing renewal"); - appendFrame(broadcast.createTrack("audio"), new Uint8Array([3])); + appendFrame(defined(broadcast.createTrack("audio")), new Uint8Array([3])); const covered = wireOf(client).consume(Path.from("room/x")).track("audio").subscribe(); expect(await covered.recvGroup()).toBeDefined(); covered.close(); @@ -554,9 +555,9 @@ describe.each([Lite.ALPN_07_WIP])("%s", (protocol) => { try { const unanswered = await requests.next(); if (!unanswered) throw new Error("missing token"); - const track = new OriginProducer() - .route(Path.from("room/x"), { hidden: true }) - .broadcast.createTrack("video"); + const track = defined( + new OriginProducer().route(Path.from("room/x"), { hidden: true }).broadcast.createTrack("video"), + ); const reader = track.subscribe(); const ready = wireOf(client).auth.ready(Path.from("room/x"), "subscribe", { until: () => abandoned(track.demand()), @@ -583,7 +584,7 @@ describe.each([Lite.ALPN_07_WIP])("%s", (protocol) => { const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room/x")); const broadcast = broadcastRoute.broadcast; - broadcast.createTrack("video"); + defined(broadcast.createTrack("video")); const { client, server, transport } = await connect({ serverPublish: origin, protocol }); const requests = server.auth.requests(); const setup = await requests.next(); @@ -621,7 +622,7 @@ describe.each([Lite.ALPN_07_WIP])("%s", (protocol) => { const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room/x")); const broadcast = broadcastRoute.broadcast; - const published = broadcast.createTrack("video"); + const published = defined(broadcast.createTrack("video")); appendFrame(published, new Uint8Array([7])); const { client, server } = await connect({ serverPublish: origin, protocol }); const requests = server.auth.requests(); @@ -657,7 +658,7 @@ describe.each([Lite.ALPN_07_WIP])("%s", (protocol) => { const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room/x")); const broadcast = broadcastRoute.broadcast; - appendFrame(broadcast.createTrack("video"), new Uint8Array([1])); + appendFrame(defined(broadcast.createTrack("video")), new Uint8Array([1])); const { client, server } = await connect({ serverPublish: origin, protocol }); await waitFor(client.auth.grant, (g) => g !== undefined && g.subscribe.size > 0); @@ -1086,7 +1087,7 @@ test("a fetch abandoned while its token waits never reaches the wire", async () const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room/x")); const broadcast = broadcastRoute.broadcast; - appendFrame(broadcast.createTrack("video"), new Uint8Array([1])); + appendFrame(defined(broadcast.createTrack("video")), new Uint8Array([1])); const { client, server, transport } = await connect({ serverPublish: origin, protocol: Lite.ALPN_07_WIP }); const requests = server.auth.requests(); const setup = await requests.next(); @@ -1126,7 +1127,7 @@ test("a listing waits for its token before reaching the wire", async () => { const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room/x")); const broadcast = broadcastRoute.broadcast; - broadcast.createTrack("video"); + defined(broadcast.createTrack("video")); const { client, server, transport } = await connect({ serverPublish: origin, protocol: Lite.ALPN_07_WIP }); const requests = server.auth.requests(); const setup = await requests.next(); @@ -1163,7 +1164,7 @@ test.each(Array.from({ length: 17 }, (_, gap) => gap))( const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room/x")); const broadcast = broadcastRoute.broadcast; - appendFrame(broadcast.createTrack("video"), new Uint8Array([7])); + appendFrame(defined(broadcast.createTrack("video")), new Uint8Array([7])); const { client, server } = await connect({ serverPublish: origin, protocol: Lite.ALPN_07_WIP }); const requests = server.auth.requests(); const setup = await requests.next(); @@ -1279,12 +1280,12 @@ test("a revoked grant resets its subscriptions with UNAUTHORIZED", async () => { const clientOrigin = new OriginProducer(); const upRoute = clientOrigin.route(Path.from("up/y")); const up = upRoute.broadcast; - const upTrack = up.createTrack("video"); + const upTrack = defined(up.createTrack("video")); const serverOrigin = new OriginProducer(); const downRoute = serverOrigin.route(Path.from("room/x")); const down = downRoute.broadcast; - const downTrack = down.createTrack("video"); + const downTrack = defined(down.createTrack("video")); const { client, server } = await connect({ publish: clientOrigin, diff --git a/js/net/src/broadcast.test.ts b/js/net/src/broadcast.test.ts index 878a93d0a97..e0bffa8f607 100644 --- a/js/net/src/broadcast.test.ts +++ b/js/net/src/broadcast.test.ts @@ -3,6 +3,7 @@ import { Duration, yieldNow } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import * as cache from "./cache.ts"; +import { defined } from "./defined.test-util.ts"; import { NotFound, StreamCode, TooFarBehind, toStreamCode } from "./error.ts"; import { hooks } from "./internal.ts"; import { textFrame } from "./mock.ts"; @@ -108,7 +109,7 @@ test("a replacement producer starts over", async () => { second.close(); broadcast.removeTrack("media"); - const third = broadcast.createTrack("media", { timescale: Timescale.MILLI }); + const third = defined(broadcast.createTrack("media", { timescale: Timescale.MILLI })); third.finishAt({ group: 0n, frame: 0 }); third.close(); broadcast.close(); @@ -121,7 +122,7 @@ test("createTrack answers a queued request", async () => { const subscriber = broadcast.track("media").subscribe().ordered(); // The track is created before any handler takes the queued request. - const producer = broadcast.createTrack("media", { timescale: Timescale.MILLI, priority: 3 }); + const producer = defined(broadcast.createTrack("media", { timescale: Timescale.MILLI, priority: 3 })); producer.writeFrame(textFrame("hello", Timestamp.fromMillis(1))); expect(await subscriber.readString()).toBe("hello"); expect((await info).priority).toBe(3); @@ -136,7 +137,7 @@ test("createTrack answers a queued request", async () => { const again = broadcast.track("media").subscribe().ordered(); producer.writeFrame(textFrame("again", Timestamp.fromMillis(2))); expect(await again.readString()).toBe("again"); - expect(() => broadcast.createTrack("media")).toThrow("duplicate track"); + expect(broadcast.createTrack("media")).toBeUndefined(); broadcast.close(); expect(await pulled).toBeUndefined(); @@ -147,11 +148,11 @@ test("createTrack with invalid info rejects the queued request it answers", asyn const pulled = wireOf(broadcast).requested(); const subscriber = broadcast.track("media").subscribe(); - expect(() => broadcast.createTrack("media", { priority: 256 })).toThrow(); + expect(() => defined(broadcast.createTrack("media", { priority: 256 }))).toThrow(); expect(await subscriber.closed).toBeInstanceOf(Error); // The refused request no longer holds the name. - broadcast.createTrack("media"); + defined(broadcast.createTrack("media")); broadcast.close(); expect(await pulled).toBeUndefined(); }); @@ -164,7 +165,7 @@ test("createTrack does not take over a request a handler already pulled", async if (!request) throw new Error("expected request"); // The handler holds it, so the name stays duplicate until it answers, as in Rust. - expect(() => broadcast.createTrack("media")).toThrow("duplicate track"); + expect(broadcast.createTrack("media")).toBeUndefined(); request.reject(new Error("request refused")); broadcast.close(); }); @@ -277,7 +278,7 @@ test("an abandoned info lookup's request goes once answered", async () => { test("a held info lookup on an inserted track leaves it open when it lets go", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("media", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("media", { timescale: Timescale.MILLI })); const hold = new AbortController(); await wireOf(broadcast).resolveTrackInfo("media", hold.signal); @@ -374,7 +375,7 @@ test("a consumer clone shares the broadcast until every handle closes", () => { test("closing every consumer leaves a produced broadcast to its producer", async () => { const producer = new BroadcastProducer(); - const track = producer.createTrack("video"); + const track = defined(producer.createTrack("video")); const consumer = producer.consume(); const subscriber = consumer.track("video").subscribe(); consumer.close(); @@ -425,7 +426,7 @@ test("consumer track subscriptions fan out and close independently", async () => test("subscribe serves a statically inserted track without a request", async () => { const broadcast = new BroadcastProducer(); - const track1 = broadcast.createTrack("track1", { timescale: Timescale.MILLI }); + const track1 = defined(broadcast.createTrack("track1", { timescale: Timescale.MILLI })); hooks.appendNext(track1).finish(); // The track already exists, so subscribe resolves immediately (no requested()). @@ -436,7 +437,7 @@ test("subscribe serves a statically inserted track without a request", async () expect(await pendingRequest(broadcast)).toBeUndefined(); // A second static track behaves the same. - const track2 = broadcast.createTrack("track2", { timescale: Timescale.MILLI }); + const track2 = defined(broadcast.createTrack("track2", { timescale: Timescale.MILLI })); const sub2 = broadcast.track("track2").subscribe().ordered(); hooks.appendNext(track2).finish(); @@ -445,7 +446,7 @@ test("subscribe serves a statically inserted track without a request", async () test("two subscribers to one inserted track each get a full copy", async () => { const broadcast = new BroadcastProducer(); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const a = broadcast .track("video") @@ -468,7 +469,7 @@ test("two subscribers to one inserted track each get a full copy", async () => { test("a late subscriber replays the cached window", async () => { const broadcast = new BroadcastProducer(); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); // Written before anyone subscribes; retained in the cache for replay. producer.writeFrame(textFrame("early", Timestamp.fromMillis(1))); @@ -482,7 +483,7 @@ test("a late subscriber replays the cached window", async () => { test("a read throws Evicted at a shed front, then resyncs to the next group", async () => { const broadcast = new BroadcastProducer(); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const sub = broadcast .track("video") .subscribe({ delay: { max: Duration.millis(5000) } }) @@ -511,7 +512,7 @@ test("a stalled consumer does not pin evicted groups", async () => { clock.jump(Duration.millis(10_000)); const broadcast = new BroadcastProducer(); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); // A subscriber that never reads. Its sink must not grow without bound. No max delay, // so only eviction (not a skip of a superseded group) can drop the old group. @@ -541,11 +542,13 @@ test("a stalled consumer does not pin evicted groups", async () => { test("createTrack commits info up front", async () => { const broadcast = new BroadcastProducer(); - const producer = broadcast.createTrack("video", { - timescale: Timescale.MILLI, - maxAge: Duration.millis(2000), - priority: 3, - }); + const producer = defined( + broadcast.createTrack("video", { + timescale: Timescale.MILLI, + maxAge: Duration.millis(2000), + priority: 3, + }), + ); expect(producer.name).toBe("video"); const info = await broadcast.track("video").info(); @@ -555,13 +558,13 @@ test("createTrack commits info up front", async () => { test("createTrack rejects a duplicate live name", () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("dup", { timescale: Timescale.MILLI }); - expect(() => broadcast.createTrack("dup", { timescale: Timescale.MILLI })).toThrow("duplicate track"); + defined(broadcast.createTrack("dup", { timescale: Timescale.MILLI })); + expect(broadcast.createTrack("dup", { timescale: Timescale.MILLI })).toBeUndefined(); }); test("a finished track is still served from its cache", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("track1", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("track1", { timescale: Timescale.MILLI })); track.writeFrame(textFrame("last")); track.finish(); track.close(); @@ -580,7 +583,7 @@ test("a finished track is still served from its cache", async () => { test("an aborted track is gone, so a subscribe with no handler answers NotFound", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("track1").abort(new Error("boom")); + defined(broadcast.createTrack("track1")).abort(new Error("boom")); // Nothing serves requests on demand, so this must fail rather than wait forever. const subscriber = broadcast.consume().track("track1").subscribe(); @@ -592,7 +595,7 @@ test("an aborted track is gone, so a subscribe with no handler answers NotFound" test("an aborted track falls through to a request when a handler is serving", async () => { const broadcast = new BroadcastProducer(); const pulled = wireOf(broadcast).requested(); - broadcast.createTrack("track1").abort(new Error("boom")); + defined(broadcast.createTrack("track1")).abort(new Error("boom")); broadcast.track("track1").subscribe(); expect((await pulled)?.name).toBe("track1"); @@ -601,13 +604,13 @@ test("an aborted track falls through to a request when a handler is serving", as test("removeTrack drops the static entry", async () => { // While the static entry exists, subscribing takes the fast path: no on-demand request. const kept = new BroadcastProducer(); - kept.createTrack("track1", { timescale: Timescale.MILLI }); + defined(kept.createTrack("track1", { timescale: Timescale.MILLI })); kept.track("track1").subscribe(); expect(await pendingRequest(kept)).toBeUndefined(); // With the entry removed and nothing serving on demand, the track is not found. const removed = new BroadcastProducer(); - removed.createTrack("track1", { timescale: Timescale.MILLI }); + defined(removed.createTrack("track1", { timescale: Timescale.MILLI })); removed.removeTrack("track1"); await expect(removed.track("track1").subscribe().info()).rejects.toBeInstanceOf(NotFound); }); @@ -633,7 +636,7 @@ test("close rejects a still-pending track request so its subscriber unblocks", a // wants a group that already exists, and waiting for one that is gone would never return. test("a fetch of a group still to come asks the request handler, and the write answers it", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); // As in Rust, the miss goes to the handler at once; without one it would be NotFound. const requests = track.requests(); @@ -657,7 +660,9 @@ test("a fetch of a group still to come asks the request handler, and the write a test("fetch maxDelay tightens the publisher's maxAge without changing omission", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Duration.millis(2000) }); + const track = defined( + broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Duration.millis(2000) }), + ); for (const millis of [0, 1000]) { const group = hooks.appendNext(track); @@ -683,7 +688,7 @@ test("fetch maxDelay tightens the publisher's maxAge without changing omission", test("aborting a fetch rejects with the signal's reason", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); // A request handler keeps the miss pending until the abort. const requests = track.requests(); @@ -725,7 +730,7 @@ test("a fetch of a failed group leaves its unread frames to the pool's expiry", const installed = clock.install(); try { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); hooks.poolTrack(track, new cache.Pool({ expiry: Duration.millis(1_000) })); const failed = hooks.appendNext(track); @@ -749,15 +754,15 @@ test("a track name with a lone surrogate is refused where it is named, since UTF const broadcast = new BroadcastProducer(); const consumer = broadcast.consume(); for (const name of ["\uD800", "a\uDC00", "\uDC00\uD800"]) { - expect(() => broadcast.createTrack(name)).toThrow("lone surrogate"); - expect(() => broadcast.createDatagrams(name)).toThrow("lone surrogate"); + expect(() => defined(broadcast.createTrack(name))).toThrow("lone surrogate"); + expect(() => defined(broadcast.createDatagrams(name))).toThrow("lone surrogate"); expect(() => broadcast.track(name)).toThrow("lone surrogate"); expect(() => consumer.track(name)).toThrow("lone surrogate"); expect(() => consumer.datagrams(name)).toThrow("lone surrogate"); } // A pair is one scalar, U+10000, and U+FFFD itself is text like any other. for (const name of ["𐀀", "a�"]) { - expect(broadcast.createTrack(name).name).toBe(name); + expect(defined(broadcast.createTrack(name)).name).toBe(name); expect(consumer.track(name).name).toBe(name); } broadcast.close(); diff --git a/js/net/src/broadcast.ts b/js/net/src/broadcast.ts index 2da0b20f17a..7acf7aea7a0 100644 --- a/js/net/src/broadcast.ts +++ b/js/net/src/broadcast.ts @@ -86,7 +86,7 @@ function createDatagrams( name: string, info: Partial, listed = true, -): datagram.Producer { +): datagram.Producer | undefined { if (state.closed.peek() !== undefined) throw new Error("broadcast is closed"); // A request its readers closed waits for async cleanup; serve the name fresh instead. const queued = state.datagramRequested @@ -98,7 +98,7 @@ function createDatagrams( producer = queued.accept(info); } else { const existing = state.datagrams.get(name); - if (existing?.closed.peek() === undefined && existing) throw new Error(`duplicate datagram track: ${name}`); + if (existing?.closed.peek() === undefined && existing) return undefined; producer = new datagram.Producer(name).accept(info); state.datagrams.set(name, producer); void producer.closed.then(() => { @@ -471,17 +471,18 @@ export class Producer { } /** - * Create a track, insert it into the broadcast, and return its producer. + * Create a track, insert it into the broadcast, and return its producer, or `undefined` while + * an open track or a live request holds the name. * * A request still queued for the name is answered with this track, so its subscribers read * from the returned producer. A request a handler has already taken stays a duplicate. * An append on the track throws if it would reuse a key an earlier track of the name - * wrote in this broadcast, so a replacement writes its first group explicitly. Throws if an - * open track or a live request already holds the name, or if the name holds a lone surrogate, - * which UTF-8 cannot carry. `info` resolves as {@link track.Producer.accept} does, so an - * omitted `maxAge` is zero, the live edge only. + * wrote in this broadcast, so a replacement writes its first group explicitly. Throws if the + * broadcast is closed, or if the name holds a lone surrogate, which UTF-8 cannot carry. `info` + * resolves as {@link track.Producer.accept} does, so an omitted `maxAge` is zero, the live + * edge only. */ - createTrack(name: string, info: track.InfoInit = {}): track.Producer { + createTrack(name: string, info: track.InfoInit = {}): track.Producer | undefined { if (this.#state.closed.peek() !== undefined) { throw new Error("broadcast is closed"); } @@ -499,7 +500,7 @@ export class Producer { // A request a handler already pulled stays duplicate, as in Rust. const live = [this.#state.tracks.get(name), this.#state.requests.get(name)]; if (live.some((existing) => existing && hooks.trackReleased(existing).peek() === undefined)) { - throw new Error(`duplicate track: ${name}`); + return undefined; } const producer = createProducer(this.#state, name).accept(info); @@ -507,8 +508,11 @@ export class Producer { return producer; } - /** Create a live datagram track in a namespace separate from stream tracks. */ - createDatagrams(name: string, info: Partial = {}): datagram.Producer { + /** + * Create a live datagram track in a namespace separate from stream tracks, or `undefined` + * while a live datagram track holds the name. + */ + createDatagrams(name: string, info: Partial = {}): datagram.Producer | undefined { return createDatagrams(this.#state, name, info); } diff --git a/js/net/src/connection/pool.test.ts b/js/net/src/connection/pool.test.ts index be7aa64e90a..80a036d5bcc 100644 --- a/js/net/src/connection/pool.test.ts +++ b/js/net/src/connection/pool.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; import { Duration, type Installed } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import { Signal } from "@moq/signals"; +import { defined } from "../defined.test-util.ts"; import { SessionCode, SessionError } from "../error.ts"; import * as Lite from "../lite/index.ts"; import { createMockTransportPair, type MockTransport } from "../mock.ts"; @@ -269,7 +270,7 @@ test("a publish through one handle resolves locally for another", async () => { const origin = publisher.origin.peek(); if (!origin) throw new Error("expected an origin"); const broadcast = publish(origin, Path.from("mine")); - broadcast.createTrack("chat", { timescale: Time.Timescale.MILLI }); + defined(broadcast.createTrack("chat", { timescale: Time.Timescale.MILLI })); // Loopback: the shared origin serves the page's own publish with no round trip, so the // request resolves synchronously instead of waiting on the relay to announce it back. diff --git a/js/net/src/connection/reload.test.ts b/js/net/src/connection/reload.test.ts index 2ac9e84f12a..d4e4b0a8036 100644 --- a/js/net/src/connection/reload.test.ts +++ b/js/net/src/connection/reload.test.ts @@ -10,6 +10,7 @@ import { ConnectTimeout, SessionCode, SessionError, StreamCode, toTransport } fr import { WireRoute } from "../hop.ts"; // Loaded up front: a session imports it on first use, which takes host turns a Manual clock cannot wait out. import "../ietf/connection.ts"; +import { defined } from "../defined.test-util.ts"; import { ALPN as IetfALPN } from "../ietf/version.ts"; import { hooks } from "../internal.ts"; import * as Lite from "../lite/index.ts"; @@ -867,7 +868,7 @@ for (const [name, teardown] of Object.entries(teardowns)) { if (!origin) throw new Error("no origin"); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); await waitUntil(() => dials.length > 0); const first = dials[0]; if (!first) throw new Error("no first dial"); @@ -954,7 +955,7 @@ for (const [name, drainEnd] of Object.entries(drainEnds)) { const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const reload = new Reload({ url: new URL("https://example.com/a"), websocket: { enabled: false }, @@ -1014,7 +1015,7 @@ test("a retired GOAWAY predecessor still closes by its handover cap", async () = const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const reload = new Reload({ url: new URL("https://example.com/"), websocket: { enabled: false }, @@ -1097,7 +1098,7 @@ test("closing the loop keeps the tokens until the session drains", async () => { await reload.auth.add("token").answered; const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const first = dials[0]; if (!first) throw new Error("no first dial"); const remote = wireOf(await first.server).consume(Path.from("room")); diff --git a/js/net/src/consume.test.ts b/js/net/src/consume.test.ts index c1cf0a7a526..792cbd7250c 100644 --- a/js/net/src/consume.test.ts +++ b/js/net/src/consume.test.ts @@ -1,6 +1,7 @@ import { expect, test } from "bun:test"; import { Producer } from "./broadcast.ts"; import { BroadcastCache } from "./consume.ts"; +import { defined } from "./defined.test-util.ts"; import { StreamCode, StreamError } from "./error.ts"; import { WireRoute } from "./hop.ts"; import * as Instance from "./instance.ts"; @@ -16,7 +17,7 @@ test("cache identity follows the serving announcement, preserving held tracks", const instance = Instance.random(); cache.announce(pool, broad, { ...WireRoute.default, instance }); const source = new Producer(); - const track = source.createTrack("video"); + const track = defined(source.createTrack("video")); const held = cache.insert(job, cache.instance(job), source.consume()); const ordered = held.track("video").subscribe().ordered(); cache.announce(job, specific, { ...WireRoute.default, instance }); diff --git a/js/net/src/datagram.test.ts b/js/net/src/datagram.test.ts index 870d0cc683f..d8769fdaeef 100644 --- a/js/net/src/datagram.test.ts +++ b/js/net/src/datagram.test.ts @@ -7,8 +7,8 @@ const seq = (sequence: bigint) => Timestamp.unscaled(sequence); test("a broadcast keeps same-name datagram and stream tracks independent", async () => { const broadcast = new Broadcast.Producer(); - const streams = broadcast.createTrack("audio"); - const datagrams = broadcast.createDatagrams("audio"); + const streams = defined(broadcast.createTrack("audio")); + const datagrams = defined(broadcast.createDatagrams("audio")); const reader = broadcast.consume().datagrams("audio"); expect(hooks.appendNext(streams).start).toBe(0n); expect(datagrams.append(seq(0n), new Uint8Array([1]))).toBe(0n); @@ -21,6 +21,7 @@ test("a broadcast keeps same-name datagram and stream tracks independent", async }); import * as Datagram from "./datagram.ts"; +import { defined } from "./defined.test-util.ts"; import { StreamCode, StreamError, TimestampMismatch } from "./error.ts"; import { hooks } from "./internal.ts"; import { wireOf } from "./wire.ts"; @@ -183,7 +184,7 @@ test("creating a datagram track in the turn its queued request closes serves the void wireOf(consumer).requestedDatagrams(); const left = consumer.datagrams("test"); left.close(); - const track = broadcast.createDatagrams("test"); + const track = defined(broadcast.createDatagrams("test")); const next = consumer.datagrams("test"); track.append(seq(0n), new Uint8Array([2])); expect((await next.recv())?.payload).toEqual(new Uint8Array([2])); diff --git a/js/net/src/defined.test-util.ts b/js/net/src/defined.test-util.ts new file mode 100644 index 00000000000..b66104d627b --- /dev/null +++ b/js/net/src/defined.test-util.ts @@ -0,0 +1,5 @@ +/** `value`, failing the test when it is `undefined`, as a name or group already taken. @internal */ +export function defined(value: T | undefined): T { + if (value === undefined) throw new Error("expected a value"); + return value; +} diff --git a/js/net/src/fill.test.ts b/js/net/src/fill.test.ts index ae181a96bf5..1f269aac697 100644 --- a/js/net/src/fill.test.ts +++ b/js/net/src/fill.test.ts @@ -4,6 +4,7 @@ import { Manual } from "@moq/clock/test"; import { Producer as BroadcastProducer } from "./broadcast.ts"; import { DEFAULT_EXPIRY } from "./cache.ts"; import { accept as acceptSession, connect as connectSession } from "./connection/index.ts"; +import { defined } from "./defined.test-util.ts"; import { NotFound, StreamCode, StreamError, toStreamCode } from "./error.ts"; import { type FillLookup, rejectGroups } from "./fill.ts"; import type { Consumer as GroupConsumer } from "./group.ts"; @@ -45,7 +46,7 @@ function serve(fill: FillGroups, archive: Archive): void { fill.dropGroups(key, key + 1n); continue; } - const group = fill.accept(key); + const group = defined(fill.accept(key)); for (const frame of frames) group.writeFrame({ payload: enc.encode(frame), timestamp: Timestamp.unscaled(group.start) }); group.finish(); @@ -72,7 +73,7 @@ async function drain(reader: { recvGroup(): Promise } // A track whose first write is group `first`, so every group below it was never cached here. function resumed(first: bigint): { broadcast: BroadcastProducer; track: Producer } { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); const group = track.createGroup(first); group.writeFrame({ payload: enc.encode(`live ${first}`), timestamp: Timestamp.unscaled(group.start) }); group.finish(); @@ -215,7 +216,7 @@ test("fill: an answer aborted below the end does not hold the end open", async ( const fetching = wireOf(broadcast).fetchGroup("video", 0n); const fill = await requestedGroups(requests); if (fill?.kind !== "groups") throw new Error("no fill of groups"); - const group = fill.accept(0n); + const group = defined(fill.accept(0n)); group.writeFrame({ payload: enc.encode("backfill"), timestamp: Timestamp.unscaled(group.start) }); if (parked) { track.finishAt({ group: 2n, frame: 0 }); @@ -247,7 +248,7 @@ test("fill: a failed answer to a gap the feed owes holds the end and the ordered async function failedAnswerHoldsTheEnd(error: Error) { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); hooks.receiveTrack(track); const reader = track.subscribe({ delay: { max: null } }); const ordered = reader.ordered(); @@ -257,7 +258,7 @@ async function failedAnswerHoldsTheEnd(error: Error) { const fetching = wireOf(broadcast).fetchGroup("video", 1n); const fill = await requestedGroups(requests); if (fill?.kind !== "groups") throw new Error("no fill of groups"); - fill.accept(1n).abort(error); + defined(fill.accept(1n)).abort(error); fill.close(); await fetching.catch(() => undefined); hooks.endTrack(track, { group: 3n, frame: 0 }); @@ -291,7 +292,7 @@ async function failedAnswerHoldsTheEnd(error: Error) { // the START answered the old floor, so it no longer bounds what the feed owes. test("fill: a group a lowered floor asks the feed for is not asked of a fill", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); hooks.receiveTrack(track); const live = track.subscribe({ ranges: [{ start: { relative: 0n } }], delay: { max: null } }); hooks.startTrack(track, { start: 1n }); @@ -319,7 +320,7 @@ test("fill: a group a lowered floor asks the feed for is not asked of a fill", a test("fill: a failed answer is withheld from a subscribed reader that reads at once", async () => { for (const dispositions of [false, true]) { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); hooks.receiveTrack(track); hooks.receiveGroup(track, { start: 2n, offset: 0 }).finish(); const reader = track.subscribe({ ranges: [{ start: { time: 0n } }], delay: { max: null } }); @@ -327,7 +328,7 @@ test("fill: a failed answer is withheld from a subscribed reader that reads at o const fetching = wireOf(broadcast).fetchGroup("video", 1n); const fill = await requestedGroups(requests); if (fill?.kind !== "groups") throw new Error("no fill of groups"); - fill.accept(1n).abort(new Error("archive failed")); + defined(fill.accept(1n)).abort(new Error("archive failed")); const seen: unknown[] = []; for (let recv = hooks.tryRecvGroup(reader, dispositions); recv.kind !== "idle"; ) { seen.push(recv.kind === "group" ? recv.group.start : recv); @@ -346,12 +347,12 @@ test("fill: a failed answer is withheld from a subscribed reader that reads at o // sees the fill's own failure, never a cache eviction. test("fill: a held answer that fails keeps its frames and its failure", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); const requests = track.requests(); const fetching = wireOf(broadcast).fetchGroup("video", 1n); const fill = await requestedGroups(requests); if (fill?.kind !== "groups") throw new Error("no fill of groups"); - const answer = fill.accept(1n); + const answer = defined(fill.accept(1n)); answer.writeFrame({ payload: enc.encode("fill 1"), timestamp: Timestamp.unscaled(answer.start) }); const group = await fetching; const failure = new Error("archive failed"); @@ -380,15 +381,15 @@ test("fill: an answer withheld after a probe judged it is asked again", async () const fill = await requestedGroups(requests); expect(fill && [fill.start, fill.end]).toEqual([0n, 4n]); if (fill?.kind !== "groups") throw new Error("no fill of groups"); - fill.accept(0n).finish(); - const answer = fill.accept(2n); + defined(fill.accept(0n)).finish(); + const answer = defined(fill.accept(2n)); answer.writeFrame({ payload: enc.encode("fill 2"), timestamp: Timestamp.unscaled(answer.start) }); expect((await first)?.start).toBe(0n); // Waiting on group 1, the bounded window probes everything it names, group 2 held among it. const second = ordered.nextGroup(); await yieldNow(); answer.abort(new Error("archive failed")); - fill.accept(1n).finish(); + defined(fill.accept(1n)).finish(); expect((await second)?.start).toBe(1n); const third = ordered.nextGroup(); @@ -407,7 +408,7 @@ test("fill: an answer withheld after a probe judged it is asked again", async () // failed group below it, which was no successor. test("fill: a gap below a group that fails after a probe is asked", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); const requests = track.requests(); const reader = track.subscribe({ ranges: [{ start: { time: 0n } }], delay: { max: Duration.millis(0) } }); const ordered = reader.ordered(); @@ -655,7 +656,7 @@ test("fill: a fill names the most urgent priority and loosest budget among its r // Rust records a stale run without answering any fill. test("fill: a stale verdict leaves an outstanding fill owed", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); const requests = track.requests(); track.createGroup(3n).finish(); const fetching = wireOf(broadcast).fetchGroup("video", 2n); @@ -665,7 +666,7 @@ test("fill: a stale verdict leaves an outstanding fill owed", async () => { hooks.dropTrackGroups(track, 2n, 3n, staleHole(500)); expect(fill.wanted()).toBe(2n); - const group = fill.accept(2n); + const group = defined(fill.accept(2n)); group.writeFrame({ payload: enc.encode("filled"), timestamp: Timestamp.unscaled(group.start) }); group.finish(); expect(await frames(await fetching)).toEqual(["filled"]); @@ -677,7 +678,7 @@ test("fill: a stale verdict leaves an outstanding fill owed", async () => { test("fill: a group arriving live answers the fill", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); const requests = track.requests(); const late = track.createGroup(3n); late.finish(); @@ -690,7 +691,7 @@ test("fill: a group arriving live answers the fill", async () => { live.writeFrame({ payload: enc.encode("live"), timestamp: Timestamp.unscaled(live.start) }); live.finish(); expect(fill.wanted()).toBeUndefined(); - expect(() => fill.accept(1n)).toThrow(); + expect(() => defined(fill.accept(1n))).toThrow(); expect(await frames(await fetching)).toEqual(["live"]); fill.close(); @@ -797,7 +798,7 @@ test("fill: a bounded reader keeps waiting on a fresh fill once an older one goe const installed = clock.install(); try { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); const write = (key: bigint) => { const group = track.createGroup(key); group.writeFrame({ @@ -830,7 +831,7 @@ test("fill: a bounded reader keeps waiting on a fresh fill once an older one goe // Holes 0-1 are past the budget now, but 3-4 are not: the read waits on them. await clock.advance(Duration.millis(600)); - const late = fills[1].accept(3n); + const late = defined(fills[1].accept(3n)); late.writeFrame({ payload: enc.encode("old 3"), timestamp: Timestamp.unscaled(late.start) }); late.finish(); expect((await next)?.start).toBe(3n); @@ -885,7 +886,7 @@ test("fill: a reader joining a wider fill is owed only its own ranges", async () expect(await Promise.race([requests.requestedFill(), yieldNow().then(() => "none")])).toBe("none"); for (const key of [2n, 7n]) { - const group = fill.accept(key); + const group = defined(fill.accept(key)); group.writeFrame({ payload: enc.encode(`old ${key}`), timestamp: Timestamp.unscaled(group.start) }); group.finish(); } @@ -1002,7 +1003,7 @@ test("fill: a filled group stays wanted only while a reader will still read it", const fill = await requestedGroups(requests); if (fill?.kind !== "groups") throw new Error("no fill of groups"); expect(fill.wanted()).toBe(0n); - const source = fill.accept(0n); + const source = defined(fill.accept(0n)); source.writeFrame({ payload: enc.encode("g0"), timestamp: Timestamp.unscaled(source.start) }); const taken = await next; expect(taken?.start).toBe(0n); @@ -1253,7 +1254,7 @@ async function session(alpn: string) { ]); const publication = origin.route(Path.from("archive")); const broadcast = publication.broadcast; - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); // Groups 0 to 2 were published before this producer existed. const live = track.createGroup(3n); live.writeFrame({ payload: enc.encode("live 3"), timestamp: Timestamp.fromMillis(3000) }); @@ -1268,7 +1269,7 @@ async function session(alpn: string) { fill.dropGroups(1n, 2n); continue; } - const group = fill.accept(key); + const group = defined(fill.accept(key)); group.writeFrame({ payload: enc.encode(`old ${key}`), timestamp: Timestamp.fromMillis(Number(key) * 1000), @@ -1348,7 +1349,7 @@ test("fill: a lite-07 ranged subscription reads history the publisher never cach // reader asks again. Mirrors the Rust `a_fills_old_answer_under_the_max_age_is_held_until_forgotten`. test("fill: an OLD answer under the max age is held as stale until forgotten", async () => { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: Duration.millis(10_000) }); + const track = defined(broadcast.createTrack("video", { maxAge: Duration.millis(10_000) })); const live = track.createGroup(3n); live.writeFrame({ payload: enc.encode("live 3"), timestamp: Timestamp.unscaled(live.start) }); live.finish(); @@ -1405,7 +1406,7 @@ test("fill: an OLD answer under the max age is held as stale until forgotten", a // whole. function headless(): { broadcast: BroadcastProducer; track: Producer } { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); const tail = hooks.receiveGroup(track, { start: 2n, offset: 3 }); for (const frame of ["c3", "c4"]) tail.writeFrame({ payload: enc.encode(frame), timestamp: Timestamp.unscaled(2n) }); @@ -1569,7 +1570,7 @@ test("fill: a fetch of a headless group asks its head, as a fetch from frame 0 d // `n` keyed by its start, `n` milliseconds. function timed(): { broadcast: BroadcastProducer; track: Producer } { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const group = track.createGroup(5n); group.writeFrame({ payload: enc.encode("g5"), timestamp: Timestamp.fromMillis(5) }); group.finish(); @@ -1586,7 +1587,7 @@ function lookups(requests: Requests, lookup: (time: bigint) => bigint | undefine times.push(fill.time); const answer = lookup(fill.time); if (answer !== undefined) { - const group = fill.accept(answer); + const group = defined(fill.accept(answer)); group.writeFrame({ payload: enc.encode(`g${answer}`), timestamp: Timestamp.fromMillis(Number(answer)), @@ -1597,7 +1598,7 @@ function lookups(requests: Requests, lookup: (time: bigint) => bigint | undefine continue; } for (let key = fill.wanted(); key !== undefined; key = fill.wanted()) { - const group = fill.accept(key); + const group = defined(fill.accept(key)); group.writeFrame({ payload: enc.encode(`g${key}`), timestamp: Timestamp.fromMillis(Number(key)), @@ -1638,7 +1639,7 @@ test("fill: a lookup answered below the eviction watermark starts the range ther const installed = clock.install(); try { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const requests = track.requests(); const times = lookups(requests, (ms) => ms); for (let n = 0n; n < 3n; n++) { @@ -1677,7 +1678,7 @@ test("fill: a lookup's answer is read at once, before its first frame: its key i const lookup = await requests.requestedFill(); if (lookup?.kind !== "lookup") throw new Error("no lookup"); expect(lookup.time).toBe(2n); - const found = lookup.accept(2n); + const found = defined(lookup.accept(2n)); expect((await next)?.start).toBe(2n); found.finish(); diff --git a/js/net/src/fill.ts b/js/net/src/fill.ts index 0d36294eb56..6102ffc07ce 100644 --- a/js/net/src/fill.ts +++ b/js/net/src/fill.ts @@ -72,7 +72,7 @@ export interface Asker { // The fill operations a handle runs against the state it came from; assigned in its static block. let fillOps: { - accept(state: FillState, pending: Pending, key: bigint, info: Info | undefined): GroupProducer; + accept(state: FillState, pending: Pending, key: bigint, info: Info | undefined): GroupProducer | undefined; drop(state: FillState, pending: Pending, start: bigint, end: bigint, hole?: { error: Error; stale?: number }): void; refuse(state: FillState, pending: Pending, start: bigint, end: bigint, error: Error, stale?: number): void; settle(state: FillState, pending: Pending): void; @@ -393,11 +393,9 @@ export class FillState { if (key < pending.start || key >= pending.end) { throw new RangeError(`group ${key} is outside the fill ${pending.start}..${pending.end}`); } - if (pending.resolved.some((run) => run.start <= key && key < run.end)) { - throw new Error(`group ${key} was already answered`); - } + if (pending.resolved.some((run) => run.start <= key && key < run.end)) return undefined; // A copy missing its head is replaced from frame 0, as a bounded reader asked. - if (state.#track.holds(key) === true) throw new Error(`duplicate group: key=${key}`); + if (state.#track.holds(key) === true) return undefined; // Landing in the cache answers it, as `arrived` records. const group = state.#track.accept(key, info); // A lookup waits only on its first answer. @@ -692,10 +690,10 @@ export class FillGroups { * Insert group `key` into the track's cache, handing it to the readers waiting on it, * and return the producer to write its frames into. `info` commits the track's {@link Info} * if it has none yet. A cached copy missing its first frames, which a reader asked whole, is - * replaced. Throws a `RangeError` outside the fill, and an error if the group was already - * answered or cached whole, or the track is closed. + * replaced. Returns `undefined` if the group was already answered or cached whole. Throws a + * `RangeError` outside the fill, and an error if the track is closed. */ - accept(start: bigint, info?: Info): GroupProducer { + accept(start: bigint, info?: Info): GroupProducer | undefined { checkKey(start); return fillOps.accept(this.#state, this.#pending, start, info); } @@ -781,10 +779,11 @@ export class FillLookup { /** * Insert the group starting at `start`, the one containing {@link time}, into the track's * cache, answering the lookup, and return the producer to write its frames into. `info` commits the track's - * {@link Info} if it has none yet. Throws a `RangeError` at or past the live edge the lookup - * was asked below, and an error if the group is cached whole or the track is closed. + * {@link Info} if it has none yet. Returns `undefined` if the group is cached whole. Throws a + * `RangeError` at or past the live edge the lookup was asked below, and an error if the track + * is closed. */ - accept(start: bigint, info?: Info): GroupProducer { + accept(start: bigint, info?: Info): GroupProducer | undefined { checkKey(start); return fillOps.accept(this.#state, this.#pending, start, info); } diff --git a/js/net/src/group-id.test.ts b/js/net/src/group-id.test.ts index 664fcf51cd0..be3bb30dd46 100644 --- a/js/net/src/group-id.test.ts +++ b/js/net/src/group-id.test.ts @@ -3,6 +3,7 @@ import { expect, test } from "bun:test"; import { type Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { accept, connect } from "./connection/index.ts"; +import { defined } from "./defined.test-util.ts"; import * as Ietf from "./ietf/index.ts"; import * as Lite from "./lite/index.ts"; import { createMockTransportPair } from "./mock.ts"; @@ -49,7 +50,7 @@ async function forward(input: BroadcastConsumer, carriesDatagrams: boolean): Pro const copy = new BroadcastProducer(); if (carriesDatagrams) { const reader = input.datagrams("video"); - const writer = copy.createDatagrams("video", await reader.info()); + const writer = defined(copy.createDatagrams("video", await reader.info())); void (async () => { try { for (let datagram = await reader.recv(); datagram; datagram = await reader.recv()) @@ -62,7 +63,7 @@ async function forward(input: BroadcastConsumer, carriesDatagrams: boolean): Pro } })(); } - const video = copy.createTrack("video", await subscription.info()); + const video = defined(copy.createTrack("video", await subscription.info())); void (async () => { for (let group = await subscription.recvGroup(); group; group = await subscription.recvGroup()) { const out = video.createGroup(group.start); @@ -88,8 +89,8 @@ for (const wire of WIRES) { const path = Path.from("big"); const publication = source.route(path); - const datagrams = wire.datagrams ? publication.broadcast.createDatagrams("video") : undefined; - const track = publication.broadcast.createTrack("video"); + const datagrams = wire.datagrams ? defined(publication.broadcast.createDatagrams("video")) : undefined; + const track = defined(publication.broadcast.createTrack("video")); const dynamic = relay.claim(path); const inputs: BroadcastConsumer[] = []; @@ -154,7 +155,7 @@ for (const wire of WIRES) { } test("a group sequence that is not a non-negative bigint is refused where a caller passes one", async () => { - const track = new BroadcastProducer().createTrack("video"); + const track = defined(new BroadcastProducer().createTrack("video")); // A plain JS caller can still pass a number, which would otherwise mix with bigints later. expect(() => track.createGroup(1 as unknown as bigint)).toThrow(TypeError); expect(() => track.createGroup(-1n)).toThrow(RangeError); diff --git a/js/net/src/ietf/connection.test.ts b/js/net/src/ietf/connection.test.ts index efc993f5436..51fb3ca768f 100644 --- a/js/net/src/ietf/connection.test.ts +++ b/js/net/src/ietf/connection.test.ts @@ -1,6 +1,7 @@ import { expect, spyOn, test } from "bun:test"; import { yieldNow } from "@moq/clock"; import { exchangeSetup } from "../connection/handshake.ts"; +import { defined } from "../defined.test-util.ts"; import { SessionCode } from "../error.ts"; import { createMockTransportPair } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; @@ -429,7 +430,7 @@ for (const [version, alpn] of [[Version.DRAFT_22, ALPN.DRAFT_22]] as const) { const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - broadcast.createTrack("video", { timescale: Timescale.MILLI }); + defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const connection = new Connection({ url: new URL("https://example.com"), quic: pair.server, @@ -464,7 +465,7 @@ async function serving(version: IetfVersion, alpn: string) { const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - broadcast.createTrack("video", { timescale: Timescale.MILLI }); + defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const connection = new Connection({ url: new URL("https://example.com"), quic: pair.server, diff --git a/js/net/src/ietf/datagram.test.ts b/js/net/src/ietf/datagram.test.ts index b94911fb804..1e768d3393b 100644 --- a/js/net/src/ietf/datagram.test.ts +++ b/js/net/src/ietf/datagram.test.ts @@ -1,6 +1,7 @@ import { expect, spyOn, test } from "bun:test"; import { Duration, yieldNow } from "@moq/clock"; import { accept, connect } from "../connection/index.ts"; +import { defined } from "../defined.test-util.ts"; import { ProtocolViolation, SessionCode } from "../error.ts"; import { hooks } from "../internal.ts"; import { createMockTransportPair, type MockTransport, manual, settlesWithin } from "../mock.ts"; @@ -142,10 +143,12 @@ test("a datagram track round-trips over moq-transport", async () => { const source = new Origin(); const path = Path.from("live"); const publication = source.route(path, { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio", { - timescale: Timescale.MILLI, - priority: 3, - }); + const datagrams = defined( + publication.broadcast.createDatagrams("audio", { + timescale: Timescale.MILLI, + priority: 3, + }), + ); publication.announce(); const pair = createMockTransportPair(ALPN.DRAFT_22); const url = new URL("https://localhost/datagrams"); @@ -197,8 +200,8 @@ test("a relay shares one IETF subscription across stream and datagram readers", const relay = new Origin(); const path = Path.from("shared"); const publication = source.route(path, { hidden: true }); - const track = publication.broadcast.createTrack("audio", { timescale: Timescale.MILLI }); - const datagrams = publication.broadcast.createDatagrams("audio", { timescale: Timescale.MICRO }); + const track = defined(publication.broadcast.createTrack("audio", { timescale: Timescale.MILLI })); + const datagrams = defined(publication.broadcast.createDatagrams("audio", { timescale: Timescale.MICRO })); publication.announce(); const upstream = createMockTransportPair(ALPN.DRAFT_18); const url = new URL("https://localhost/shared"); @@ -309,7 +312,7 @@ for (const alpn of [ALPN.DRAFT_18, ALPN.DRAFT_20, ALPN.DRAFT_22]) { using clock = manual(); const source = new Origin(); const publication = source.route(Path.from("live"), { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio"); + const datagrams = defined(publication.broadcast.createDatagrams("audio")); publication.announce(); const pair = createMockTransportPair(alpn); lagAnswers(pair.server, lag); @@ -351,7 +354,7 @@ for (const alpn of [ALPN.DRAFT_18, ALPN.DRAFT_20, ALPN.DRAFT_22]) { using clock = manual(); const source = new Origin(); const publication = source.route(Path.from("live"), { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio"); + const datagrams = defined(publication.broadcast.createDatagrams("audio")); publication.announce(); const pair = createMockTransportPair(alpn); const url = new URL("https://localhost/datagrams"); diff --git a/js/net/src/ietf/join.test.ts b/js/net/src/ietf/join.test.ts index 0b87dc5a98e..d29fed1cba6 100644 --- a/js/net/src/ietf/join.test.ts +++ b/js/net/src/ietf/join.test.ts @@ -2,6 +2,7 @@ import { expect, jest, onTestFinished, test } from "bun:test"; import { Duration, now } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import * as Connection from "../connection/index.ts"; +import { defined } from "../defined.test-util.ts"; import { StreamCode } from "../error.ts"; import { hooks } from "../internal.ts"; import { GRACE } from "../ledger.ts"; @@ -606,9 +607,9 @@ async function publishing(version: IetfVersion) { const publication = origin.route(Path.from("room")); const broadcast = publication.broadcast; // Written once, before anyone subscribed, and left open: only the head can deliver it. - const catalog = broadcast.createTrack("catalog.json", { timescale: Timescale.MILLI }); + const catalog = defined(broadcast.createTrack("catalog.json", { timescale: Timescale.MILLI })); hooks.appendNext(catalog).writeFrame(textFrame("catalog")); - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = hooks.appendNext(video); group.writeFrame(textFrame("v0")); group.writeFrame(textFrame("v1")); diff --git a/js/net/src/ietf/malformed.test.ts b/js/net/src/ietf/malformed.test.ts index cb1f7bbfe21..1d617350564 100644 --- a/js/net/src/ietf/malformed.test.ts +++ b/js/net/src/ietf/malformed.test.ts @@ -2,6 +2,7 @@ import { expect, spyOn, test } from "bun:test"; import { Duration } from "@moq/clock"; import type { Manual } from "@moq/clock/test"; import { exchangeSetup } from "../connection/handshake.ts"; +import { defined } from "../defined.test-util.ts"; import { ProtocolViolation, SessionCode, StreamCode, StreamError } from "../error.ts"; import { createMockTransportPair, manual } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; @@ -64,7 +65,7 @@ async function serving(version: IetfVersion, alpn: string) { const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - broadcast.createTrack("video", { timescale: Timescale.MILLI }); + defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const connection = new Connection({ url: new URL("https://example.com"), quic: pair.server, diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index 031cc7d12a9..3ee02c6d0b5 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -5,6 +5,7 @@ import { Once, Signal } from "@moq/signals"; import type { Credential, Grant } from "../auth.ts"; import { Producer as BroadcastProducer } from "../broadcast.ts"; import { accept, connect } from "../connection/index.ts"; +import { defined } from "../defined.test-util.ts"; import { error, fromTransport, @@ -234,11 +235,13 @@ test("TRACK_STATUS is answered on every draft without subscribing", async () => const session = new NativeSession(pair.server, version, true); const { pub, origin } = publisher(pair.server, { session }); const broadcast = publish(origin, Path.from("room")); - const track = broadcast.createTrack("video", { - timescale: Timescale.MILLI, - maxAge: Duration.millis(5000), - priority: 2, - }); + const track = defined( + broadcast.createTrack("video", { + timescale: Timescale.MILLI, + maxAge: Duration.millis(5000), + priority: 2, + }), + ); const group = track.createGroup(4n); group.writeFrame({ payload: new Uint8Array([1]), timestamp: Timestamp.fromMillis(0) }); group.writeFrame({ payload: new Uint8Array([2]), timestamp: Timestamp.fromMillis(1) }); @@ -285,7 +288,7 @@ test("TRACK_STATUS finished at once is answered on every draft", async () => { if (!pending) throw new Error("no request for room"); finish(); const served = new BroadcastProducer(); - served.createTrack("video"); + defined(served.createTrack("video")); pending.serve(served); await task; expect(await wire().u53()).toBe(TrackStatusOk.id); @@ -302,7 +305,7 @@ test("TRACK_STATUS for an empty track names no largest", async () => { const pair = createMockTransportPair(ALPNS[version]); const session = new NativeSession(pair.server, version, true); const { pub, origin } = publisher(pair.server, { session }); - publish(origin, Path.from("room")).createTrack("video"); + defined(publish(origin, Path.from("room")).createTrack("video")); const { stream, wire } = requestStream(version); await pub.runTrackStatusRequest(trackStatus("room"), stream); @@ -859,7 +862,9 @@ test("a blocked group header is reset when the group expires", async () => { const { pub, origin } = publisher(pair.server); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); + const track = defined( + broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }), + ); const client = await Stream.open(pair.client, { version: VERSION }); const server = await Stream.accept(pair.server, VERSION); if (!server) throw new Error("publisher never accepted the subscribe stream"); @@ -937,7 +942,7 @@ test("a group stream whose FIN never completes is reset when the group expires", const { pub, origin } = publisher(pair.server); const broadcast = publish(origin, Path.from("test")); // No subscriber max age, so the track's caps the budget. - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: budget }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: budget })); const client = await Stream.open(pair.client, { version: VERSION }); const server = await Stream.accept(pair.server, VERSION); if (!server) throw new Error("publisher never accepted the subscribe stream"); @@ -1021,7 +1026,7 @@ test("a group stream whose FIN never completes is reset after the cache evicts i const budget = Duration.millis(60_000); const { pub, origin } = publisher(pair.server); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: budget }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: budget })); const client = await Stream.open(pair.client, { version: VERSION }); const server = await Stream.accept(pair.server, VERSION); if (!server) throw new Error("publisher never accepted the subscribe stream"); @@ -1111,7 +1116,9 @@ test("a group that goes stale while its stream opens writes nothing", async () = const { pub, origin } = publisher(pair.server); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }); + const track = defined( + broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }), + ); const client = await Stream.open(pair.client, { version: VERSION }); const server = await Stream.accept(pair.server, VERSION); if (!server) throw new Error("publisher never accepted the subscribe stream"); @@ -2211,7 +2218,7 @@ test("subscription completion sends PUBLISH_DONE on every supported draft", asyn const path = Path.from("test"); const { pub, origin } = publisher(pair.server, { session }); const broadcast = publish(origin, path); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const client = await Stream.open(pair.client, { version }); const server = await Stream.accept(pair.server, version); @@ -2491,7 +2498,7 @@ async function readFill( test("draft-22: an absolute filter trims the range it serves", async () => { using clock = manual(); const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); for (let i = 0; i < 4; i++) writeGroup(track, 3); const { client } = await runSubscribe( @@ -2548,7 +2555,7 @@ test("draft-22: an absolute filter trims the range it serves", async () => { */ test("draft-22: a filter starting past a group's end claims no END_OF_GROUP", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); writeGroup(track, 2); writeGroup(track, 2); @@ -2575,7 +2582,7 @@ test("draft-22: a filter starting past a group's end claims no END_OF_GROUP", as /** An absolute filter has a fixed start, so its SUBSCRIBE is no join even over the refresh ratio. */ test("draft-22: an absolute subscribe is no join", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, refresh: { ratio: 0 } }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, refresh: { ratio: 0 } })); writeGroup(track, 3); const { client } = await runSubscribe( @@ -2611,7 +2618,7 @@ test.each(IETF_VERSIONS)("version %d: only an absolute start replays history", a ] as const) { const fx = fixture(version); // Unlimited max age, so the first group is still served once its successor exists. - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); writeGroup(track, 1); writeGroup(track, 1); @@ -2650,7 +2657,7 @@ test.each(["nextObject", "unfiltered"] as const)( "draft-22: a %s fill serves the current group head once", async (kind) => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); writeGroup(track, 1); const group = hooks.appendNext(track); @@ -2704,7 +2711,7 @@ test.each(["nextObject", "unfiltered"] as const)( test("draft-22: a fill never rewinds an absolute live join", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); writeGroup(track, 2); const { client } = await runSubscribe( fx, @@ -2745,7 +2752,7 @@ test("draft-22: a fill never rewinds an absolute live join", async () => { */ test("draft-22: an open group with a shed front refuses a tail join", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = hooks.appendNext(track); for (let i = 0; i < 40; i++) { @@ -2781,7 +2788,7 @@ test("draft-22: an open group with a shed front refuses a tail join", async () = */ test("draft-22: a backwards range within one group serves nothing and ends the stream", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); // Deliberately left open: a hang here would outlive the group rather than end with it. const group = hooks.appendNext(track); @@ -2813,7 +2820,7 @@ test.each(["ascending", "descending"] as const)("draft-22: a wider fill is refus const fx = fixture(); // No max age: group 9 is served live, and a zero budget would give it up mid-write once the // live group supersedes it, racing this test's read of the refused fill. - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); for (const key of [0n, 3n, 9n]) { const group = track.createGroup(key); for (let i = 0; i < 2; i++) @@ -2860,7 +2867,7 @@ test.each(["ascending", "descending"] as const)("draft-22: a wider fill is refus test("draft-22: an empty track opens no fill stream", async () => { using clock = manual(); const fx = fixture(); - fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client, ok } = await runSubscribe( fx, @@ -2889,7 +2896,7 @@ test("draft-22: an empty track opens no fill stream", async () => { */ async function subscribeOkLargest(version: IetfVersion): Promise { const fx = fixture(version); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = track.createGroup(5n); for (let i = 0; i < 4; i++) { @@ -2933,7 +2940,7 @@ test.each([ ] as const)("%s: opt-out omits the Track Properties", async (_alpn, version) => { for (const propertiesWanted of [true, false]) { const fx = fixture(version); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client, ok } = await runSubscribe( fx, @@ -2972,7 +2979,7 @@ test.each([[Version.DRAFT_18, GroupOrder.Descending]] as const)( "%s: SUBSCRIBE_OK announces the served order", async (version, announced) => { const fx = fixture(version); - fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client, ok } = await runSubscribe( fx, @@ -2995,7 +3002,7 @@ test.each([[Version.DRAFT_18, GroupOrder.Descending]] as const)( test("a timed track declares TIMESCALE and sends no Timestamp", async () => { for (const version of IETF_VERSIONS) { const fx = fixture(version); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client, ok } = await runSubscribe( fx, new Subscribe({ @@ -3024,7 +3031,7 @@ test("a timed track declares TIMESCALE and sends no Timestamp", async () => { */ test.each(["skipGroups", "append"] as const)("our object 0 names the skipped keys below it: %s", async (how) => { const fx = fixture(); - const track = fx.broadcast.createTrack("video"); + const track = defined(fx.broadcast.createTrack("video")); const { client } = await runSubscribe( fx, new Subscribe({ @@ -3073,7 +3080,7 @@ test.each(["skipGroups", "append"] as const)("our object 0 names the skipped key test.each([false, true])("draft-22: exact terminal 5/5 survives group FIN=%s", async (finished) => { const fx = fixture(); - const track = fx.broadcast.createTrack("video"); + const track = defined(fx.broadcast.createTrack("video")); const { client } = await runSubscribe( fx, new Subscribe({ @@ -3144,7 +3151,7 @@ test("draft-22: an inline terminal reset after its FIN falls back to a standalon return writer; }); const fx = fixture(); - const track = fx.broadcast.createTrack("video"); + const track = defined(fx.broadcast.createTrack("video")); const { client } = await runSubscribe( fx, new Subscribe({ @@ -3213,7 +3220,7 @@ test("draft-22: an inline terminal reset after its FIN falls back to a standalon test("draft-22: a clean close past a bounded filter's end still sends PUBLISH_DONE", async () => { using clock = manual(); const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); writeGroup(track, 1); // group 0, the whole requested range const { client } = await runSubscribe( @@ -3251,7 +3258,7 @@ test("draft-22: a clean close past a bounded filter's end still sends PUBLISH_DO test("draft-22: a bounded filter that reaches the track's end still sends END_OF_TRACK", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); writeGroup(track, 1); // group 0 writeGroup(track, 1); // group 1, the filter's last and the track's @@ -3342,7 +3349,7 @@ for (const synchronous of [true, false]) { test(`a ${synchronous ? "thrown" : "rejected"} group open does not escape the subscription`, async () => { using clock = manual(); const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const attempted = Promise.withResolvers(); const failure = new Error("stream opening failed"); const create = spyOn(fx.pair.server, "createUnidirectionalStream").mockImplementationOnce(() => { @@ -3386,7 +3393,7 @@ for (const synchronous of [true, false]) { test("draft-22: PUBLISH_DONE waits for a queued group and counts every stream", async () => { using clock = manual(); const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); // Park the first stream open, the way a transport at its stream cap does. const slot = Promise.withResolvers(); @@ -3554,7 +3561,7 @@ for (const version of [Version.DRAFT_18] as const) { test("requester FIN keeps a draft-22 subscription serving; STOP_SENDING cancels it", async () => { const fx = fixture(Version.DRAFT_22); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const client = await Stream.open(fx.pair.client, { version: fx.version }); const server = await Stream.accept(fx.pair.server, fx.version); if (!server) throw new Error("missing stream"); @@ -3592,7 +3599,7 @@ test("requester FIN keeps a draft-22 subscription serving; STOP_SENDING cancels for (const version of [Version.DRAFT_18] as const) { test(`requester FIN cancels a ${version.toString(16)} subscription`, async () => { const fx = fixture(version); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const client = await Stream.open(fx.pair.client, { version: fx.version }); const server = await Stream.accept(fx.pair.server, fx.version); if (!server) throw new Error("missing stream"); @@ -3622,7 +3629,7 @@ for (const version of [Version.DRAFT_18] as const) { test("REQUEST_UPDATE applies priority and preserves it when omitted", async () => { const fx = fixture(Version.DRAFT_18); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client } = await runSubscribe( fx, new Subscribe({ @@ -3655,7 +3662,7 @@ test("REQUEST_UPDATE applies priority and preserves it when omitted", async () = test("REQUEST_UPDATE accepts delivery timeouts without changing the subscription", async () => { const fx = fixture(Version.DRAFT_18); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client } = await runSubscribe( fx, new Subscribe({ @@ -3681,7 +3688,7 @@ test("REQUEST_UPDATE accepts delivery timeouts without changing the subscription test("TRACK_PROPERTY_FILTER on a subscription update closes with PROTOCOL_VIOLATION", async () => { const fx = fixture(Version.DRAFT_18); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const client = await Stream.open(fx.pair.client, { version: fx.version }); const server = await Stream.accept(fx.pair.server, fx.version); if (!server) throw new Error("missing subscribe stream"); @@ -3717,7 +3724,7 @@ test("TRACK_PROPERTY_FILTER on a subscription update closes with PROTOCOL_VIOLAT test("unsupported REQUEST_UPDATE is refused and ends with UPDATE_FAILED", async () => { const fx = fixture(Version.DRAFT_18); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client } = await runSubscribe( fx, new Subscribe({ @@ -3749,7 +3756,7 @@ test("unsupported REQUEST_UPDATE is refused and ends with UPDATE_FAILED", async test("a SUBSCRIBE pauses without demand and resumes as a new subscriber", async () => { for (const startPaused of [false, true]) { const fx = fixture(V22); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const write = (text: string) => { const group = hooks.appendNext(track); group.writeFrame({ @@ -3813,8 +3820,8 @@ test("a SUBSCRIBE pauses without demand and resumes as a new subscriber", async test("a paused relay subscription reacquires its upstream datagrams", async () => { const source = new OriginProducer(); const route = source.route(Path.from("test")); - const track = route.broadcast.createTrack("audio", {}); - const datagrams = route.broadcast.createDatagrams("audio", {}); + const track = defined(route.broadcast.createTrack("audio", {})); + const datagrams = defined(route.broadcast.createDatagrams("audio", {})); const upstream = createMockTransportPair(ALPN.DRAFT_18); const url = new URL("https://localhost/resume"); const peers = await Promise.all([ @@ -3884,7 +3891,7 @@ test.each(["writable", "createWritable"] as const)( "concurrent IETF subscriptions share the %s datagram transport", async (datagramWritable) => { const fx = fixture(V22, undefined, createMockTransportPair(ALPN.DRAFT_22, { datagramWritable })); - const producers = ["audio", "video"].map((name) => fx.broadcast.createDatagrams(name, {})); + const producers = ["audio", "video"].map((name) => defined(fx.broadcast.createDatagrams(name, {}))); const received = fx.pair.client.datagrams.readable.getReader(); const clients: Stream[] = []; try { @@ -3931,7 +3938,7 @@ test("a paused IETF subscription leaves a blocked datagram write", async () => { }), }); const fx = fixture(V22, undefined, pair); - const datagrams = fx.broadcast.createDatagrams("audio", {}); + const datagrams = defined(fx.broadcast.createDatagrams("audio", {})); const { client } = await runSubscribe( fx, new Subscribe({ @@ -3963,7 +3970,7 @@ test("a paused IETF subscription leaves a blocked datagram write", async () => { test("a datagram-only SUBSCRIBE releases demand on pause and resumes", async () => { for (const startPaused of [false, true]) { const fx = fixture(V22); - const datagrams = fx.broadcast.createDatagrams("audio", {}); + const datagrams = defined(fx.broadcast.createDatagrams("audio", {})); const received = fx.pair.client.datagrams.readable.getReader(); const { client } = await runSubscribe( fx, @@ -4012,7 +4019,7 @@ test("a datagram-only SUBSCRIBE releases demand on pause and resumes", async () test("a paused SUBSCRIBE ends once its grant is revoked", async () => { const grant = new Signal(undefined); const fx = fixture(V22, grant); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client } = await runSubscribe( fx, new Subscribe({ @@ -4068,7 +4075,7 @@ test("a pause resets a group stream parked on flow control", async () => { const fx = fixture(V22); const { stream: stalled, parked, state } = stalledStream(); spyOn(fx.pair.server, "createUnidirectionalStream").mockImplementationOnce(async () => stalled); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client } = await runSubscribe( fx, new Subscribe({ @@ -4102,7 +4109,7 @@ test("draft-22: narrowing resets a group stream parked on flow control", async ( const fx = fixture(V22); const { stream: stalled, parked, aborted } = stalledStream(); spyOn(fx.pair.server, "createUnidirectionalStream").mockImplementationOnce(async () => stalled); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client } = await runSubscribe( fx, new Subscribe({ @@ -4264,7 +4271,7 @@ test.each([0, Number.MAX_SAFE_INTEGER + 2])( test("draft-22: a range update replaces the live subscription bounds", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const { client } = await runSubscribe( fx, new Subscribe({ @@ -4318,7 +4325,7 @@ test("draft-22: a range update replaces the live subscription bounds", async () test("IETF draft-18: range updates preserve the shared subscription", async () => { const fx = fixture(Version.DRAFT_18); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client } = await runSubscribe( fx, new Subscribe({ @@ -4349,7 +4356,7 @@ test("IETF draft-18: range updates preserve the shared subscription", async () = test("draft-22: an update fills its snapshot under its own request ID", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); for (let i = 0; i < 3; i++) writeGroup(track, 2); const { client } = await runSubscribe( fx, @@ -4397,7 +4404,7 @@ test("draft-22: an update fills its snapshot under its own request ID", async () test("draft-22: an empty newer group is not an object in Largest or a relative fill", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); writeGroup(track, 2); const empty = hooks.appendNext(track); const { client, ok } = await runSubscribe( @@ -4430,7 +4437,7 @@ test("draft-22: an empty newer group is not an object in Largest or a relative f test("draft-22: reported Largest survives absent headers, older cache entries, and eviction", async () => { using clock = manual(); const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); hooks.reportedLargest(track, { group: 4n, frame: 3 }, false); const { client, ok } = await runSubscribe( fx, @@ -4468,7 +4475,7 @@ test("draft-22: reported Largest survives absent headers, older cache entries, a test("draft-22: Next Object behind an upstream group report still delivers its first object", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); // What an IETF SUBSCRIBE_OK leaves on a cold copy: the group, but no frame it can name. hooks.reportedGroup(track, 0n); const { client, ok } = await runSubscribe( @@ -4501,7 +4508,7 @@ test("draft-22: Next Object behind an upstream group report still delivers its f test("draft-22: Next Object on an empty group still delivers its first object", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = hooks.appendNext(track); const { client, ok } = await runSubscribe( fx, @@ -4545,7 +4552,7 @@ test("draft-22: cancellation releases a fill parked on flow control", async () = }, }); spyOn(fx.pair.server, "createUnidirectionalStream").mockImplementationOnce(async () => stalled); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); writeGroup(track, 1); const { client } = await runSubscribe( fx, @@ -4576,7 +4583,7 @@ test("draft-22: cancellation releases a fill parked on flow control", async () = // and wire 191 is outside the model's -128..=127, so the fork throws and the fill never runs. test("draft-22: a SUBSCRIBE's fill reads the cache at the converted subscriber priority", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); writeGroup(track, 2); const { client } = await runSubscribe( fx, @@ -4616,7 +4623,7 @@ test("draft-22: an update's fill reads the cache at the converted subscriber pri return new Promise(() => {}); }, }); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); writeGroup(track, 1); const { client } = await runSubscribe( fx, @@ -4654,7 +4661,7 @@ test("draft-22: an update's fill reads the cache at the converted subscriber pri test("draft-22: narrowing gives up an excluded group's open stream", async () => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const open = hooks.appendNext(track); open.writeFrame({ payload: new Uint8Array([1]), timestamp: Timestamp.fromMillis(Number(open.start)) }); const { client } = await runSubscribe( @@ -4699,7 +4706,7 @@ test("draft-22: an update reopening a drained subscription serves its tail", asy await credit.promise; return createUni(options); }); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const open = hooks.appendNext(track); open.writeFrame({ payload: new TextEncoder().encode("head"), timestamp: Timestamp.now() }); const { client } = await runSubscribe( @@ -4743,7 +4750,7 @@ test("draft-22: an update reopening a drained subscription serves its tail", asy test("draft-22: widening with a fill keeps the open live group", async () => { using clock = manual(); const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); writeGroup(track, 1); const open = hooks.appendNext(track); open.writeFrame({ payload: new TextEncoder().encode("1.0"), timestamp: Timestamp.fromMillis(Number(open.start)) }); @@ -4786,7 +4793,7 @@ test("draft-22: widening with a fill keeps the open live group", async () => { test("draft-22: a fill-only update short of the edge keeps the live join's floor", async () => { using clock = manual(); const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); writeGroup(track, 1); const open = hooks.appendNext(track); open.writeFrame({ payload: new TextEncoder().encode("1.0"), timestamp: Timestamp.fromMillis(Number(open.start)) }); @@ -4832,7 +4839,7 @@ test("draft-22: a fill-only update short of the edge keeps the live join's floor test("draft-22: a fill-only update keeps the subscription's floor", async () => { using clock = manual(); const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); writeGroup(track, 1); const open = hooks.appendNext(track); open.writeFrame({ payload: new TextEncoder().encode("1.0"), timestamp: Timestamp.fromMillis(Number(open.start)) }); @@ -4876,7 +4883,7 @@ test.each([ [1n, 1n], ])("draft-22: widening with a fill resumes a group a narrowing to %p.%p gave up", async (group, object) => { const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); writeGroup(track, 1); const open = hooks.appendNext(track); open.writeFrame({ payload: new TextEncoder().encode("1.0"), timestamp: Timestamp.fromMillis(Number(open.start)) }); @@ -4934,7 +4941,7 @@ async function readServed( test("a SUBSCRIBE carries no budget, so the publisher's own policy bounds it", async () => { const fx = fixture(Version.DRAFT_18); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI })); const { client } = await runSubscribe( fx, new Subscribe({ @@ -4964,7 +4971,7 @@ for (const endObject of [BigInt(Number.MAX_SAFE_INTEGER), (1n << 60n) + 1n]) { test(`an IETF filter ending at object ${endObject} serves bounded model frames`, async () => { using _clock = manual(); const fx = fixture(); - const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const { client } = await runSubscribe( fx, new Subscribe({ diff --git a/js/net/src/ietf/subscriber.ts b/js/net/src/ietf/subscriber.ts index 1dc58c647f7..7809b78a228 100644 --- a/js/net/src/ietf/subscriber.ts +++ b/js/net/src/ietf/subscriber.ts @@ -2329,7 +2329,7 @@ export class Subscriber { #bindDatagrams(source: broadcast.Consumer, track: track.Producer, info: Partial) { const pending = this.#datagramRequests.get(source); const entry = pending?.get(track.name); - let producer: datagram.Producer; + let producer: datagram.Producer | undefined; try { producer = entry ? entry.request.accept(info) : wireOf(source).createDatagrams(track.name, info, false); } catch (err) { @@ -2337,6 +2337,8 @@ export class Subscriber { console.debug(`serving the stream track without datagrams: ${reason(err)}`); return; } + // A live datagram track already holds the name. + if (!producer) return; pending?.delete(track.name); entry?.accepted.set(true); let held: track.Subscriber | undefined; diff --git a/js/net/src/integration.test.ts b/js/net/src/integration.test.ts index d731b5d6222..bf131cbc76d 100644 --- a/js/net/src/integration.test.ts +++ b/js/net/src/integration.test.ts @@ -12,6 +12,7 @@ import { connect as connectSession, type Session, } from "./connection/index.ts"; +import { defined } from "./defined.test-util.ts"; import { SessionCode, SessionError, StreamCode, StreamError, TooFarBehind } from "./error.ts"; import * as Ietf from "./ietf/index.ts"; import { Publisher as IetfPublisher } from "./ietf/publisher.ts"; @@ -342,7 +343,7 @@ test("integration: lite applies initial and updated group bounds", async () => { ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); for (let key = 0n; key < GROUP_COUNT; key++) hooks.appendNext(producer).finish(); const remote = wireOf(client).consume(Path.from("test")); @@ -398,7 +399,7 @@ test("integration: lite refuses an empty requested range on open and on update", ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); for (let key = 0; key < GROUP_COUNT; key++) hooks.appendNext(producer).finish(); const remote = wireOf(client).consume(Path.from("test")); @@ -452,7 +453,7 @@ test("integration: lite-07 serves sparse and relative ranges", async () => { ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); for (let key = 0; key < 10; key++) hooks.appendNext(producer).finish(); const remote = wireOf(client).consume(Path.from("test")); @@ -497,7 +498,7 @@ test("integration: lite-07 reports a relative start over a frameless newest grou ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { maxAge: null }); + const producer = defined(broadcast.createTrack("video", { maxAge: null })); for (let key = 0; key < 5; key++) { const group = hooks.appendNext(producer); group.writeFrame({ payload: new Uint8Array([key]), timestamp: Timestamp.unscaled(group.start) }); @@ -539,7 +540,7 @@ test("integration: lite-07 joins a late relative start at the live edge", async ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); hooks.appendNext(producer).finish(); const remote = wireOf(client).consume(Path.from("test")); @@ -586,7 +587,7 @@ test("integration: lite-07 keeps a covered bounded subscription open", async () ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); for (const key of [0n, 1n, 2n, 4n, 5n]) producer.createGroup(key).finish(); const remote = wireOf(client).consume(Path.from("test")); @@ -638,7 +639,7 @@ test("integration: lite-07 serves a time range", async () => { ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); // Keyed by start, as the wire names a group: one per second. for (let start = 0n; start < 10_000n; start += 1000n) { const group = producer.createGroup(start); @@ -854,7 +855,7 @@ test("integration: a group reset carries the peer's code to the subscriber", asy ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const remote = wireOf(client).consume(Path.from("test")); const track = remote.track("video").subscribe().ordered(); @@ -894,7 +895,7 @@ test("integration: a locally raised group error reaches the peer as its own code ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const remote = wireOf(client).consume(Path.from("test")); const track = remote.track("video").subscribe().ordered(); @@ -997,7 +998,7 @@ test("integration: lite draft-07 fetches a cached group", async () => { ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const group0 = hooks.appendNext(producer); group0.writeFrame({ payload: enc.encode("alpha"), timestamp: Timestamp.fromMillis(10) }); @@ -1038,7 +1039,7 @@ test.each(["gap", "end"])("integration: lite fetch rejects coalesced misses at % const broadcast = publish(origin, Path.from("test")); let serving: Promise | undefined; if (missing === "gap") { - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = producer.createGroup(1n); group.finish(); } else { @@ -1083,7 +1084,7 @@ test.each(["frame", "FIN"])("integration: lite fetch waits for the publisher's f accept(pair.server, url, { publish: origin.consume() }), ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = hooks.appendNext(producer); const remote = wireOf(client).consume(Path.from("test")); try { @@ -1130,7 +1131,7 @@ test("integration: lite draft-05 coalesces concurrent fetches of one group", asy ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group0 = hooks.appendNext(producer); group0.writeFrame({ payload: enc.encode("alpha"), timestamp: Timestamp.fromMillis(10) }); @@ -1174,7 +1175,7 @@ test("integration: lite draft-07 fetches an in-progress group", async () => { ]); const broadcast = publish(origin, Path.from("test")); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); // Open the group and write one frame, but leave it open (in-progress). const group0 = hooks.appendNext(producer); @@ -1215,7 +1216,7 @@ test("integration: lite draft-07 track info follows a republished broadcast", as const path = Path.from("test"); const first = publish(origin, path); - first.createTrack("video", { priority: 1, timescale: Timescale.MILLI, maxAge: Duration.millis(1000) }); + defined(first.createTrack("video", { priority: 1, timescale: Timescale.MILLI, maxAge: Duration.millis(1000) })); const remote = wireOf(client).consume(path); const before = await remote.track("video").info(); @@ -1226,7 +1227,7 @@ test("integration: lite draft-07 track info follows a republished broadcast", as // Replace the broadcast on the same path with one whose track declares different // immutable properties. const second = publish(origin, path); - second.createTrack("video", { priority: 7, timescale: Timescale.MICRO, maxAge: Duration.millis(5000) }); + defined(second.createTrack("video", { priority: 7, timescale: Timescale.MICRO, maxAge: Duration.millis(5000) })); const after = await remote.track("video").info(); expect(after.priority).toBe(7); @@ -1257,9 +1258,11 @@ test.each([Lite.ALPN_03, Lite.ALPN_05, Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_22])( const path = Path.from("test"); const broadcast = publish(origin, path); const tracks = { - omitted: broadcast.createTrack("omitted", { timescale: Timescale.MILLI }), - unlimited: broadcast.createTrack("unlimited", { timescale: Timescale.MILLI, maxAge: null }), - explicit: broadcast.createTrack("explicit", { timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }), + omitted: defined(broadcast.createTrack("omitted", { timescale: Timescale.MILLI })), + unlimited: defined(broadcast.createTrack("unlimited", { timescale: Timescale.MILLI, maxAge: null })), + explicit: defined( + broadcast.createTrack("explicit", { timescale: Timescale.MILLI, maxAge: Duration.millis(5000) }), + ), }; expect((await tracks.omitted.info()).maxAge).toEqual(Duration.ZERO); expect((await tracks.unlimited.info()).maxAge).toBeNull(); @@ -1300,7 +1303,7 @@ test("integration: lite draft-07 fetch uses the republished track's timescale", const path = Path.from("test"); const first = publish(origin, path); - const firstTrack = first.createTrack("video", { timescale: Timescale.MILLI }); + const firstTrack = defined(first.createTrack("video", { timescale: Timescale.MILLI })); const firstGroup = hooks.appendNext(firstTrack); firstGroup.writeFrame({ payload: enc.encode("alpha"), timestamp: Timestamp.fromMillis(10) }); firstGroup.finish(); @@ -1310,7 +1313,7 @@ test("integration: lite draft-07 fetch uses the republished track's timescale", expect((await remote.track("video").info()).timescale).toBe(Timescale.MILLI); const second = publish(origin, path); - const secondTrack = second.createTrack("video", { timescale: Timescale.MICRO }); + const secondTrack = defined(second.createTrack("video", { timescale: Timescale.MICRO })); const secondGroup = hooks.appendNext(secondTrack); secondGroup.writeFrame({ payload: enc.encode("beta"), timestamp: Timestamp.fromMicros(1234) }); secondGroup.finish(); @@ -1429,7 +1432,7 @@ async function runSubscriberTeardown(protocol: string, version?: number) { ]); const broadcast = publish(origin, Path.from("test")); - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); video.writeFrame(textFrame("hello")); const remote = wireOf(client).consume(Path.from("test")); @@ -1469,7 +1472,7 @@ test("integration: lite fetch teardown when the reader abandons an open group", ]); const broadcast = publish(origin, Path.from("test")); - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = hooks.appendNext(video); // deliberately left open: an indefinite group. group.writeFrame(textFrame("hello")); @@ -1509,7 +1512,7 @@ test("integration: lite fan-out keeps the upstream until the last subscriber lea ]); const broadcast = publish(origin, Path.from("test")); - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); video.writeFrame(textFrame("hello", Timestamp.fromMillis(0))); const remote = wireOf(client).consume(Path.from("test")); @@ -1546,7 +1549,7 @@ test("integration: lite re-subscribe re-opens the upstream after each teardown", ]); const broadcast = publish(origin, Path.from("test")); - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const remote = wireOf(client).consume(Path.from("test")); @@ -1577,7 +1580,7 @@ test("integration: lite coalesced fetch stays until every reader abandons the op ]); const broadcast = publish(origin, Path.from("test")); - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = hooks.appendNext(video); // open group.writeFrame(textFrame("hello")); @@ -1618,7 +1621,7 @@ test("integration: lite fetch re-armed by a late reader keeps every frame", asyn ]); const broadcast = publish(origin, Path.from("test")); - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const remote = wireOf(client).consume(Path.from("test")); for (let delay = 0; delay <= 12; delay++) { @@ -1659,7 +1662,7 @@ test("integration: lite fetch delivers every frame of a finite multi-frame group ]); const broadcast = publish(origin, Path.from("test")); - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = hooks.appendNext(video); const count = 50; for (let i = 0; i < count; i++) group.writeFrame(textFrame(`f${i}`)); @@ -2171,7 +2174,7 @@ test("origin: one origin on both directions consumes locally and never echoes", // The client publishes; consuming its own path through the shared origin is local, no wire. const mine = publish(shared, Path.from("from-client")); - mine.createTrack("chat", { timescale: Timescale.MILLI }); + defined(mine.createTrack("chat", { timescale: Timescale.MILLI })); const reader = shared.consume(); const loopback = await routed(reader, Path.from("from-client")); if (!loopback) throw new Error("expected a local route"); @@ -2690,7 +2693,7 @@ test("create then announce is discoverable on the wire", async () => { const announced = client.routes(); const broadcastRoute = origin.route(Path.from("later"), { hidden: true }); const broadcast = broadcastRoute.broadcast; - broadcast.createTrack("chat", { timescale: Timescale.MILLI }); + defined(broadcast.createTrack("chat", { timescale: Timescale.MILLI })); const pending = announced.next(); broadcastRoute.announce(); @@ -2713,7 +2716,7 @@ test.each([Lite.ALPN_06, Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_18, Ietf.ALPN.DRAFT_2 const consumer = new OriginProducer(); const handle = origin.claim(Path.empty()); const held = new BroadcastProducer(); - held.createTrack("chat", { timescale: Timescale.MILLI }).writeFrame(textFrame("hello")); + defined(held.createTrack("chat", { timescale: Timescale.MILLI })).writeFrame(textFrame("hello")); const serving = (async () => { for await (const request of handle.requested()) request.serve(held.consume()); })(); @@ -3056,7 +3059,7 @@ test("integration: lite-07 drops a group reset to make room, and a FETCH reads i ]); const broadcast = publish(origin, Path.from("live")); // Kept, so the older group is never too old for the subscription. - const producer = broadcast.createTrack("0", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("0", { timescale: Timescale.MILLI, maxAge: null })); const remote = wireOf(client).consume(Path.from("live")); const subscriber = remote.track("0").subscribe({ order: "descending", delay: { max: Duration.millis(30_000) } }); try { @@ -3114,7 +3117,7 @@ for (const alpn of [Lite.ALPN_06, Lite.ALPN_07_WIP]) { accept(pair.server, url, { publish: origin.consume() }), ]); const broadcast = publish(origin, Path.from("live")); - const producer = broadcast.createTrack("0", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("0", { timescale: Timescale.MILLI, maxAge: null })); const remote = wireOf(client).consume(Path.from("live")); const subscriber = remote .track("0") diff --git a/js/net/src/listing.test.ts b/js/net/src/listing.test.ts index 283cad00fe9..c936ff951d8 100644 --- a/js/net/src/listing.test.ts +++ b/js/net/src/listing.test.ts @@ -1,6 +1,7 @@ import { expect, test } from "bun:test"; import { yieldNow } from "@moq/clock"; import { Producer as BroadcastProducer } from "./broadcast.ts"; +import { defined } from "./defined.test-util.ts"; import { NotFound, StreamCode, StreamError } from "./error.ts"; import type { Tracks } from "./listing.ts"; import type { Info } from "./track.ts"; @@ -60,8 +61,8 @@ function list(broadcast: BroadcastProducer): Events { test("tracks present arrive before synced", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("a"); - broadcast.createTrack("b"); + defined(broadcast.createTrack("a")); + defined(broadcast.createTrack("b")); expect(await list(broadcast).drain()).toEqual(["+a", "+b", "synced"]); }); @@ -69,40 +70,40 @@ test("an empty listing syncs at once", async () => { const broadcast = new BroadcastProducer(); const tracks = list(broadcast); expect(await tracks.drain()).toEqual(["synced"]); - broadcast.createTrack("a"); + defined(broadcast.createTrack("a")); expect(await tracks.drain()).toEqual(["+a"]); }); test("a listed track reports its info", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("a", { priority: 9, refresh: { ratio: 4 } }); + defined(broadcast.createTrack("a", { priority: 9, refresh: { ratio: 4 } })); const event = await broadcast.consume().tracks().next(); expect(event?.kind === "added" && event.info).toMatchObject({ priority: 9, refresh: { ratio: 4, interval: null } }); }); test("a datagram track is listed until it ends", async () => { const broadcast = new BroadcastProducer(); - const early = broadcast.createDatagrams("early", { priority: 4 }); + const early = defined(broadcast.createDatagrams("early", { priority: 4 })); const event = await broadcast.consume().tracks().next(); expect(event).toMatchObject({ kind: "added", name: "early", datagrams: true, info: { priority: 4 } }); const tracks = list(broadcast); expect(await tracks.drain()).toEqual(["+d:early", "synced"]); - const late = broadcast.createDatagrams("late"); + const late = defined(broadcast.createDatagrams("late")); expect(await tracks.drain()).toEqual(["+d:late"]); early.finish(); late.abort(new Error("aborted")); expect(await tracks.drain()).toEqual(["~d:early", "-d:late"]); // A name ended is free for a new track, listed afresh. - broadcast.createDatagrams("early"); + defined(broadcast.createDatagrams("early")); expect(await tracks.drain()).toEqual(["+d:early"]); }); test("the two kinds of a name are listed apart", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("a"); - const datagrams = broadcast.createDatagrams("a"); + defined(broadcast.createTrack("a")); + const datagrams = defined(broadcast.createDatagrams("a")); const tracks = list(broadcast); expect(await tracks.drain()).toEqual(["+a", "+d:a", "synced"]); broadcast.removeTrack("a"); @@ -129,16 +130,16 @@ test("a datagram track served on request is never listed", async () => { const tracks = new Events(consumer.tracks()); expect(await tracks.drain()).toEqual(["synced"]); consumer.datagrams("x"); - (await requested)?.accept({}); + defined((await requested)?.accept({})); // A session's datagram track riding a stream track's subscription is not listed either. - wireOf(broadcast).createDatagrams("y", {}, false); + defined(wireOf(broadcast).createDatagrams("y", {}, false)); expect(await tracks.drain()).toEqual([]); }); test("a track leaving the table is removed", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("a"); - const b = broadcast.createTrack("b"); + defined(broadcast.createTrack("a")); + const b = defined(broadcast.createTrack("b")); const tracks = list(broadcast); expect(await tracks.drain()).toEqual(["+a", "+b", "synced"]); broadcast.removeTrack("a"); @@ -148,7 +149,7 @@ test("a track leaving the table is removed", async () => { test("a finished track is listed while the table holds it", async () => { const broadcast = new BroadcastProducer(); - const a = broadcast.createTrack("a"); + const a = defined(broadcast.createTrack("a")); a.finish(); a.close(); const tracks = list(broadcast); @@ -162,8 +163,8 @@ test("a finished track is listed while the table holds it", async () => { test("a track that finished but stays open ends the listing as finished", async () => { const broadcast = new BroadcastProducer(); - const a = broadcast.createTrack("a"); - broadcast.createTrack("b"); + const a = defined(broadcast.createTrack("a")); + defined(broadcast.createTrack("b")); a.finish(); const tracks = list(broadcast); expect(await tracks.drain()).toEqual(["+a", "+b", "synced"]); @@ -187,13 +188,13 @@ test("a lister finishes or removes a track", async () => { test("a recreated track leaves as it ended before it is added again", async () => { const broadcast = new BroadcastProducer(); - const a = broadcast.createTrack("a"); + const a = defined(broadcast.createTrack("a")); a.finish(); a.close(); const tracks = list(broadcast); expect(await tracks.drain()).toEqual(["+a", "synced"]); // The finished track still holds the name; its replacement takes it over. - broadcast.createTrack("a"); + defined(broadcast.createTrack("a")); expect(await tracks.drain()).toEqual(["~a", "+a"]); }); @@ -211,15 +212,15 @@ test("a track served on request is never listed", async () => { // A queued request answered by createTrack is the producer's track, so it is listed. consumer.track("z").subscribe(); - broadcast.createTrack("z"); + defined(broadcast.createTrack("z")); expect(await tracks.drain()).toEqual(["+z"]); broadcast.close(); }); test("an initial track removed before it is read is omitted", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("a"); - broadcast.createTrack("b"); + defined(broadcast.createTrack("a")); + defined(broadcast.createTrack("b")); const tracks = list(broadcast); broadcast.removeTrack("a"); expect(await tracks.drain()).toEqual(["+b", "synced"]); @@ -227,23 +228,23 @@ test("an initial track removed before it is read is omitted", async () => { test("churn never postpones synced", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("a"); - broadcast.createTrack("b"); + defined(broadcast.createTrack("a")); + defined(broadcast.createTrack("b")); const tracks = broadcast.consume().tracks(); // New names keep arriving faster than the reader drains them. - broadcast.createTrack("c"); + defined(broadcast.createTrack("c")); expect(await tracks.next()).toMatchObject({ kind: "added", name: "a" }); - broadcast.createTrack("d"); + defined(broadcast.createTrack("d")); expect(await tracks.next()).toMatchObject({ kind: "added", name: "b" }); - broadcast.createTrack("e"); + defined(broadcast.createTrack("e")); expect(await new Events(tracks).drain()).toEqual(["synced", "+c", "+d", "+e"]); }); test("a removal of a seen track may precede synced", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("a"); - broadcast.createTrack("b"); - broadcast.createTrack("c"); + defined(broadcast.createTrack("a")); + defined(broadcast.createTrack("b")); + defined(broadcast.createTrack("c")); const tracks = broadcast.consume().tracks(); expect(await tracks.next()).toMatchObject({ kind: "added", name: "a" }); broadcast.removeTrack("a"); @@ -253,14 +254,14 @@ test("a removal of a seen track may precede synced", async () => { test("a stalled reader holds one change per name", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("seen"); - broadcast.createTrack("stay"); + defined(broadcast.createTrack("seen")); + defined(broadcast.createTrack("stay")); const tracks = list(broadcast); expect(await tracks.drain()).toEqual(["+seen", "+stay", "synced"]); broadcast.removeTrack("seen"); for (let round = 0; round < 1000; round++) { - broadcast.createTrack(`churn${round}`); - broadcast.createTrack("seen"); + defined(broadcast.createTrack(`churn${round}`)); + defined(broadcast.createTrack("seen")); broadcast.removeTrack(`churn${round}`); broadcast.removeTrack("seen"); } @@ -269,7 +270,7 @@ test("a stalled reader holds one change per name", async () => { test("the broadcast ending ends the listing", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("a"); + defined(broadcast.createTrack("a")); const consumer = broadcast.consume(); const tracks = new Events(consumer.tracks()); broadcast.close(); @@ -281,16 +282,16 @@ test("the broadcast ending ends the listing", async () => { // saw; an error ends at once. test("a clean end follows the removals before it", async () => { const broadcast = new BroadcastProducer(); - const a = broadcast.createTrack("a"); - broadcast.createTrack("b"); - const live = broadcast.createTrack("live"); + const a = defined(broadcast.createTrack("a")); + defined(broadcast.createTrack("b")); + const live = defined(broadcast.createTrack("live")); const tracks = list(broadcast); expect(await tracks.drain()).toEqual(["+a", "+b", "+live", "synced"]); a.finish(); a.close(); broadcast.removeTrack("a"); broadcast.removeTrack("b"); - broadcast.createTrack("unseen"); + defined(broadcast.createTrack("unseen")); live.finish(); live.close(); broadcast.close(); @@ -301,7 +302,7 @@ test("a clean end follows the removals before it", async () => { const handler = wireOf(both).lister(); handler.add("a", { info: INFO }); handler.synced(); - const own = both.createTrack("a"); + const own = defined(both.createTrack("a")); const served = list(both); expect(await served.drain()).toEqual(["+a", "synced"]); own.finish(); @@ -311,7 +312,7 @@ test("a clean end follows the removals before it", async () => { // A reader that closes itself reads nothing more, even what was queued before the end. const closing = new BroadcastProducer(); - const gone = closing.createTrack("gone"); + const gone = defined(closing.createTrack("gone")); const reader = list(closing); expect(await reader.drain()).toEqual(["+gone", "synced"]); gone.finish(); @@ -341,19 +342,19 @@ test("a clean end follows the removals before it", async () => { test("a closed listing reads nothing more, and leaving a loop early closes it", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("a"); + defined(broadcast.createTrack("a")); const tracks = broadcast.consume().tracks(); for await (const event of tracks) { expect(event).toMatchObject({ kind: "added", name: "a" }); break; } - broadcast.createTrack("b"); + defined(broadcast.createTrack("b")); expect(await tracks.next()).toBeUndefined(); }); test("readers wait for the lister to sync", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("own"); + defined(broadcast.createTrack("own")); const lister = wireOf(broadcast).lister(); expect(lister.wanted.peek()).toBe(false); @@ -375,7 +376,7 @@ test("readers wait for the lister to sync", async () => { test("a name listed by both is reported once", async () => { const broadcast = new BroadcastProducer(); - broadcast.createTrack("a"); + defined(broadcast.createTrack("a")); const lister = wireOf(broadcast).lister(); lister.add("a", { info: INFO }); lister.synced(); @@ -434,7 +435,7 @@ test("a closed lister answers nothing more, even beside its successor", async () test("an owner lists each broadcast once", async () => { const broadcast = new BroadcastProducer(); const other = new BroadcastProducer(); - broadcast.createTrack("a"); + defined(broadcast.createTrack("a")); const owner = {}; const older = new Events(wireOf(broadcast).tracks(owner)); const elsewhere = new Events(wireOf(other).tracks(owner)); @@ -447,7 +448,7 @@ test("an owner lists each broadcast once", async () => { // The replaced reader leaving releases nothing of the newer one's. older.tracks.close(); - broadcast.createTrack("b"); + defined(broadcast.createTrack("b")); expect(await newer.drain()).toEqual(["+b"]); newer.tracks.close(); stranger.tracks.close(); @@ -480,8 +481,8 @@ test("an ended answer ends its readers and a later reader asks again", async () test("a cleared answer unsyncs a reader still waiting", async () => { const broadcast = new BroadcastProducer(); const lister = wireOf(broadcast).lister(); - broadcast.createTrack("a"); - broadcast.createTrack("b"); + defined(broadcast.createTrack("a")); + defined(broadcast.createTrack("b")); lister.synced(); const tracks = broadcast.consume().tracks(); expect(await tracks.next()).toMatchObject({ kind: "added", name: "a" }); diff --git a/js/net/src/lite/compression.test.ts b/js/net/src/lite/compression.test.ts index ca83b15f58b..721e1394fc3 100644 --- a/js/net/src/lite/compression.test.ts +++ b/js/net/src/lite/compression.test.ts @@ -3,6 +3,7 @@ import { Duration } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import { accept } from "../connection/accept.ts"; import { connect } from "../connection/connect.ts"; +import { defined } from "../defined.test-util.ts"; import { hooks } from "../internal.ts"; import { createMockTransportPair } from "../mock.ts"; import { Producer } from "../origin.ts"; @@ -18,8 +19,8 @@ for (const downstream of [ALPN_06, ALPN_07_WIP]) { const destination = new Producer(); const broadcastRoute = source.route(Path.from("compressed"), { hidden: true }); const broadcast = broadcastRoute.broadcast; - const datagrams = broadcast.createDatagrams("data"); - const track = broadcast.createTrack("data", { compression: "deflate" }); + const datagrams = defined(broadcast.createDatagrams("data")); + const track = defined(broadcast.createTrack("data", { compression: "deflate" })); broadcastRoute.announce(); const peers: { abort(): void }[] = []; async function link(publish: Producer, consume: Producer, alpn: string) { diff --git a/js/net/src/lite/connection.test.ts b/js/net/src/lite/connection.test.ts index a8a17a49203..ffbd136ce27 100644 --- a/js/net/src/lite/connection.test.ts +++ b/js/net/src/lite/connection.test.ts @@ -5,6 +5,7 @@ import { Session as Qmux } from "@moq/qmux"; import { accept } from "../connection/accept.ts"; import { connect } from "../connection/connect.ts"; import { inspect } from "../connection/stats.ts"; +import { defined } from "../defined.test-util.ts"; import { SessionCode, SessionError } from "../error.ts"; import { hooks } from "../internal.ts"; import { createMockTransportPair, type MockTransport, manual, settlesWithin, textFrame } from "../mock.ts"; @@ -354,7 +355,7 @@ for (const [alpn, version] of [ const origin = new Producer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const url = new URL("https://localhost/test"); const client = new Connection({ url, quic: pair.client, version }); const server = new Connection({ url, quic: pair.server, version, publish: origin.consume(), client: false }); @@ -413,7 +414,7 @@ for (const [alpn, version] of [ const origin = new Producer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const url = new URL("https://localhost/test"); const client = new Connection({ url, quic: pair.client, version }); const server = new Connection({ @@ -480,7 +481,7 @@ for (const [alpn, version] of [ const origin = new Producer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const url = new URL("https://localhost/test"); const client = new Connection({ url, quic: pair.client, version }); const server = new Connection({ @@ -531,7 +532,7 @@ for (const [alpn, version] of [ const origin = new Producer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const url = new URL("https://localhost/test"); const client = new Connection({ url, quic: pair.client, version }); const server = new Connection({ @@ -575,7 +576,7 @@ for (const [alpn, version] of [ const origin = new Producer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const url = new URL("https://localhost/test"); const client = new Connection({ url, quic: pair.client, version }); const server = new Connection({ @@ -615,7 +616,7 @@ async function servedRawSubscription(alpn: string = ALPN_07_WIP, version: Versio const origin = new Producer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const server = new Connection({ url: new URL("https://relay.example/"), quic: pair.server, @@ -733,7 +734,7 @@ test("close waits for a served FETCH to be acknowledged", async () => { const origin = new Producer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = hooks.appendNext(producer); group.writeFrame(textFrame("last", Timestamp.fromMillis(Number(group.start)))); group.finish(); @@ -786,7 +787,7 @@ test("close waits for a request served while withdrawals are in flight", async ( const destination = new Producer(); const broadcastRoute = source.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = hooks.appendNext(producer); group.writeFrame(textFrame("last", Timestamp.fromMillis(Number(group.start)))); group.finish(); diff --git a/js/net/src/lite/copy_fill.test.ts b/js/net/src/lite/copy_fill.test.ts index 2fcab947259..8f5f69f0c47 100644 --- a/js/net/src/lite/copy_fill.test.ts +++ b/js/net/src/lite/copy_fill.test.ts @@ -8,6 +8,7 @@ import { Duration, Elapsed, sleep, timeout } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import { DEFAULT_EXPIRY } from "../cache.ts"; import { accept as acceptSession, connect as connectSession } from "../connection/index.ts"; +import { defined } from "../defined.test-util.ts"; import { StreamCode, StreamError } from "../error.ts"; import type { Consumer as GroupConsumer } from "../group.ts"; import { hooks } from "../internal.ts"; @@ -37,7 +38,7 @@ async function peers(alpn: string) { ]); const publication = origin.route(Path.from("room")); const broadcast = publication.broadcast; - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const requests = track.requests(); void (async () => { for (let fill = await requestedGroups(requests); fill; fill = await requestedGroups(requests)) { @@ -46,7 +47,7 @@ async function peers(alpn: string) { fill.dropGroups(1n, 2n); continue; } - write(fill.accept(key), key, "old"); + write(defined(fill.accept(key)), key, "old"); } fill.close(); } @@ -250,7 +251,7 @@ test("copy fill: a filled group stops downloading once every reader left or pass acceptSession({ transport: pair.server, url, publish: origin.consume() }), ]); const publication = origin.route(Path.from("room")); - const track = publication.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(publication.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); write(track.createGroup(1n), 1n, "live"); // The archive answers group 0 with one frame and keeps it open. const requests = track.requests(); @@ -259,7 +260,7 @@ test("copy fill: a filled group stops downloading once every reader left or pass const fill = await requestedGroups(requests); if (fill?.kind !== "groups") throw new Error("no fill of groups"); fills.push(fill); - const group = fill.accept(0n); + const group = defined(fill.accept(0n)); group.writeFrame({ payload: enc.encode("old 0"), timestamp: Timestamp.fromMillis(0) }); return group; })(); @@ -317,7 +318,7 @@ test("copy fill: a filled group nobody holds any more stops downloading", async acceptSession({ transport: pair.server, url, publish: origin.consume() }), ]); const publication = origin.route(Path.from("room")); - const track = publication.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(publication.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); write(track.createGroup(1n), 1n, "live"); // The archive answers group 0 with one frame and never finishes it. const requests = track.requests(); @@ -326,7 +327,7 @@ test("copy fill: a filled group nobody holds any more stops downloading", async const fill = await requestedGroups(requests); if (fill?.kind !== "groups") throw new Error("no fill of groups"); fills.push(fill); - const group = fill.accept(0n); + const group = defined(fill.accept(0n)); group.writeFrame({ payload: enc.encode("old 0"), timestamp: Timestamp.fromMillis(0) }); return group; })(); @@ -388,7 +389,7 @@ test("copy fill: a group reset to make room ends", async () => { acceptSession({ transport: pair.server, url, publish: origin.consume() }), ]); const publication = origin.route(Path.from("room")); - const track = publication.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(publication.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); write(track.createGroup(2n), 2n, "live"); // The archive answers group 0 with one frame and keeps it open, so its stream is still open, and // group 1 whole. @@ -398,9 +399,9 @@ test("copy fill: a group reset to make room ends", async () => { const fill = await requestedGroups(requests); if (fill?.kind !== "groups") throw new Error("no fill of groups"); fills.push(fill); - const group = fill.accept(0n); + const group = defined(fill.accept(0n)); group.writeFrame({ payload: enc.encode("old 0"), timestamp: Timestamp.fromMillis(0) }); - write(fill.accept(1n), 1n, "old"); + write(defined(fill.accept(1n)), 1n, "old"); return group; })(); const remote = wireOf(client).consume(Path.from("room")); @@ -491,7 +492,7 @@ test.each([Lite.ALPN_05, Lite.ALPN_06, Lite.ALPN_07_WIP])( acceptSession({ transport: pair.server, url, publish: origin.consume() }), ]); const broadcast = origin.route(Path.from("room")).broadcast; - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); write(track.createGroup(3n), 3n, "live"); // The archive has group 2 once `archived`, and never refuses it as lost. let archived = false; @@ -503,7 +504,7 @@ test.each([Lite.ALPN_05, Lite.ALPN_06, Lite.ALPN_07_WIP])( fill.refuseGroups(key, key + 1n, new StreamError(StreamCode.NotFound)); continue; } - const group = fill.accept(key); + const group = defined(fill.accept(key)); for (let frame = 0; frame < 5; frame++) group.writeFrame({ payload: enc.encode(`c${frame}`), timestamp: Timestamp.fromMillis(2000) }); group.finish(); diff --git a/js/net/src/lite/datagram-tracks.test.ts b/js/net/src/lite/datagram-tracks.test.ts index a7eea3b7d1d..d14309c1da1 100644 --- a/js/net/src/lite/datagram-tracks.test.ts +++ b/js/net/src/lite/datagram-tracks.test.ts @@ -3,6 +3,7 @@ import * as clock from "@moq/clock"; import { yieldNow } from "@moq/clock"; import { Signal } from "@moq/signals"; import { accept, connect } from "../connection/index.ts"; +import { defined } from "../defined.test-util.ts"; import { SessionCode } from "../error.ts"; import { hooks } from "../internal.ts"; import { createMockTransportPair, type MockTransport, manual } from "../mock.ts"; @@ -25,12 +26,14 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { using clock = manual(); const source = new Origin(); const publication = source.route(path, { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio", { - timescale: Timescale.MICRO, - priority: -7, - }); + const datagrams = defined( + publication.broadcast.createDatagrams("audio", { + timescale: Timescale.MICRO, + priority: -7, + }), + ); const track = streams - ? publication.broadcast.createTrack("audio", { timescale: Timescale.MILLI }) + ? defined(publication.broadcast.createTrack("audio", { timescale: Timescale.MILLI })) : undefined; publication.announce(); const pair = createMockTransportPair(alpn); @@ -116,10 +119,10 @@ test("lite-04 refuses datagram tracks at setup", async () => { test("lite-07 bounds and prioritizes independent createWritable datagram queues", async () => { const source = new Origin(); const publication = source.route(path, { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio"); - publication.broadcast.createTrack("audio", { compression: "deflate" }); + const datagrams = defined(publication.broadcast.createDatagrams("audio")); + defined(publication.broadcast.createTrack("audio", { compression: "deflate" })); publication.announce(); - const other = publication.broadcast.createDatagrams("other", { priority: 7 }); + const other = defined(publication.broadcast.createDatagrams("other", { priority: 7 })); const pair = createMockTransportPair(ALPN_07_WIP, { datagramWritable: "createWritable" }); Object.defineProperty(pair.server.datagrams, "maxDatagramSize", { value: 900 }); const [client, server] = await Promise.all([ @@ -171,8 +174,8 @@ for (const alpn of [ALPN_05, ALPN_06]) test(`${alpn}: datagram readers rejoin and outlive streams (${first} first)`, async () => { const source = new Origin(); const publication = source.route(path, { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio"); - const track = publication.broadcast.createTrack("audio"); + const datagrams = defined(publication.broadcast.createDatagrams("audio")); + const track = defined(publication.broadcast.createTrack("audio")); publication.announce(); const pair = createMockTransportPair(alpn); const [client, server] = await Promise.all([ @@ -216,7 +219,7 @@ for (const alpn of [ALPN_05, ALPN_06]) test("lite-07 forwards a priority change made while the previous DATAGRAMS_UPDATE writes", async () => { const source = new Origin(); const publication = source.route(path, { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio"); + const datagrams = defined(publication.broadcast.createDatagrams("audio")); publication.announce(); const pair = createMockTransportPair(ALPN_07_WIP); const [client, server] = await Promise.all([ @@ -247,8 +250,8 @@ test("lite-07 forwards a priority change made while the previous DATAGRAMS_UPDAT test("lite-06: a request cancelled behind the shared datagram writer sends nothing", async () => { const source = new Origin(); const publication = source.route(path, { hidden: true }); - const first = publication.broadcast.createDatagrams("a"); - const second = publication.broadcast.createDatagrams("b"); + const first = defined(publication.broadcast.createDatagrams("a")); + const second = defined(publication.broadcast.createDatagrams("b")); publication.announce(); const pair = createMockTransportPair(ALPN_06); // The legacy API's one session queue, stalled on its first write. @@ -351,7 +354,7 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { using clock = manual(); const source = new Origin(); const publication = source.route(path, { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio"); + const datagrams = defined(publication.broadcast.createDatagrams("audio")); publication.announce(); const pair = createMockTransportPair(alpn); lagAnswers(pair.server, lag); @@ -395,7 +398,7 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { using clock = manual(); const source = new Origin(); const publication = source.route(path, { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio"); + const datagrams = defined(publication.broadcast.createDatagrams("audio")); publication.announce(); const pair = createMockTransportPair(alpn); const [client, server] = await Promise.all([ @@ -433,7 +436,7 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { const BURST = 64; const source = new Origin(); const publication = source.route(path, { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio"); + const datagrams = defined(publication.broadcast.createDatagrams("audio")); publication.announce(); const pair = createMockTransportPair(alpn); const [client, server] = await Promise.all([ @@ -478,7 +481,7 @@ for (const alpn of [ALPN_05, ALPN_06, ALPN_07_WIP]) { test(`${alpn}: a session close right after a datagram track's end keeps the end`, async () => { const source = new Origin(); const publication = source.route(path, { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio"); + const datagrams = defined(publication.broadcast.createDatagrams("audio")); publication.announce(); const pair = createMockTransportPair(alpn); const [client, server] = await Promise.all([ @@ -527,7 +530,7 @@ for (const [alpn, version] of [ test(`${alpn}: a duplicate SETUP after a datagram track's end keeps the end`, async () => { const source = new Origin(); const publication = source.route(path, { hidden: true }); - const datagrams = publication.broadcast.createDatagrams("audio"); + const datagrams = defined(publication.broadcast.createDatagrams("audio")); publication.announce(); const pair = createMockTransportPair(alpn); // Once armed, the publisher's FINs on the request streams it accepts never leave. @@ -636,7 +639,7 @@ function holdNextAnswer(transport: MockTransport): { arm(): void; release(): voi test("lite-07: an unanswered track's datagrams don't delay another track's last", async () => { const source = new Origin(); const publication = source.route(path, { hidden: true }); - const b = publication.broadcast.createDatagrams("b"); + const b = defined(publication.broadcast.createDatagrams("b")); // Answers "a" on demand. const requested = wireOf(publication.broadcast).requestedDatagrams(); publication.announce(); diff --git a/js/net/src/lite/drop_record.test.ts b/js/net/src/lite/drop_record.test.ts index 5fafc6aa838..d729b1c59f6 100644 --- a/js/net/src/lite/drop_record.test.ts +++ b/js/net/src/lite/drop_record.test.ts @@ -7,6 +7,7 @@ import { Duration, Elapsed, timeout } from "@moq/clock"; import type { Manual } from "@moq/clock/test"; import * as cache from "../cache.ts"; import { accept, connect } from "../connection/index.ts"; +import { defined } from "../defined.test-util.ts"; import { StreamCode, StreamError, toStreamCode } from "../error.ts"; import { hooks, type Recv, staleHole } from "../internal.ts"; import { createMockTransportPair, manual } from "../mock.ts"; @@ -133,7 +134,7 @@ async function chain(up: Version, down: Version) { for await (const request of claim.requested()) request.serve(wireOf(ingest).consume(request.path)); })(); const broadcast = source.route(path).broadcast; - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); hooks.poolTrack(track, new cache.Pool({})); const remote = wireOf(viewer).consume(path); diff --git a/js/net/src/lite/fills.test.ts b/js/net/src/lite/fills.test.ts index ddd08953dd5..3f947721c5d 100644 --- a/js/net/src/lite/fills.test.ts +++ b/js/net/src/lite/fills.test.ts @@ -4,6 +4,7 @@ import { expect, spyOn, test } from "bun:test"; import { yieldNow } from "@moq/clock"; import { Signal } from "@moq/signals"; import { Producer as BroadcastProducer } from "../broadcast.ts"; +import { defined } from "../defined.test-util.ts"; import { StreamCode, StreamError } from "../error.ts"; import { hooks, type Run } from "../internal.ts"; import { requestedGroups } from "../mock.ts"; @@ -18,7 +19,7 @@ const enc = new TextEncoder(); // reader asks of it. async function missing(): Promise<{ broadcast: BroadcastProducer; track: Producer; fill: FillGroups; close(): void }> { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); const group = track.createGroup(4n); group.writeFrame({ payload: enc.encode("live 4"), timestamp: Timestamp.unscaled(group.start) }); group.finish(); @@ -135,7 +136,7 @@ test("range fills: a stale drop of asked groups is recovered once, on a subscrip fills.poll(tail, true); expect(opened.length).toBe(1); expect(peer.fill.wanted()).toBe(0n); - peer.fill.accept(0n).finish(); + defined(peer.fill.accept(0n)).finish(); fills.poll(tail, true); // Refused for this fill, which moves on past them. expect(peer.fill.wanted()).toBe(3n); @@ -160,7 +161,8 @@ test("range fills: the last recovery finishing reports the fills empty", async ( // Every group arrives while a stream of the recovery is still read, which keeps it. recovery.reading = true; - for (let key = peer.fill.wanted(); key !== undefined; key = peer.fill.wanted()) peer.fill.accept(key).finish(); + for (let key = peer.fill.wanted(); key !== undefined; key = peer.fill.wanted()) + defined(peer.fill.accept(key)).finish(); expect(fills.poll(tail, true)).toBe(true); expect(fills.ask.groups).toEqual([]); expect(fills.isEmpty()).toBe(false); @@ -195,7 +197,7 @@ test("range fills: a recovery's refusals stand until the fill reaches them", asy // The fill still waits on group 0. expect(peer.fill.wanted()).toBe(0n); - peer.fill.accept(0n).finish(); + defined(peer.fill.accept(0n)).finish(); fills.poll(tail, true); expect(peer.fill.wanted()).toBe(3n); // Recorded as lost: a later reader is told so rather than waiting on them. @@ -337,7 +339,7 @@ test("range fills: a passing refusal ends with the fills it answered", async () fills.poll(tail, true); opened[0]?.finish([{ start: 1n, end: 3n, refusal: passing(new StreamError(StreamCode.Cancel)) }]); await yieldNow(); - peer.fill.accept(0n).finish(); + defined(peer.fill.accept(0n)).finish(); fills.poll(tail, true); expect(peer.fill.wanted()).toBe(3n); peer.fill.close(); @@ -381,7 +383,7 @@ test("range fills: a recovery's refusal answers before it is over", async () => fills.poll(tail, true); fills.refuse(1n, 3n, new StreamError(StreamCode.Old)); fills.poll(tail, true); - peer.fill.accept(0n).finish(); + defined(peer.fill.accept(0n)).finish(); fills.poll(tail, true); expect(peer.fill.wanted()).toBe(1n); @@ -411,7 +413,7 @@ test("range fills: a recovery's refusal is taken once", async () => { if (!recovery) throw new Error("no recovery"); // Still reading another of its streams, so it stays out with no fill owing it. recovery.reading = true; - peer.fill.accept(0n).finish(); + defined(peer.fill.accept(0n)).finish(); recovery.refuse({ start: 1n, end: 2n, refusal: passing(new StreamError(StreamCode.Cancel)) }); fills.poll(tail, true); expect(peer.fill.wanted()).toBe(2n); @@ -463,7 +465,7 @@ test("range fills: an older recovery ending keeps a newer one's coverage", async if (!older) throw new Error("no recovery"); // It refuses group 1 and keeps reading group 2, past the fill. older.reading = true; - peer.fill.accept(0n).finish(); + defined(peer.fill.accept(0n)).finish(); older.refuse({ start: 1n, end: 2n, refusal: passing(new StreamError(StreamCode.Cancel)) }); fills.poll(tail, true); peer.fill.close(); @@ -521,7 +523,7 @@ test("range fills: a stale drop repeated during its recovery waits on it", async fills.poll(tail, true); fills.refuse(1n, 3n, new StreamError(StreamCode.Old)); fills.poll(tail, true); - peer.fill.accept(0n).finish(); + defined(peer.fill.accept(0n)).finish(); fills.poll(tail, true); expect(peer.fill.wanted()).toBe(1n); diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index 3ff309467b2..5023bcb960c 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -4,6 +4,7 @@ import { Manual } from "@moq/clock/test"; import { Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; import { Producer as BroadcastProducer } from "../broadcast.ts"; +import { defined } from "../defined.test-util.ts"; import { fromTransport, ProtocolViolation, SessionCode, StreamCode, StreamError, toStreamCode } from "../error.ts"; import { Consumer as GroupConsumer, type Producer as GroupProducer } from "../group.ts"; import { randomHop } from "../hop.ts"; @@ -208,7 +209,7 @@ async function subscribeEnd( const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const client = await Stream.open(pair.client, { version }); const server = await Stream.accept(pair.server, version); @@ -278,11 +279,13 @@ async function groupSendOrders(options: { const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { - timescale: Timescale.MILLI, - priority: options.publisher, - maxAge: null, - }); + const track = defined( + broadcast.createTrack("video", { + timescale: Timescale.MILLI, + priority: options.publisher, + maxAge: null, + }), + ); const client = await Stream.open(pair.client, { version }); const server = await Stream.accept(pair.server, version); @@ -375,7 +378,7 @@ test("lite draft-05: a subscribe update re-ranks a group already on the wire", a const publisher = new Publisher(pair.server, Version.DRAFT_05, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const client = await Stream.open(pair.client, { version: Version.DRAFT_05 }); const server = await Stream.accept(pair.server, Version.DRAFT_05); @@ -426,7 +429,7 @@ test("lite draft-05: a subscribe update during the stream open still ranks the g const publisher = new Publisher(pair.server, Version.DRAFT_05, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); // Hold the group's stream open call until the test releases it. let release: () => void = () => {}; @@ -484,7 +487,7 @@ test("lite draft-05: many concurrent groups share one subscription listener", as const publisher = new Publisher(pair.server, Version.DRAFT_05, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const client = await Stream.open(pair.client, { version: Version.DRAFT_05 }); const server = await Stream.accept(pair.server, Version.DRAFT_05); @@ -536,7 +539,7 @@ test("lite draft-05: the fetch response ranks the publisher's own writes", async const publisher = new Publisher(pair.server, Version.DRAFT_05, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = track.createGroup(7n); group.writeFrame(textFrame("hello")); @@ -569,7 +572,7 @@ test.each([0, 5, 6, 7])("a fetched cached tail keeps absolute indices from %s", const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = hooks.receiveGroup(track, { start: 0n, offset: 5 }); for (const value of ["a", "b"]) group.writeFrame(textFrame(value)); group.finish(); @@ -615,7 +618,7 @@ test("lite draft-06: an unchecked track's fetched frames carry their own timesta const publisher = new Publisher(pair.server, Version.DRAFT_06, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MICRO, unchecked: true }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MICRO, unchecked: true })); const group = track.createGroup(0n); group.writeFrame(textFrame("hello", Timestamp.fromMillis(36_000_000))); @@ -739,7 +742,7 @@ async function servedSubscription( } // Unset is no publisher limit: these fixtures serve superseded groups. const info = { timescale: Timescale.MILLI, maxAge: options.maxAge ?? null }; - let track = options.pending ? undefined : broadcast.createTrack("video", info); + let track = options.pending ? undefined : defined(broadcast.createTrack("video", info)); for (const key of options.prefill ?? []) { if (!track) throw new Error("a pending track holds nothing to prefill"); const group = track.createGroup(key); @@ -2293,7 +2296,7 @@ test("lite draft-07: subscribe end precedes groups below a declared finish", asy const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_07, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const client = await Stream.open(pair.client, { version: Version.DRAFT_07 }); const server = await Stream.accept(pair.server, Version.DRAFT_07); @@ -2338,7 +2341,7 @@ test("lite draft-06: an errored end is not declared early", async () => { const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_06, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const client = await Stream.open(pair.client, { version: Version.DRAFT_06 }); const server = await Stream.accept(pair.server, Version.DRAFT_06); @@ -2395,7 +2398,7 @@ async function heldOpenEnd() { const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_07, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); let open!: (ok: boolean) => void; const opened = new Promise((resolve) => { @@ -2474,7 +2477,7 @@ test("lite draft-07: a group whose close fails is dropped", async () => { const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_07, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const createUni = pair.server.createUnidirectionalStream.bind(pair.server); spyOn(pair.server, "createUnidirectionalStream").mockImplementation(async (options) => { @@ -2521,7 +2524,7 @@ test("blocked DROP responses stop opening later groups", async () => { const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_07, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const client = await Stream.open(pair.client, { version: Version.DRAFT_07 }); const server = await Stream.accept(pair.server, Version.DRAFT_07); if (!server) throw new Error("missing subscribe stream"); @@ -2608,7 +2611,7 @@ async function serve( const publisher = new Publisher(pair.server, Version.DRAFT_06, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const client = await Stream.open(pair.client, { version: Version.DRAFT_06 }); const server = await Stream.accept(pair.server, Version.DRAFT_06); @@ -2804,7 +2807,7 @@ async function saturatedGroup() { const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_05, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const client = await Stream.open(pair.client, { version: Version.DRAFT_05 }); const server = await Stream.accept(pair.server, Version.DRAFT_05); @@ -2882,7 +2885,7 @@ test("lite draft-05: a blocked group header is reset when the group expires", as const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_05, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const client = await Stream.open(pair.client, { version: Version.DRAFT_05 }); const server = await Stream.accept(pair.server, Version.DRAFT_05); if (!server) throw new Error("publisher never accepted the subscribe stream"); @@ -3006,7 +3009,7 @@ test("lite draft-05: a group parked at its tail resets as too old when it expire const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_05, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const frame = (ms: number) => ({ payload: new TextEncoder().encode("x"), timestamp: Timestamp.fromMillis(ms) }); const client = await Stream.open(pair.client, { version: Version.DRAFT_05 }); @@ -3063,7 +3066,7 @@ test("lite draft-05: a group that goes stale while its stream opens writes nothi const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_05, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); let requested!: () => void; const opening = new Promise((resolve) => { @@ -3237,7 +3240,7 @@ test("lite draft-06: a grant that shrinks while a TRACK resolves refuses it", as const resets = spyOn(Writer.prototype, "reset"); const produced = new BroadcastProducer(); - produced.createTrack("video", { timescale: Timescale.MILLI }); + defined(produced.createTrack("video", { timescale: Timescale.MILLI })); try { const serving = publisher.runTrackInfo(new TrackMessage(Path.from("live/cam"), "video"), server); @@ -3296,7 +3299,7 @@ test("lite draft-06: a grant that shrinks while TRACK_INFO is blocked resets it" const resets = spyOn(Writer.prototype, "reset"); const produced = new BroadcastProducer(); - produced.createTrack("video", { timescale: Timescale.MILLI }); + defined(produced.createTrack("video", { timescale: Timescale.MILLI })); try { const serving = publisher.runTrackInfo(new TrackMessage(Path.from("live/cam"), "video"), stream); const request = await requests.next(); @@ -3376,7 +3379,7 @@ test("lite draft-06: a grant that shrinks mid-fetch resets the fetch", async () }); const broadcast = publish(origin, Path.from("live")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); // Left open, so the fetch is still serving when the grant shrinks. const group = track.createGroup(0n); group.writeFrame(textFrame("first")); @@ -3412,7 +3415,7 @@ test("lite draft-07: a fetch whose budget gives up partway resets as too old", a const origin = new OriginProducer(); const publisher = new Publisher(pair.server, Version.DRAFT_07, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("live")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const frame = (ms: number) => ({ payload: new TextEncoder().encode("x"), timestamp: Timestamp.fromMillis(ms) }); // Left open, so the fetch is still serving when the track runs on. const open = track.createGroup(0n); @@ -3459,7 +3462,7 @@ test.each([0, 1])("lite draft-07 reports the cached largest position when starti const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("quiet")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const group = track.createGroup(0n); group.writeFrame(textFrame("cached")); group.finish(); @@ -3505,7 +3508,7 @@ test.each([false, true])( const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("relayed")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); // The source answered with group 4 as its largest; only group 0 has landed. hooks.reportedLargest(track, { group: 4n, frame: 0 }, ended); const group = track.createGroup(0n); @@ -3577,7 +3580,7 @@ for (const version of [Version.DRAFT_05, Version.DRAFT_06, Version.DRAFT_07]) { const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const broadcast = publish(origin, Path.from("test")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); const client = await Stream.open(pair.client, { version }); const server = await Stream.accept(pair.server, version); @@ -3689,8 +3692,8 @@ test("lite-06: a datagram request failing behind the shared writer resets rather const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("test")); - const first = broadcast.createDatagrams("a"); - const second = broadcast.createDatagrams("b"); + const first = defined(broadcast.createDatagrams("a")); + const second = defined(broadcast.createDatagrams("b")); const subscribe = async (id: bigint, track: string) => { const client = await Stream.open(pair.client, { version }); @@ -3785,8 +3788,8 @@ for (const version of [Version.DRAFT_05, Version.DRAFT_06]) { test(`${label}, stream track ${stream}: a SUBSCRIBE sends the datagrams written since its TRACK_INFO`, async () => { const legacy = legacyPublisher(version); try { - const datagrams = legacy.broadcast.createDatagrams("events"); - if (stream) legacy.broadcast.createTrack("events", { timescale: Timescale.MILLI }); + const datagrams = defined(legacy.broadcast.createDatagrams("events")); + if (stream) defined(legacy.broadcast.createTrack("events", { timescale: Timescale.MILLI })); await legacy.track(); datagrams.append(Timestamp.unscaled(0n), Uint8Array.of(0xaa)); await legacy.subscribe(-5); @@ -3804,7 +3807,7 @@ for (const version of [Version.DRAFT_05, Version.DRAFT_06]) { test(`${label}: a SUBSCRIBE reads from the oldest hold`, async () => { const legacy = legacyPublisher(version); try { - const datagrams = legacy.broadcast.createDatagrams("events"); + const datagrams = defined(legacy.broadcast.createDatagrams("events")); await legacy.track(); datagrams.append(Timestamp.unscaled(0n), Uint8Array.of(0xaa)); await legacy.track(); @@ -3820,11 +3823,11 @@ for (const version of [Version.DRAFT_05, Version.DRAFT_06]) { test(`${label}: a SUBSCRIBE reads the current datagram track past an older hold`, async () => { const legacy = legacyPublisher(version); try { - const first = legacy.broadcast.createDatagrams("events"); + const first = defined(legacy.broadcast.createDatagrams("events")); await legacy.track(); first.append(Timestamp.unscaled(0n), Uint8Array.of(0xaa)); first.finish(); - const current = legacy.broadcast.createDatagrams("events"); + const current = defined(legacy.broadcast.createDatagrams("events")); await legacy.track(); current.append(Timestamp.unscaled(0n), Uint8Array.of(0xbb)); await legacy.subscribe(0); diff --git a/js/net/src/lite/refresh.test.ts b/js/net/src/lite/refresh.test.ts index 64a7f544473..c8a1fd131ee 100644 --- a/js/net/src/lite/refresh.test.ts +++ b/js/net/src/lite/refresh.test.ts @@ -3,6 +3,7 @@ import { Duration } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import { accept } from "../connection/accept.ts"; import { connect } from "../connection/connect.ts"; +import { defined } from "../defined.test-util.ts"; import { hooks } from "../internal.ts"; import { createMockTransportPair } from "../mock.ts"; import { Producer } from "../origin.ts"; @@ -18,7 +19,7 @@ test.each([ALPN_06, ALPN_07_WIP])("refresh joins reach a browser publisher on %s const b = new Producer(); const broadcastRoute = source.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("data", { refresh: { ratio: 1 } }); + const producer = defined(broadcast.createTrack("data", { refresh: { ratio: 1 } })); const asked = hooks.demandAsked(producer.demand()); const pair = createMockTransportPair(alpn); const url = new URL("https://localhost/refresh"); @@ -91,9 +92,11 @@ test("a refresh resolves once the session sends it upstream", async () => { const installed = clock.install(); const source = new Producer(); const b = new Producer(); - const producer = source.route(Path.from("room")).broadcast.createTrack("data", { - refresh: { interval: Duration.secs(5) }, - }); + const producer = defined( + source.route(Path.from("room")).broadcast.createTrack("data", { + refresh: { interval: Duration.secs(5) }, + }), + ); const asked = hooks.demandAsked(producer.demand()); const pair = createMockTransportPair(ALPN_07_WIP); const url = new URL("https://localhost/refresh"); diff --git a/js/net/src/lite/subscriber.ts b/js/net/src/lite/subscriber.ts index dddc9e11339..61ccfadff13 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -1719,28 +1719,31 @@ export class Subscriber { const datagrams = request ? request.accept(info) : wireOf(state.consumer).createDatagrams(producer.name, info, false); - entry.datagrams = { producer: datagrams, timescale: framing.scale }; - entry.legacyKey = state.legacyKey; - this.#datagrams.set(id, entry.datagrams); - this.#legacyDatagrams.set(state.legacyKey, entry.datagrams); - let held: track.Subscriber | undefined; - const sync = () => { - const priority = datagrams.priority.peek(); - if (priority === undefined) { + // Undefined while a live datagram track already holds the name: serve the stream track alone. + if (datagrams) { + entry.datagrams = { producer: datagrams, timescale: framing.scale }; + entry.legacyKey = state.legacyKey; + this.#datagrams.set(id, entry.datagrams); + this.#legacyDatagrams.set(state.legacyKey, entry.datagrams); + let held: track.Subscriber | undefined; + const sync = () => { + const priority = datagrams.priority.peek(); + if (priority === undefined) { + held?.close(); + held = undefined; + } else if (held) { + held.update({ priority }); + } else { + held = producer.subscribe({ priority }); + } + }; + const dispose = datagrams.priority.subscribe(sync); + sync(); + entry.datagramDemand = () => { + dispose(); held?.close(); - held = undefined; - } else if (held) { - held.update({ priority }); - } else { - held = producer.subscribe({ priority }); - } - }; - const dispose = datagrams.priority.subscribe(sync); - sync(); - entry.datagramDemand = () => { - dispose(); - held?.close(); - }; + }; + } } this.#subscribes.set(id, entry); @@ -2379,11 +2382,11 @@ export class Subscriber { cancel.abort(); return; } - let group: netGroup.Producer; + let group: netGroup.Producer | undefined; try { // The live feed may have brought it meanwhile, or every reader left. - if (!fill.isWanted(key)) throw new StreamError(StreamCode.Cancel, { message: "cancel" }); - group = fill.accept(key); + if (fill.isWanted(key)) group = fill.accept(key); + if (!group) throw new StreamError(StreamCode.Cancel, { message: "cancel" }); } catch (err) { stream.abort(error(err)); return; diff --git a/js/net/src/lite/tracks.test.ts b/js/net/src/lite/tracks.test.ts index ba25b0c4da3..7e14799091e 100644 --- a/js/net/src/lite/tracks.test.ts +++ b/js/net/src/lite/tracks.test.ts @@ -4,6 +4,7 @@ import { type Getter, Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; import { Producer as BroadcastProducer, type Tracks } from "../broadcast.ts"; import { accept, connect } from "../connection/index.ts"; +import { defined } from "../defined.test-util.ts"; import { fromTransport, NotFound, SessionCode, StreamCode, StreamError } from "../error.ts"; import { randomHop } from "../hop.ts"; import * as Instance from "../instance.ts"; @@ -414,7 +415,7 @@ test("data after a TRACKS request closes the session", async () => { const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - broadcast.createTrack("a"); + defined(broadcast.createTrack("a")); const { list, closing } = publisher(origin); const listing = await list("room"); expect(await listing.next()).toBe("+a"); @@ -429,7 +430,7 @@ test("a publisher lists its broadcast's own tracks, never one served on request" const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - broadcast.createTrack("a", { priority: 5 }); + defined(broadcast.createTrack("a", { priority: 5 })); // Served on request: answered when asked, never listed. void wireOf(broadcast) .requested() @@ -440,7 +441,7 @@ test("a publisher lists its broadcast's own tracks, never one served on request" expect(await listing.next()).toBe("synced"); broadcast.consume().track("x").subscribe(); - broadcast.createTrack("b"); + defined(broadcast.createTrack("b")); expect(await listing.next()).toBe("+b"); broadcast.close(); @@ -451,7 +452,7 @@ test("a newer listing of a broadcast on one session replaces the older", async ( const origin = new OriginProducer(); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - broadcast.createTrack("a"); + defined(broadcast.createTrack("a")); const { list } = publisher(origin); const older = await list("room"); expect(await older.next()).toBe("+a"); @@ -460,7 +461,7 @@ test("a newer listing of a broadcast on one session replaces the older", async ( expect(await newer.next()).toBe("+a"); expect(await newer.next()).toBe("synced"); expect(await older.next()).toBe(`reset: ${StreamCode.Cancel}`); - broadcast.createTrack("b"); + defined(broadcast.createTrack("b")); expect(await newer.next()).toBe("+b"); broadcast.close(); }); @@ -471,7 +472,7 @@ test("a path served through a covering prefix route is NOT_FOUND", async () => { void (async () => { for await (const request of dynamic.requested()) { const served = new BroadcastProducer(); - served.createTrack("video"); + defined(served.createTrack("video")); request.serve(served); } })(); @@ -488,7 +489,7 @@ test("a local read through a covering prefix route is NOT_FOUND, and through its void (async () => { for await (const request of dynamic.requested()) { const served = new BroadcastProducer(); - served.createTrack("video"); + defined(served.createTrack("video")); request.serve(served); } })(); @@ -522,13 +523,15 @@ test("a listing over a session carries each track's info, end to end", async () ]); const broadcastRoute = origin.route(Path.from("room")); const broadcast = broadcastRoute.broadcast; - broadcast.createTrack("a", { - timescale: Timescale.MILLI, - maxAge: Duration.millis(3000), - priority: 9, - refresh: { ratio: 4, interval: Duration.millis(250) }, - compression: "deflate", - }); + defined( + broadcast.createTrack("a", { + timescale: Timescale.MILLI, + maxAge: Duration.millis(3000), + priority: 9, + refresh: { ratio: 4, interval: Duration.millis(250) }, + compression: "deflate", + }), + ); const tracks = wireOf(client).consume(Path.from("room")).tracks(); expect(await tracks.next()).toEqual({ @@ -543,11 +546,11 @@ test("a listing over a session carries each track's info, end to end", async () }, }); expect(await next(tracks)).toBe("synced"); - broadcast.createTrack("b"); + defined(broadcast.createTrack("b")); expect(await next(tracks)).toBe("+b"); broadcast.removeTrack("a"); expect(await next(tracks)).toBe("-a"); - const datagrams = broadcast.createDatagrams("a", { timescale: Timescale.MILLI, priority: 3 }); + const datagrams = defined(broadcast.createDatagrams("a", { timescale: Timescale.MILLI, priority: 3 })); expect(await tracks.next()).toEqual({ kind: "added", name: "a", @@ -575,7 +578,7 @@ test("an instance-pinned front lists its serving route's tracks", async () => { instance: { id: Instance.parse("01900000-0000-7000-8000-000000000001"), epoch: 0n }, }); const broadcast = broadcastRoute.broadcast; - broadcast.createTrack("a"); + defined(broadcast.createTrack("a")); broadcastRoute.announce(); const reader = clientOrigin.consume(); @@ -589,7 +592,7 @@ test("an instance-pinned front lists its serving route's tracks", async () => { // The front syncs with its source's listing, which syncs when the peer does. expect(await next(tracks)).toBe("+a"); expect(await next(tracks)).toBe("synced"); - broadcast.createTrack("b"); + defined(broadcast.createTrack("b")); expect(await next(tracks)).toBe("+b"); tracks.close(); request.close(); @@ -605,7 +608,7 @@ test("a front pinned to a named instance served through a covering prefix route void (async () => { for await (const request of dynamic.requested()) { const served = new BroadcastProducer(); - served.createTrack("video"); + defined(served.createTrack("video")); request.serve(served); } })(); diff --git a/js/net/src/lite/widened_max_age.test.ts b/js/net/src/lite/widened_max_age.test.ts index 3f58ade9af2..57e0b37deec 100644 --- a/js/net/src/lite/widened_max_age.test.ts +++ b/js/net/src/lite/widened_max_age.test.ts @@ -4,6 +4,7 @@ import { expect, test } from "bun:test"; import { Duration } from "@moq/clock"; import { accept, connect } from "../connection/index.ts"; +import { defined } from "../defined.test-util.ts"; import { hooks } from "../internal.ts"; import { createMockTransportPair } from "../mock.ts"; import { Producer as OriginProducer } from "../origin.ts"; @@ -31,7 +32,7 @@ test("a widened maxDelay re-offers what the publisher skipped below the start", const origin = new OriginProducer(); const publication = origin.route(Path.from("room")); const broadcast = publication.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); // One group per second, so a budget picks how far back a reader reaches. for (let key = 0; key < 10; key++) { const group = hooks.appendNext(producer); @@ -73,7 +74,7 @@ for (const [version, alpn] of [ const origin = new OriginProducer(); const publication = origin.route(Path.from("room")); const broadcast = publication.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const write = (key: number, millis: number) => { const group = producer.createGroup(BigInt(key)); group.writeFrame({ payload: new Uint8Array([key]), timestamp: Timestamp.fromMillis(millis) }); @@ -123,7 +124,7 @@ test("a widening recovers the stale groups for a bounded lite-07 reader", async const origin = new OriginProducer(); const publication = origin.route(Path.from("room")); const broadcast = publication.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const write = (key: number, millis: number) => { const group = producer.createGroup(BigInt(key)); group.writeFrame({ payload: new Uint8Array([key]), timestamp: Timestamp.fromMillis(millis) }); diff --git a/js/net/src/order.test.ts b/js/net/src/order.test.ts index 621e8a4371d..99d199d6d13 100644 --- a/js/net/src/order.test.ts +++ b/js/net/src/order.test.ts @@ -8,6 +8,7 @@ import { expect, test } from "bun:test"; import { Duration } from "@moq/clock"; import { accept, connect, type Session } from "./connection/index.ts"; +import { defined } from "./defined.test-util.ts"; import type { Producer as GroupProducer } from "./group.ts"; import { FetchHeader } from "./ietf/fetch.ts"; import * as Ietf from "./ietf/index.ts"; @@ -147,7 +148,7 @@ async function backlog(protocol: string, order: Order, update?: Order) { const broadcastRoute = origin.route(Path.from("test")); const broadcast = broadcastRoute.broadcast; - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const groups = [0, 1, 2].map(() => writeGroup(video)); const remote = wireOf(client).consume(Path.from("test")); @@ -200,7 +201,7 @@ test.each(["ascending", "descending"] as const)("ietf serves GROUP_ORDER %s", as const broadcastRoute = origin.route(Path.from("test")); const broadcast = broadcastRoute.broadcast; - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const remote = wireOf(client).consume(Path.from("test")); const subscriber = remote.track("video").subscribe({ delay: { max: MAX_DELAY }, order }); @@ -267,7 +268,7 @@ test("ietf keeps a closing group stream ranked until it settles", async () => { const broadcastRoute = origin.route(Path.from("test")); const broadcast = broadcastRoute.broadcast; - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const remote = wireOf(client).consume(Path.from("test")); const subscriber = remote.track("video").subscribe({ delay: { max: MAX_DELAY }, order: "descending" }); @@ -307,7 +308,7 @@ test("a shared track aggregates descending and serves each subscriber in its own const broadcastRoute = origin.route(Path.from("test")); const broadcast = broadcastRoute.broadcast; - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const ascendingRemote = wireOf(ascending.client).consume(Path.from("test")); const ascendingTrack = ascendingRemote.track("video").subscribe({ delay: { max: MAX_DELAY }, order: "ascending" }); diff --git a/js/net/src/origin-request.test.ts b/js/net/src/origin-request.test.ts index d1a732bf00f..c595627cfba 100644 --- a/js/net/src/origin-request.test.ts +++ b/js/net/src/origin-request.test.ts @@ -1,5 +1,6 @@ import { expect, test } from "bun:test"; import { Producer as BroadcastProducer } from "./broadcast"; +import { defined } from "./defined.test-util.ts"; import { StreamCode, StreamError } from "./error"; import { WireRoute } from "./hop"; import * as Instance from "./instance.ts"; @@ -403,9 +404,10 @@ test("an application serves held content without an exact route", async () => { const pending = (await requests.next()).value; if (!pending) throw new Error("expected a request"); const source = new BroadcastProducer(); - source - .createTrack("data") - .writeFrame({ payload: new TextEncoder().encode("held"), timestamp: Timestamp.unscaled(0n) }); + defined(source.createTrack("data")).writeFrame({ + payload: new TextEncoder().encode("held"), + timestamp: Timestamp.unscaled(0n), + }); pending.serve(source.consume()); await settle(); const reader = request.active.peek()?.track("data").subscribe().ordered(); @@ -530,7 +532,7 @@ test("a throwing handler disposes its job route and leaves the claim answerable" const failed = (async () => { for await (const request of claim.requested()) { using job = request.route({ hidden: true }); - job.broadcast.createTrack("video"); + defined(job.broadcast.createTrack("video")); throw new Error("handler failed"); } })(); @@ -1311,7 +1313,7 @@ test("a claim moving on keeps its held answers", async () => { const minted = claim.instance; const requests = claim.requested(); const held = new BroadcastProducer(); - held.createTrack("data").writeFrame({ + defined(held.createTrack("data")).writeFrame({ payload: new TextEncoder().encode("held"), timestamp: Timestamp.unscaled(0n), }); diff --git a/js/net/src/origin.test.ts b/js/net/src/origin.test.ts index 0280ee02a28..21242ebcc5a 100644 --- a/js/net/src/origin.test.ts +++ b/js/net/src/origin.test.ts @@ -3,6 +3,7 @@ import { yieldNow } from "@moq/clock"; import { getter, Once, race, Signal } from "@moq/signals"; import { announcedView } from "./announced.test-util"; import { type Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; +import { defined } from "./defined.test-util.ts"; import { StreamCode, StreamError } from "./error.ts"; import { type Cost, toHop, WireRoute } from "./hop.ts"; import * as Instance from "./instance.ts"; @@ -66,7 +67,7 @@ for (const via of ["direct", "request", "follow"] as const) { const origin = new Producer(); const path = Path.from("live"); const broadcast = publish(origin, path); - const track = broadcast.createTrack("video", { maxAge: null }); + const track = defined(broadcast.createTrack("video", { maxAge: null })); const request = via === "direct" ? undefined : origin.consume()[via](path); await settle(); const consumed = request ? request.active.peek() : broadcast.consume(); @@ -250,7 +251,7 @@ test("a published broadcast resolves by path", async () => { expect(wireOf(consumer).routes(path)).toBe(false); const broadcast = publish(origin, path); - broadcast.createTrack("video", { timescale: Timescale.MILLI }); + defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const handle = await routed(consumer, path); expect(handle).toBeDefined(); @@ -324,7 +325,7 @@ test("a superseded broadcast closes, and its subscribers keep reading", async () const publication = origin.route(path, { hidden: true }); const first = publication.broadcast; - const track = first.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(first.createTrack("video", { timescale: Timescale.MILLI })); publication.announce(); const mine = await routed(consumer, path); const subscriber = mine?.track("video").subscribe(); @@ -522,11 +523,11 @@ test("a local publish shadows a remote entry", async () => { const path = Path.from("room"); const upstream = new BroadcastProducer(); - upstream.createTrack("remote-track", { timescale: Timescale.MILLI }); + defined(upstream.createTrack("remote-track", { timescale: Timescale.MILLI })); const dispose = serve(origin, path, provider(upstream), { hops: [], cost: 9n }); const local = publish(origin, path); - local.createTrack("local-track", { timescale: Timescale.MILLI }); + defined(local.createTrack("local-track", { timescale: Timescale.MILLI })); // Local wins: the handle reaches the local track, not the remote one. const handle = await routed(consumer, path); @@ -652,7 +653,7 @@ test("disposing the newest remote route promotes the fallback", async () => { // Two sessions announced the same path; the older one is still alive when the newer // one goes away, so the route must fail over rather than black-hole. const older = new BroadcastProducer(); - older.createTrack("chat", { timescale: Timescale.MILLI }); + defined(older.createTrack("chat", { timescale: Timescale.MILLI })); const keepOlder = older.consume(); const disposeOlder = serve(origin, path, provider(older)); @@ -1401,7 +1402,7 @@ test("a handle serves a request under live", async () => { expect(req?.path).toBe(Path.from("live/cam")); const produced = new BroadcastProducer(); - produced.createTrack("video", { timescale: Timescale.MILLI }); + defined(produced.createTrack("video", { timescale: Timescale.MILLI })); req.serve(produced); await settle(); @@ -1439,7 +1440,7 @@ test("a received route still serves a broadcast a session delivered", async () = const origin = new Producer(); const path = Path.from("room"); const upstream = new BroadcastProducer(); - upstream.createTrack("video"); + defined(upstream.createTrack("video")); const foreign = upstream.consume(); overrideBroadcastWire(foreign, {}); const stop = serve(origin, path, () => foreign); @@ -1476,7 +1477,7 @@ test("an accepted dynamic broadcast is retired when it closes, and its handle re const first = await it.next(); const produced = new BroadcastProducer(); - produced.createTrack("video", { timescale: Timescale.MILLI }); + defined(produced.createTrack("video", { timescale: Timescale.MILLI })); first.value.serve(produced); await settle(); const held = request.active.peek(); @@ -1489,7 +1490,7 @@ test("an accepted dynamic broadcast is retired when it closes, and its handle re const second = await it.next(); expect(second.value?.path).toBe(path); const replacement = new BroadcastProducer(); - replacement.createTrack("video", { timescale: Timescale.MILLI }); + defined(replacement.createTrack("video", { timescale: Timescale.MILLI })); second.value.serve(replacement); await settle(); expect(request.active.peek()).toBe(held); @@ -2853,7 +2854,7 @@ test("demand held across an instance change asks again, unless it named the old await expect(pinned).rejects.toThrow("unroutable"); const next = new BroadcastProducer(); - const track = next.createTrack("video"); + const track = defined(next.createTrack("video")); (await it.next()).value.serve(next); const subscription = (await unpinned)?.track("video").subscribe(); track.createGroup(7n); @@ -2901,7 +2902,7 @@ test("demand held across an instance round trip still asks again", async () => { req.serve(new BroadcastProducer().consume()); const next = new BroadcastProducer(); - const track = next.createTrack("video"); + const track = defined(next.createTrack("video")); (await it.next()).value.serve(next); const subscription = (await demanded)?.track("video").subscribe(); track.createGroup(7n); @@ -3031,7 +3032,7 @@ test.each([ const held = origin.consume().request(path); const old = new BroadcastProducer(); - const oldTrack = old.createTrack("video"); + const oldTrack = defined(old.createTrack("video")); (await requests.next()).value.serve(old); await settle(); const resolved = held.active.peek(); @@ -3068,7 +3069,7 @@ test.each([ const fresh = origin.consume().request(path); const demanded = wireOf(origin.consume()).demand(path); const next = new BroadcastProducer(); - const nextTrack = next.createTrack("video"); + const nextTrack = defined(next.createTrack("video")); (await requests.next()).value.serve(next); await settle(); expect(fresh.active.peek()?.instance).toBe(to); @@ -3166,7 +3167,7 @@ test("a session's re-request after an instance update asks the handler again", a wireOf(dynamic).update({ ...wireOf(dynamic).info, instance: NEWER }); const after = wire.demand(path); const next = new BroadcastProducer(); - const track = next.createTrack("video"); + const track = defined(next.createTrack("video")); (await requests.next()).value.serve(next); const subscription = (await after)?.track("video").subscribe(); track.createGroup(7n); @@ -3201,7 +3202,7 @@ test("an update does not override route selection: another claim at the instance wireOf(first).update({ ...wireOf(first).info, instance: NEWER, cost: 9n }); const fresh = origin.consume().request(path); const replacement = new BroadcastProducer(); - const track = replacement.createTrack("video"); + const track = defined(replacement.createTrack("video")); (await secondRequests.next()).value.serve(replacement); await settle(); expect(held.active.peek()?.instance).toBe(INSTANCE); diff --git a/js/net/src/parked-expiry.test.ts b/js/net/src/parked-expiry.test.ts index 2482d09e004..6784edfd285 100644 --- a/js/net/src/parked-expiry.test.ts +++ b/js/net/src/parked-expiry.test.ts @@ -1,6 +1,7 @@ import { expect, spyOn, test } from "bun:test"; import { Duration } from "@moq/clock"; import { Manual } from "@moq/clock/test"; +import { defined } from "./defined.test-util.ts"; import { StreamCode } from "./error.ts"; import { randomHop } from "./hop.ts"; import { Publisher as IetfPublisher } from "./ietf/publisher.ts"; @@ -37,7 +38,7 @@ for (const protocol of protocols) { // No publisher limit, so the cache eviction rather than a stale verdict ends a long budget. // moq-transport carries no subscriber budget, so there the publisher's own limit expires it. const maxAge = protocol.kind === "ietf" && mode === "expires" ? Duration.millis(budget) : null; - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge })); const write = (key: bigint) => { const group = track.createGroup(key); group.writeFrame({ payload: new Uint8Array([1]), timestamp: Timestamp.fromMillis(Number(key)) }); @@ -157,7 +158,7 @@ for (const protocol of protocols) { const broadcast = broadcastRoute.broadcast; // No publisher limit, so the eviction rather than a stale verdict gives the group up: lite-07 // closes the stream of a group gone stale instead of resetting it. - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const write = (key: bigint, frames: number) => { const group = track.createGroup(key); for (let frame = 0; frame < frames; frame++) { diff --git a/js/net/src/priority.test.ts b/js/net/src/priority.test.ts index 250fa7aaa86..38bd91dbe09 100644 --- a/js/net/src/priority.test.ts +++ b/js/net/src/priority.test.ts @@ -1,5 +1,6 @@ import { expect, test } from "bun:test"; import { Producer as BroadcastProducer } from "./broadcast.ts"; +import { defined } from "./defined.test-util.ts"; import { Version } from "./lite/version.ts"; import { Priority, sendOrder } from "./priority.ts"; import { type SendStream, Writer } from "./stream.ts"; @@ -70,7 +71,7 @@ test("out of range ranks stay inside their own bits", () => { // group already on the wire keeps writing after the track stops handing out new ones. function ranking(options: Subscription = {}) { const broadcast = new BroadcastProducer(); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const subscriber = track.subscribe(options); // The send order lands on the underlying stream, exactly as it would on a real one. diff --git a/js/net/src/resume.model.test.ts b/js/net/src/resume.model.test.ts index 819a01bc787..feb68d23b5c 100644 --- a/js/net/src/resume.model.test.ts +++ b/js/net/src/resume.model.test.ts @@ -16,6 +16,7 @@ import { Duration } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import fc from "fast-check"; import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; +import { defined } from "./defined.test-util.ts"; import { NotFound, StreamCode, StreamError, TooFarBehind } from "./error.ts"; import type { Frame, Consumer as GroupConsumer, Producer as GroupProducer } from "./group.ts"; import { toHop, WireRoute } from "./hop.ts"; @@ -469,7 +470,7 @@ class Model { }); const serving = wireOf(this.origin).receive(PATH, route); const broadcast = new BroadcastProducer(); - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); void (async () => { for await (const request of serving.requested()) { request.serve(Upstream.of(broadcast, (key, local) => this.fill(instance, slot, key, local))); diff --git a/js/net/src/resume.test-util.ts b/js/net/src/resume.test-util.ts index b2af8f15563..ba21a0b5464 100644 --- a/js/net/src/resume.test-util.ts +++ b/js/net/src/resume.test-util.ts @@ -1,4 +1,5 @@ import type { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast"; +import { defined } from "./defined.test-util.ts"; import { hooks } from "./internal.ts"; import { Timestamp } from "./time.ts"; @@ -8,7 +9,7 @@ let probes = 0; export function readsFrom(active: BroadcastConsumer | undefined, source: BroadcastProducer): boolean { if (!active) return false; const name = `probe-${probes++}`; - const track = source.createTrack(name); + const track = defined(source.createTrack(name)); const group = hooks.appendNext(track); group.writeFrame({ payload: new Uint8Array([1]), timestamp: Timestamp.unscaled(group.start) }); group.finish(); diff --git a/js/net/src/resume.test.ts b/js/net/src/resume.test.ts index 65b2abeb168..46141f64f7f 100644 --- a/js/net/src/resume.test.ts +++ b/js/net/src/resume.test.ts @@ -3,6 +3,7 @@ import { Duration, yieldNow } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import { Signal } from "@moq/signals"; import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; +import { defined } from "./defined.test-util.ts"; import { NotFound, SessionCode, SessionError, StreamCode, StreamError } from "./error.ts"; import { type Consumer as GroupConsumer, Producer as GroupProducer } from "./group.ts"; import { WireRoute } from "./hop.ts"; @@ -63,7 +64,7 @@ function serve(origin: Producer, source: BroadcastProducer, cost: bigint) { * Resumed readers backfill superseded groups, so it sets no publisher limit. */ function copy(source: BroadcastProducer) { - const producer = source.createTrack("seq", { maxAge: null }); + const producer = defined(source.createTrack("seq", { maxAge: null })); return { producer, write(key: bigint, frames = 1, close = true) { @@ -173,7 +174,7 @@ test("a pending refresh moves to the next copy when the one it asked closes", as const sources = [new BroadcastProducer(), new BroadcastProducer()]; const handles = sources.map((source) => source.consume()); const tracks = sources.map((source) => { - const producer = source.createTrack("seq", { maxAge: null, refresh: { interval: Duration.secs(5) } }); + const producer = defined(source.createTrack("seq", { maxAge: null, refresh: { interval: Duration.secs(5) } })); const group = producer.createGroup(0n); group.writeFrame({ payload: enc.encode("0"), timestamp: Timestamp.unscaled(group.start) }); group.finish(); @@ -538,7 +539,7 @@ test("a backfill waits on a fill the finished route still owes", async () => { fill.dropGroups(key, key + 1n); continue; } - const group = fill.accept(key); + const group = defined(fill.accept(key)); group.writeFrame({ payload: enc.encode("2.0"), timestamp: Timestamp.unscaled(group.start) }); group.finish(); } @@ -778,13 +779,13 @@ test("a lagging same-instance replica resumes from one publisher's bytes exactly const publisher = new Producer(); const originalRoute = publisher.route(path, { instance: { id: INSTANCE, epoch: 0n } }); const original = originalRoute.broadcast; - const source = original.createTrack("seq", { maxAge: null }); + const source = defined(original.createTrack("seq", { maxAge: null })); const origin = new Producer(); // Both replicas forward this one source. Only the incumbent pauses mid-group. function replica(lagging: boolean) { const broadcast = new BroadcastProducer(); - const output = broadcast.createTrack("seq", { maxAge: null }); + const output = defined(broadcast.createTrack("seq", { maxAge: null })); const input = source.subscribe({ delay: { max: Duration.millis(60_000) } }); const release = Promise.withResolvers(); let stopped = false; @@ -1017,8 +1018,8 @@ for (const [name, before, after] of [ ] as const) { test(`a replacement claiming different ${name} is refused once the old copy runs out`, async () => { const { a, b, swap, active, close } = await setup(); - const old = a.createTrack("seq", before); - b.createTrack("seq", after); + const old = defined(a.createTrack("seq", before)); + defined(b.createTrack("seq", after)); const sub = active.track("seq").subscribe(); expect(await sub.info()).toMatchObject(before); await swap(); @@ -1037,7 +1038,7 @@ for (const [name, before, after] of [ // `unchecked` records how a copy arrived (lite-05/06), so it splices beside a lite-07 copy. test("a replacement differing only in unchecked takes over", async () => { const { a, b, swap, active, close } = await setup(); - const old = a.createTrack("seq", { unchecked: true, maxAge: null }); + const old = defined(a.createTrack("seq", { unchecked: true, maxAge: null })); const tb = copy(b); const sub = active.track("seq").subscribe(); await sub.info(); @@ -1342,8 +1343,8 @@ test("a replacement that aborts before its first group after the front concludes test("waiting for the end of a track whose replacement was refused ends with the refusal", async () => { const { a, b, swap, active, close } = await setup(); - const old = a.createTrack("seq", { priority: 1 }); - b.createTrack("seq", { priority: 2 }); + const old = defined(a.createTrack("seq", { priority: 1 })); + defined(b.createTrack("seq", { priority: 2 })); const sub = active.track("seq").subscribe(); expect((await sub.info()).priority).toBe(1); await swap(); @@ -1375,10 +1376,10 @@ test("a fetched group continued from an empty, already-closed copy releases that const sub = front.consumer.track("seq").subscribe(); // Group 5 is empty: the first route fails it, the next holds it closed. - const failing = a.createTrack("fetch").createGroup(5n); + const failing = defined(a.createTrack("fetch")).createGroup(5n); const group = await front.consumer.track("fetch").fetchGroup(5n); const read = group.readFrame(); - const whole = b.createTrack("fetch").createGroup(5n); + const whole = defined(b.createTrack("fetch")).createGroup(5n); whole.finish(); front.serve(b.consume()); await settle(); @@ -1416,7 +1417,7 @@ test("a fetched group failing as it is handed out releases its route once", asyn ta.write(0n); expect(drain(sub)).toEqual([0n]); - const fa = a.createTrack("fetch"); + const fa = defined(a.createTrack("fetch")); const failing = fa.createGroup(5n); failing.writeFrame({ payload: enc.encode("5.0"), timestamp: Timestamp.unscaled(failing.start) }); const fetching = front.consumer.track("fetch").fetchGroup(5n); @@ -1426,12 +1427,12 @@ test("a fetched group failing as it is handed out releases its route once", asyn // The next route holds the fetched group whole; the old one still feeds the reader a // group the new route never has. - const fb = b.createTrack("fetch"); + const fb = defined(b.createTrack("fetch")); const whole = fb.createGroup(5n); whole.writeFrame({ payload: enc.encode("5.0"), timestamp: Timestamp.unscaled(whole.start) }); whole.writeFrame({ payload: enc.encode("5.1"), timestamp: Timestamp.unscaled(whole.start) }); whole.finish(); - b.createTrack("seq"); + defined(b.createTrack("seq")); front.serve(b.consume()); const group = await fetching; const frames: string[] = []; @@ -1953,8 +1954,8 @@ test("a replacement spliced before the first copy answers is still checked again const front = new Front(); const a = new BroadcastProducer(); const b = new BroadcastProducer(); - const old = a.createTrack("seq", { priority: 1 }); - b.createTrack("seq", { priority: 2 }); + const old = defined(a.createTrack("seq", { priority: 1 })); + defined(b.createTrack("seq", { priority: 2 })); front.serve(a.consume()); const sub = front.consumer.track("seq").subscribe(); // Swapped in the same turn, before the first copy's info committed anywhere. @@ -2105,8 +2106,8 @@ test("a late subscriber's first route is checked against properties an earlier s const front = new Front(); const a = new BroadcastProducer(); const b = new BroadcastProducer(); - a.createTrack("seq", { priority: 1 }); - b.createTrack("seq", { priority: 2 }); + defined(a.createTrack("seq", { priority: 1 })); + defined(b.createTrack("seq", { priority: 2 })); front.serve(a.consume()); expect((await front.consumer.track("seq").info()).priority).toBe(1); @@ -2499,8 +2500,8 @@ for (const [field, first, second] of [ const front = new Front(); const a = new BroadcastProducer(); const b = new BroadcastProducer(); - a.createTrack("seq", first); - b.createTrack("seq", second); + defined(a.createTrack("seq", first)); + defined(b.createTrack("seq", second)); front.serve(a.consume()); expect(await front.consumer.track("seq").info()).toMatchObject(first); front.serve(b.consume()); @@ -2515,8 +2516,8 @@ test("a failed group on a route whose replacement was refused ends with the refu const front = new Front(); const a = new BroadcastProducer(); const b = new BroadcastProducer(); - const ta = a.createTrack("seq", { priority: 1 }); - b.createTrack("seq", { priority: 2 }); + const ta = defined(a.createTrack("seq", { priority: 1 })); + defined(b.createTrack("seq", { priority: 2 })); front.serve(a.consume()); const sub = front.consumer.track("seq").subscribe(); const stalled = ta.createGroup(0n); @@ -2593,8 +2594,8 @@ test("a fetch never reads a replacement refused for its track properties", async const front = new Front(); const a = new BroadcastProducer(); const b = new BroadcastProducer(); - a.createTrack("seq", { priority: 1 }); - const tb = b.createTrack("seq", { priority: 2 }); + defined(a.createTrack("seq", { priority: 1 })); + const tb = defined(b.createTrack("seq", { priority: 2 })); const group = tb.createGroup(0n); group.writeFrame({ payload: enc.encode("b"), timestamp: Timestamp.unscaled(group.start) }); group.finish(); @@ -2616,7 +2617,7 @@ test("the first fetch of a track says what the track is for later routes", async [a, 1], [b, 2], ] as const) { - const producer = source.createTrack("seq", { priority }); + const producer = defined(source.createTrack("seq", { priority })); const group = producer.createGroup(0n); group.writeFrame({ payload: enc.encode(`${priority}`), timestamp: Timestamp.unscaled(group.start) }); group.finish(); @@ -2635,7 +2636,7 @@ test("aborting a fetch stops it while its route's properties are still being che const front = new Front(); const a = new BroadcastProducer(); const b = new BroadcastProducer(); - a.createTrack("seq"); + defined(a.createTrack("seq")); // b serves tracks on demand but never answers, so its properties never arrive. void wireOf(b).requested(); front.serve(a.consume()); @@ -2672,8 +2673,8 @@ test("a fetch never hands out a group from a route refused for its properties", const front = new Front(); const a = new BroadcastProducer(); const b = new BroadcastProducer(); - a.createTrack("seq", { priority: 1 }); - const tb = b.createTrack("seq", { priority: 2 }); + defined(a.createTrack("seq", { priority: 1 })); + const tb = defined(b.createTrack("seq", { priority: 2 })); const group = tb.createGroup(0n); group.writeFrame({ payload: enc.encode("b"), timestamp: Timestamp.unscaled(group.start) }); group.finish(); @@ -2695,7 +2696,7 @@ test("a refused route is not served again by a later compatible source", async ( const b = new BroadcastProducer(); const c = new BroadcastProducer(); const ta = copy(a); - b.createTrack("seq", { priority: 2 }); + defined(b.createTrack("seq", { priority: 2 })); const tc = copy(c); front.serve(a.consume()); const sub = front.consumer.track("seq").subscribe(); @@ -2962,7 +2963,7 @@ test("track info asks the next route when the current one never answers", async const b = new BroadcastProducer(); // a serves tracks on demand but never answers. void wireOf(a).requested(); - b.createTrack("seq", { priority: 2 }); + defined(b.createTrack("seq", { priority: 2 })); front.serve(a.consume()); const info = front.consumer.track("seq").info(); await settle(); @@ -3011,7 +3012,7 @@ test("track info waits for the copy being read to say what the track is", async const b = new BroadcastProducer(); // a answers what the track is only when told to. const requests = wireOf(a).requested(); - b.createTrack("seq", { priority: 2 }); + defined(b.createTrack("seq", { priority: 2 })); front.serve(a.consume()); const sub = front.consumer.track("seq").subscribe(); front.serve(b.consume()); @@ -3083,7 +3084,7 @@ test("a fetch waits for the copy being read to say what the track is", async () const b = new BroadcastProducer(); // a answers what the track is only when told to. const requests = wireOf(a).requested(); - const tb = b.createTrack("seq", { priority: 2 }); + const tb = defined(b.createTrack("seq", { priority: 2 })); const group = tb.createGroup(0n); group.writeFrame({ payload: enc.encode("b"), timestamp: Timestamp.unscaled(group.start) }); group.finish(); @@ -3132,7 +3133,7 @@ test("a fetch still out on the old route moves to the new one", async () => { const a = new BroadcastProducer(); const b = new BroadcastProducer(); // a has the track but not group 5 yet, so its fetch waits on a's request handler. - const pending = a.createTrack("seq", { maxAge: null }).requests(); + const pending = defined(a.createTrack("seq", { maxAge: null })).requests(); const tb = copy(b); tb.write(5n); front.serve(a.consume()); @@ -3937,7 +3938,7 @@ test.each([ // The old source's listing is answered, as a session answers its peer's. const answer = wireOf(from).lister(); answer.synced(); - b.createTrack("seq"); + defined(b.createTrack("seq")); front.serve(from); const tracks = front.consumer.tracks(); try { @@ -3952,7 +3953,7 @@ test.each([ end(answer); await settled; expect(await tracks.next()).toMatchObject({ kind: "added", name: "seq" }); - b.createTrack("late"); + defined(b.createTrack("late")); expect(await tracks.next()).toMatchObject({ kind: "added", name: "late" }); } finally { tracks.close(); diff --git a/js/net/src/retention.test.ts b/js/net/src/retention.test.ts index 7f43534d31a..c7283e5b219 100644 --- a/js/net/src/retention.test.ts +++ b/js/net/src/retention.test.ts @@ -1,6 +1,7 @@ import { afterAll, afterEach, expect, spyOn, test } from "bun:test"; import { type Dispose, Once } from "@moq/signals"; import { accept, connect } from "./connection/index.ts"; +import { defined } from "./defined.test-util.ts"; import type * as Group from "./group.ts"; import * as Ietf from "./ietf/index.ts"; import { hooks } from "./internal.ts"; @@ -84,7 +85,7 @@ async function session(alpn: string) { const broadcastRoute = origin.route(Path.from("test")); const broadcast = broadcastRoute.broadcast; - const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const remote = wireOf(client).consume(Path.from("test")); const track = remote.track("video").subscribe().ordered(); diff --git a/js/net/src/subscribe_priority.test.ts b/js/net/src/subscribe_priority.test.ts index 7038fff86ee..dc92d380d26 100644 --- a/js/net/src/subscribe_priority.test.ts +++ b/js/net/src/subscribe_priority.test.ts @@ -6,6 +6,7 @@ import { expect, spyOn, test } from "bun:test"; import { yieldNow } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import { accept, connect, type Session } from "./connection/index.ts"; +import { defined } from "./defined.test-util.ts"; import * as Ietf from "./ietf/index.ts"; import { SubscribeUpdate } from "./ietf/subscribe.ts"; import * as Lite from "./lite/index.ts"; @@ -63,7 +64,7 @@ test.each([Lite.ALPN_07_WIP, ...Object.values(Ietf.ALPN)])( const origin = new OriginProducer(); const broadcastRoute = origin.route(path); const broadcast = broadcastRoute.broadcast; - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const [client, server] = await session(protocol, origin); const remote = wireOf(client).consume(path); @@ -102,7 +103,7 @@ test.each(Object.values(Ietf.ALPN))("%s ends a subscription mid-update without a const origin = new OriginProducer(); const broadcastRoute = origin.route(path); const broadcast = broadcastRoute.broadcast; - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const [client, server] = await session(protocol, origin); let closed: Error | null | undefined; void client.closed.then((err) => { @@ -138,7 +139,7 @@ test.each(Object.values(Ietf.ALPN))("%s sends no update when the last subscriber const origin = new OriginProducer(); const broadcastRoute = origin.route(path); const broadcast = broadcastRoute.broadcast; - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const [client, server] = await session(protocol, origin); try { const remote = wireOf(client).consume(path); @@ -164,7 +165,7 @@ test.each(Object.values(Ietf.ALPN))("%s ends the track when an update fails to e const origin = new OriginProducer(); const broadcastRoute = origin.route(path); const broadcast = broadcastRoute.broadcast; - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI })); const [client, server] = await session(protocol, origin); let closed: Error | null | undefined; void client.closed.then((err) => { diff --git a/js/net/src/tail.test.ts b/js/net/src/tail.test.ts index e7f0be2fadd..4db05c85b7b 100644 --- a/js/net/src/tail.test.ts +++ b/js/net/src/tail.test.ts @@ -3,6 +3,7 @@ import { Duration, type Installed, Instant } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import { Once } from "@moq/signals"; import { accept, connect } from "./connection/index.ts"; +import { defined } from "./defined.test-util.ts"; import * as Ietf from "./ietf/index.ts"; import { GRACE as TAIL_GRACE_MS } from "./ledger.ts"; import * as Lite from "./lite/index.ts"; @@ -29,7 +30,7 @@ async function session(protocol: string) { ]); const broadcastRoute = origin.route(Path.from("test")); const broadcast = broadcastRoute.broadcast; - const video = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const video = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const remote = wireOf(client).consume(Path.from("test")); const reader = remote .track("video") diff --git a/js/net/src/terminal.test.ts b/js/net/src/terminal.test.ts index ea603d9fc11..0ff564c8d00 100644 --- a/js/net/src/terminal.test.ts +++ b/js/net/src/terminal.test.ts @@ -1,5 +1,6 @@ import { expect, test } from "bun:test"; import { Producer as BroadcastProducer } from "./broadcast.ts"; +import { defined } from "./defined.test-util.ts"; import { ProtocolViolation, SessionCode, StreamCode } from "./error.ts"; import { hooks } from "./internal.ts"; import { Connection } from "./lite/connection.ts"; @@ -58,7 +59,7 @@ test("a lite protocol violation reaches the subscribed track and its open group" const pair = createMockTransportPair(ALPN_06); const origin = new OriginProducer(); const publication = origin.route(Path.from("room")); - const producer = publication.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const producer = defined(publication.broadcast.createTrack("video", { timescale: Timescale.MILLI })); hooks.appendNext(producer).writeFrame(textFrame("prefix")); const url = new URL("https://example.com"); const client = new Connection({ url, quic: pair.client, version: Version.DRAFT_06 }); diff --git a/js/net/src/untimed.test.ts b/js/net/src/untimed.test.ts index f3722e5b715..9cc3253b9d5 100644 --- a/js/net/src/untimed.test.ts +++ b/js/net/src/untimed.test.ts @@ -4,6 +4,7 @@ import { expect, test } from "bun:test"; import { type Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { accept, connect } from "./connection/index.ts"; +import { defined } from "./defined.test-util.ts"; import * as Ietf from "./ietf/index.ts"; import { hooks } from "./internal.ts"; import * as Lite from "./lite/index.ts"; @@ -88,7 +89,7 @@ async function roundTrip(wire: Wire, timescale: Timescale | undefined, timestamp async function republish(input: BroadcastConsumer): Promise { const subscription = input.track("video").subscribe(); const copy = new BroadcastProducer(); - const video = copy.createTrack("video", await subscription.info()); + const video = defined(copy.createTrack("video", await subscription.info())); void (async () => { try { const groups = subscription.ordered(); diff --git a/js/net/src/wire.ts b/js/net/src/wire.ts index 3290dd1a037..916b76b73d5 100644 --- a/js/net/src/wire.ts +++ b/js/net/src/wire.ts @@ -26,7 +26,7 @@ export interface Broadcast { datagrams(name: string): datagram.Consumer; liveDatagrams(name: string): datagram.Consumer | undefined; /** Create a datagram track, listed unless `listed` is false, as a session's track riding a stream track's subscription. */ - createDatagrams(name: string, info: Partial, listed?: boolean): datagram.Producer; + createDatagrams(name: string, info: Partial, listed?: boolean): datagram.Producer | undefined; requestedDatagrams(): Promise; subscribe(name: string, options?: track.Subscription): track.Subscriber; /** The track's properties; `hold` keeps the track wanted until it aborts, the way a held TRACK stream does, and aborting it before the answer abandons the lookup. */ diff --git a/js/publish/src/broadcast.ts b/js/publish/src/broadcast.ts index c6bdc009485..0c2b6c32905 100644 --- a/js/publish/src/broadcast.ts +++ b/js/publish/src/broadcast.ts @@ -515,6 +515,7 @@ export class Broadcast { // Catalog JSON is small and repetitive. compression: "deflate", }); + if (!track) throw new Error(`the track ${Broadcast.CATALOG_TRACK} already exists`); effect.cleanup(() => { track.finish(); track.close(); @@ -564,6 +565,7 @@ export class Broadcast { entry.name, rendition.kind === "video" ? { ...info, refresh: VIDEO_REFRESH } : info, ); + if (!entry.track) throw new Error(`the track ${entry.name} already exists`); } entry.owner = rendition; const served = entry.track; diff --git a/js/room/src/chat.test.ts b/js/room/src/chat.test.ts index cae3306d740..6f95579310d 100644 --- a/js/room/src/chat.test.ts +++ b/js/room/src/chat.test.ts @@ -3,6 +3,7 @@ import { Duration } from "@moq/clock"; import { Manual } from "@moq/clock/test"; import { Broadcast, Time } from "@moq/net"; import { HISTORY, info, Publisher, Subscriber, TRACK } from "./chat.ts"; +import { defined } from "./defined.test-util.ts"; test("chat expires ten-second history and late readers only see retained messages", async () => { const clock = new Manual(); @@ -38,7 +39,7 @@ test("chat expires ten-second history and late readers only see retained message test("chat rejects non-string window records and propagates track failures", async () => { const broadcast = new Broadcast.Producer(); - const track = broadcast.createTrack(TRACK, info()); + const track = defined(broadcast.createTrack(TRACK, info())); const subscriber = Subscriber.subscribe(broadcast.consume()); try { track.writeFrame({ diff --git a/js/room/src/chat.ts b/js/room/src/chat.ts index d199cd8b2a4..7f9473c758c 100644 --- a/js/room/src/chat.ts +++ b/js/room/src/chat.ts @@ -32,7 +32,9 @@ export class Publisher { /** Create the chat track on a broadcast. */ static create(broadcast: Broadcast.Producer): Publisher { - return new Publisher(broadcast.createTrack(TRACK, info())); + const track = broadcast.createTrack(TRACK, info()); + if (!track) throw new Error(`the track ${TRACK} already exists`); + return new Publisher(track); } /** Publish a chat window over an existing track. */ diff --git a/js/room/src/defined.test-util.ts b/js/room/src/defined.test-util.ts new file mode 100644 index 00000000000..b66104d627b --- /dev/null +++ b/js/room/src/defined.test-util.ts @@ -0,0 +1,5 @@ +/** `value`, failing the test when it is `undefined`, as a name or group already taken. @internal */ +export function defined(value: T | undefined): T { + if (value === undefined) throw new Error("expected a value"); + return value; +} diff --git a/js/room/src/metadata.test.ts b/js/room/src/metadata.test.ts index d2a891d3a8e..4a6693cd27d 100644 --- a/js/room/src/metadata.test.ts +++ b/js/room/src/metadata.test.ts @@ -4,6 +4,7 @@ import * as Net from "@moq/net"; import type * as Publish from "@moq/publish"; import { Effect, Signal } from "@moq/signals"; import type * as Watch from "@moq/watch"; +import { defined } from "./defined.test-util.ts"; import { consume, type ExtendedCatalog, type Preview, serve, TRACK, userFields } from "./metadata.ts"; // Drain queued effects and their asynchronous subscription continuations. @@ -49,10 +50,10 @@ test("metadata clears when entries disappear or broadcast becomes inactive", asy }); const active = new Signal(net.consume()); const user = new Json.Snapshot.Producer({ - track: net.createTrack(TRACK.user, { timescale: Net.Time.Timescale.MILLI }), + track: defined(net.createTrack(TRACK.user, { timescale: Net.Time.Timescale.MILLI })), }); const preview = new Json.Snapshot.Producer({ - track: net.createTrack(TRACK.preview, { timescale: Net.Time.Timescale.MILLI }), + track: defined(net.createTrack(TRACK.preview, { timescale: Net.Time.Timescale.MILLI })), }); user.update({ name: "Alice" }, Net.Time.Timestamp.now()); preview.update({ info: { video: true } }, Net.Time.Timestamp.now()); @@ -84,10 +85,10 @@ test("metadata refuses values that do not match their schema and keeps the last const active = new Signal(net.consume()); // Unvalidated producers, standing in for a remote publisher that sends anything. const user = new Json.Snapshot.Producer({ - track: net.createTrack(TRACK.user, { timescale: Net.Time.Timescale.MILLI }), + track: defined(net.createTrack(TRACK.user, { timescale: Net.Time.Timescale.MILLI })), }); const preview = new Json.Snapshot.Producer({ - track: net.createTrack(TRACK.preview, { timescale: Net.Time.Timescale.MILLI }), + track: defined(net.createTrack(TRACK.preview, { timescale: Net.Time.Timescale.MILLI })), }); const warn = spyOn(console, "warn").mockImplementation(() => {}); const consumed = consume({ out: { catalog, active } } as unknown as Watch.Broadcast); diff --git a/js/room/src/metadata.ts b/js/room/src/metadata.ts index 71c8c215a94..fcb2683cdfd 100644 --- a/js/room/src/metadata.ts +++ b/js/room/src/metadata.ts @@ -184,6 +184,7 @@ function serveSnapshot( maxAge: Duration.millis(86_400_000), priority: PRIORITY, }); + if (!track) throw new Error(`the track ${name} already exists`); effect.cleanup(() => { track.finish(); track.close(); diff --git a/js/stats/src/defined.test-util.ts b/js/stats/src/defined.test-util.ts new file mode 100644 index 00000000000..b66104d627b --- /dev/null +++ b/js/stats/src/defined.test-util.ts @@ -0,0 +1,5 @@ +/** `value`, failing the test when it is `undefined`, as a name or group already taken. @internal */ +export function defined(value: T | undefined): T { + if (value === undefined) throw new Error("expected a value"); + return value; +} diff --git a/js/stats/src/stats.test.ts b/js/stats/src/stats.test.ts index ae0d2340180..41e13c6ebec 100644 --- a/js/stats/src/stats.test.ts +++ b/js/stats/src/stats.test.ts @@ -1,6 +1,7 @@ import { expect, test } from "bun:test"; import * as Json from "@moq/json"; import { type Broadcast, Origin, Path, Time } from "@moq/net"; +import { defined } from "./defined.test-util.ts"; import { Consumer, Nodes, @@ -17,7 +18,7 @@ let keys = 0n; const key = () => Time.Timestamp.unscaled(keys++); function publish(broadcast: Broadcast.Producer, name: string) { - return new Json.Snapshot.Producer({ track: broadcast.createTrack(name) }); + return new Json.Snapshot.Producer({ track: defined(broadcast.createTrack(name)) }); } test("discovers each node under the prefix", async () => { diff --git a/js/watch/src/audio/decoder.test.ts b/js/watch/src/audio/decoder.test.ts index f0aa8e02b4e..36265d812ec 100644 --- a/js/watch/src/audio/decoder.test.ts +++ b/js/watch/src/audio/decoder.test.ts @@ -7,6 +7,7 @@ import * as Container from "@moq/hang/container"; import * as Moq from "@moq/net"; import { Effect, Signal } from "@moq/signals"; import type { Broadcast } from "../broadcast"; +import { defined } from "../defined.test-util.ts"; import { DELAY_MAX, type Delay, STRETCH, Sync } from "../sync"; import { Decoder as VideoDecoder } from "../video/decoder"; import { Source as VideoSource } from "../video/source"; @@ -342,7 +343,7 @@ async function play(initial: Delay, buffered = false, cmaf = false) { // Published, so finishing it declares the subscription's end as a publisher's FIN does. The // reads themselves come from `feed`. const publish = () => - producer.createTrack("audio", { timescale: Moq.Time.Timescale.MILLI, maxAge: Container.MAX_AGE }); + defined(producer.createTrack("audio", { timescale: Moq.Time.Timescale.MILLI, maxAge: Container.MAX_AGE })); let track = publish(); let audio = Catalog.AudioConfigSchema.parse({ codec: "opus", @@ -1587,7 +1588,9 @@ async function livePlayback(burst: number) { const sync = new Sync({ delay: new Signal("auto") }); // Published before the decoder subscribes, since a broadcast with no request handler refuses // an unknown track. - let track = producer.createTrack("audio", { timescale: Moq.Time.Timescale.MILLI, maxAge: Container.MAX_AGE }); + let track = defined( + producer.createTrack("audio", { timescale: Moq.Time.Timescale.MILLI, maxAge: Container.MAX_AGE }), + ); const enabled = new Signal(true); const decoder = new Decoder({ source, sync, enabled }); @@ -1626,7 +1629,9 @@ async function livePlayback(burst: number) { rename(name: string, patch: Record = {}) { track.finish(); track.close(); - track = producer.createTrack(name, { timescale: Moq.Time.Timescale.MILLI, maxAge: Container.MAX_AGE }); + track = defined( + producer.createTrack(name, { timescale: Moq.Time.Timescale.MILLI, maxAge: Container.MAX_AGE }), + ); sequence = 0n; catalog.set({ audio: { renditions: { [name]: Catalog.AudioConfigSchema.parse({ ...audio, ...patch }) } } }); }, @@ -1634,7 +1639,9 @@ async function livePlayback(burst: number) { move(path: string) { media.peek().close(); producer = new Moq.Origin.Producer().route(Moq.Path.from(path), { hidden: true }).broadcast; - track = producer.createTrack("audio", { timescale: Moq.Time.Timescale.MILLI, maxAge: Container.MAX_AGE }); + track = defined( + producer.createTrack("audio", { timescale: Moq.Time.Timescale.MILLI, maxAge: Container.MAX_AGE }), + ); sequence = 0n; media.set(producer.consume()); }, diff --git a/js/watch/src/broadcast.test.ts b/js/watch/src/broadcast.test.ts index 28caeb2acab..44e37267d31 100644 --- a/js/watch/src/broadcast.test.ts +++ b/js/watch/src/broadcast.test.ts @@ -10,6 +10,7 @@ import { key } from "../../json/src/key.test-util.ts"; import * as Mint from "../../net/src/mint.ts"; import { wireOf } from "../../net/src/wire.ts"; import { Broadcast } from "./broadcast"; +import { defined } from "./defined.test-util.ts"; function publish(origin: Origin.Producer, path: Path.Valid) { return origin.route(path).broadcast; @@ -111,7 +112,7 @@ describe("unsupported catalog", () => { const owner = new Origin.Producer(); const name = Path.from("room/live.hang"); const published = publish(owner, name); - const track = published.createTrack(Catalog.TRACK, { compression: compress ? "deflate" : "none" }); + const track = defined(published.createTrack(Catalog.TRACK, { compression: compress ? "deflate" : "none" })); const producer = new Json.Snapshot.Producer({ track, deltas: false }); const enabled = new Signal(true); const source = new Broadcast({ origin: owner, name, catalogFormat: "hang", enabled }); @@ -156,7 +157,7 @@ for (const driven of [true, false]) { const name = Path.from("room/live.hang"); const published = publish(owner, name); const producer = new Json.Snapshot.Producer({ - track: published.createTrack(Catalog.TRACK), + track: defined(published.createTrack(Catalog.TRACK)), deltas: false, }); const tail = new Signal(true); @@ -207,7 +208,7 @@ it("reports a catalog that ends empty as offline", async () => { const name = Path.from("room/live.hang"); const published = publish(owner, name); const producer = new Json.Snapshot.Producer({ - track: published.createTrack(Catalog.TRACK), + track: defined(published.createTrack(Catalog.TRACK)), deltas: false, }); const source = new Broadcast({ origin: owner, name, catalogFormat: "hang", enabled: true }); @@ -1171,13 +1172,15 @@ it("subscribes a cross-broadcast MSF rendition on its namespace", async () => { const owner = new Origin.Producer(); const catalogBroadcast = publish(owner, Path.from("room/catalog.msf")); const referenced = publish(owner, Path.from("room/left")); - catalogBroadcast - .createTrack("video") - .writeFrame({ payload: new Uint8Array([1]), timestamp: Moq.Time.Timestamp.unscaled(0n) }); - referenced - .createTrack("video") - .writeFrame({ payload: new Uint8Array([2]), timestamp: Moq.Time.Timestamp.unscaled(0n) }); - catalogBroadcast.createTrack("catalog").writeFrame({ + defined(catalogBroadcast.createTrack("video")).writeFrame({ + payload: new Uint8Array([1]), + timestamp: Moq.Time.Timestamp.unscaled(0n), + }); + defined(referenced.createTrack("video")).writeFrame({ + payload: new Uint8Array([2]), + timestamp: Moq.Time.Timestamp.unscaled(0n), + }); + defined(catalogBroadcast.createTrack("catalog")).writeFrame({ payload: Msf.encode({ tracks: [ { diff --git a/js/watch/src/defined.test-util.ts b/js/watch/src/defined.test-util.ts new file mode 100644 index 00000000000..b66104d627b --- /dev/null +++ b/js/watch/src/defined.test-util.ts @@ -0,0 +1,5 @@ +/** `value`, failing the test when it is `undefined`, as a name or group already taken. @internal */ +export function defined(value: T | undefined): T { + if (value === undefined) throw new Error("expected a value"); + return value; +} diff --git a/js/watch/src/include.test.ts b/js/watch/src/include.test.ts index 189e576810b..9a0eaba68aa 100644 --- a/js/watch/src/include.test.ts +++ b/js/watch/src/include.test.ts @@ -8,6 +8,7 @@ import { key } from "../../json/src/key.test-util.ts"; import * as Mint from "../../net/src/mint.ts"; import { wireOf } from "../../net/src/wire.ts"; import { Broadcast } from "./broadcast"; +import { defined } from "./defined.test-util.ts"; import { Source } from "./video/source"; import { stubSupport } from "./webcodecs.test-util"; @@ -43,12 +44,13 @@ it("reads a listed include's catalog but no media, keeping its rendition IDs its const origin = new Origin.Producer(); const parent = publish(origin, "room/main.hang"); const include = publish(origin, "room/extra.hang"); - const includeCatalog = include.createTrack(Catalog.TRACK); + const includeCatalog = defined(include.createTrack(Catalog.TRACK)); const catalog = new Json.Snapshot.Producer({ track: includeCatalog, deltas: false }); - parent - .createTrack("video") - .writeFrame({ payload: new TextEncoder().encode("source frames"), timestamp: Time.Timestamp.unscaled(0n) }); - const includeVideo = include.createTrack("video"); + defined(parent.createTrack("video")).writeFrame({ + payload: new TextEncoder().encode("source frames"), + timestamp: Time.Timestamp.unscaled(0n), + }); + const includeVideo = defined(include.createTrack("video")); includeVideo.writeFrame({ payload: new TextEncoder().encode("include frames"), timestamp: Time.Timestamp.unscaled(0n), @@ -184,7 +186,7 @@ it("reports an include outside the origin's scope as an error, leaving the paren it("tracks the include entry without reopening it on unrelated catalog updates", async () => { const origin = new Origin.Producer(); publish(origin, "room/main.hang"); - const firstCatalog = publish(origin, "room/first.hang").createTrack(Catalog.TRACK); + const firstCatalog = defined(publish(origin, "room/first.hang").createTrack(Catalog.TRACK)); publish(origin, "room/second.hang"); const catalog = new Signal(Catalog.RootSchema.parse({ include: { extra: { broadcast: "./first.hang" } } })); const parent = new Broadcast({ @@ -315,7 +317,7 @@ it("never reads an include of another instance, but reads a minted one", async ( publish(origin, "room/main.hang"); const served = Instance.random(); const proven = publish(origin, "room/proven.hang", served); - const track = proven.createTrack(Catalog.TRACK); + const track = defined(proven.createTrack(Catalog.TRACK)); // A route over a wire that carries no instance has one its session minted. publish(origin, "room/plain.hang", Mint.fresh()); const named = Instance.random(); @@ -361,7 +363,7 @@ it("shares the parent's resolution, so a new instance checks the held handle", a const origin = new Origin.Producer(); const [served, other] = [Instance.random(), Instance.random()]; publish(origin, "room/main.hang", served); - const extraCatalog = publish(origin, "room/extra.hang", served).createTrack(Catalog.TRACK); + const extraCatalog = defined(publish(origin, "room/extra.hang", served).createTrack(Catalog.TRACK)); const entries = (instance?: Instance.Valid) => Catalog.RootSchema.parse({ include: { @@ -424,19 +426,19 @@ it("offers every include's renditions to selection, subscribing only the selecte using _decoder = stubSupport({ video: () => true }); const origin = new Origin.Producer(); const parent = publish(origin, "room/main.hang"); - const parentHd = parent.createTrack("hd"); + const parentHd = defined(parent.createTrack("hd")); const served = Instance.random(); const ladder = publish(origin, "room/ladder.hang", served); - const ladderTrack = ladder.createTrack(Catalog.TRACK); + const ladderTrack = defined(ladder.createTrack(Catalog.TRACK)); const ladderCatalog = new Json.Snapshot.Producer({ track: ladderTrack, deltas: false }); const rung = (name: string) => { - const track = ladder.createTrack(name); + const track = defined(ladder.createTrack(name)); track.writeFrame({ payload: new TextEncoder().encode(name), timestamp: key() }); return track; }; const [high, low, ladderHd] = [rung("720p"), rung("360p"), rung("hd")]; - const remote = publish(origin, "room/remote.hang").createTrack("remote"); - const nested = publish(origin, "room/nested.hang").createTrack(Catalog.TRACK); + const remote = defined(publish(origin, "room/remote.hang").createTrack("remote")); + const nested = defined(publish(origin, "room/nested.hang").createTrack(Catalog.TRACK)); const sized = (width: number, height: number, bitrate: number): Catalog.VideoConfig => Catalog.VideoConfigSchema.parse({ ...video("avc1.42001f"), codedWidth: width, codedHeight: height, bitrate }); @@ -547,7 +549,7 @@ it("dedupes an include's rendition only against a usable one", async () => { const serve = (instance: Instance.Valid) => { const broadcast = publish(origin, "room/extra.hang", instance); const catalog = new Json.Snapshot.Producer({ - track: broadcast.createTrack(Catalog.TRACK), + track: defined(broadcast.createTrack(Catalog.TRACK)), deltas: false, }); catalog.update(Catalog.RootSchema.parse({ video: { renditions: { v: video("vp8") } } }), key()); @@ -587,10 +589,10 @@ it("takes a missing section's display settings from the include whose renditions publish(origin, "room/main.hang"); const serve = (path: string, value: Catalog.Root) => { const broadcast = publish(origin, path); - new Json.Snapshot.Producer({ track: broadcast.createTrack(Catalog.TRACK), deltas: false }).update( - value, - key(), - ); + new Json.Snapshot.Producer({ + track: defined(broadcast.createTrack(Catalog.TRACK)), + deltas: false, + }).update(value, key()); return broadcast; }; // The first include's only rendition reads a broadcast nobody announced, so none of it is listed. diff --git a/js/watch/src/offline.test.ts b/js/watch/src/offline.test.ts index 6c3a73a459d..b5f45e699f7 100644 --- a/js/watch/src/offline.test.ts +++ b/js/watch/src/offline.test.ts @@ -11,6 +11,7 @@ import { accept, connect } from "../../net/src/connection/index.ts"; import * as Lite from "../../net/src/lite/index.ts"; import { createMockTransportPair, waitFor } from "../../net/src/mock.ts"; import { Broadcast } from "./broadcast"; +import { defined } from "./defined.test-util.ts"; import type MoqWatch from "./element"; import { offlineIndicator } from "./ui/components/offline-indicator"; import { refusedIndicator } from "./ui/components/refused-indicator"; @@ -23,7 +24,7 @@ test("a live broadcast reads connecting until connected and again once the conne const name = Path.from("live.hang"); const route = relay.route(name); const producer = new Json.Snapshot.Producer({ - track: route.broadcast.createTrack(Catalog.TRACK), + track: defined(route.broadcast.createTrack(Catalog.TRACK)), deltas: false, }); producer.update({}, key()); diff --git a/js/watch/src/retention.test.ts b/js/watch/src/retention.test.ts index f593295548a..0b9bf49a4ac 100644 --- a/js/watch/src/retention.test.ts +++ b/js/watch/src/retention.test.ts @@ -5,6 +5,7 @@ import { Container } from "@moq/hang"; import * as Moq from "@moq/net"; import { Time } from "@moq/net"; import { Derived, Effect, Signal } from "@moq/signals"; +import { defined } from "./defined.test-util.ts"; import { nextMedia, subscribeMedia } from "./media"; import { Sync } from "./sync"; @@ -95,7 +96,7 @@ test("a long subscription through the player path leaves nothing behind", async const broadcast = new Moq.Broadcast.Producer(); // The track's cache keeps every group here for its fixed 30s idle window whatever maxAge the // track declares, and holds no reactions or listeners while it does. - const track = broadcast.createTrack("audio", { timescale: Time.Timescale.MILLI }); + const track = defined(broadcast.createTrack("audio", { timescale: Time.Timescale.MILLI })); const format = new Container.Legacy.Format("audio"); const producer = new Container.Legacy.Producer(track, format); diff --git a/js/watch/src/video/decoder.test.ts b/js/watch/src/video/decoder.test.ts index 7f99848bf73..321752e0ba0 100644 --- a/js/watch/src/video/decoder.test.ts +++ b/js/watch/src/video/decoder.test.ts @@ -9,6 +9,7 @@ import { Effect, Signal } from "@moq/signals"; import { ringSamples } from "../audio/latency"; import { AudioRingBuffer } from "../audio/ring-buffer"; import type { Broadcast } from "../broadcast"; +import { defined } from "../defined.test-util.ts"; import { type Delay, Sync, Track } from "../sync"; import { stubSupport } from "../webcodecs.test-util"; import { Decoder } from "./decoder"; @@ -387,7 +388,9 @@ async function guardedPlayback( // Published before the decoder subscribes, since a broadcast with no request handler refuses // an unknown track. const track = live - ? mediaProducer.createTrack("video", { timescale: Moq.Time.Timescale.MILLI, maxAge: Container.MAX_AGE }) + ? defined( + mediaProducer.createTrack("video", { timescale: Moq.Time.Timescale.MILLI, maxAge: Container.MAX_AGE }), + ) : undefined; const decoder = new Decoder({ source, sync, enabled }); // Another track on the same clock, whose arrivals the tests drive by hand. @@ -447,7 +450,12 @@ async function guardedPlayback( ? new Moq.Origin.Producer().route(Moq.Path.from(path), { hidden: true }).broadcast : new Moq.Broadcast.Producer(); const track = live - ? mediaProducer.createTrack("video", { timescale: Moq.Time.Timescale.MILLI, maxAge: Container.MAX_AGE }) + ? defined( + mediaProducer.createTrack("video", { + timescale: Moq.Time.Timescale.MILLI, + maxAge: Container.MAX_AGE, + }), + ) : undefined; media.set(mediaProducer.consume()); return track; @@ -1189,10 +1197,12 @@ it("a renamed video track keeps the delay, so audio neither skips nor goes silen (playback.track as Moq.Track.Producer).close(); playback.switchRendition("video/1"); video.replace( - playback.producer.createTrack("video/1", { - timescale: Moq.Time.Timescale.MILLI, - maxAge: Container.MAX_AGE, - }), + defined( + playback.producer.createTrack("video/1", { + timescale: Moq.Time.Timescale.MILLI, + maxAge: Container.MAX_AGE, + }), + ), ); await run(20_000, 26_000); diff --git a/rs/hang/examples/video.rs b/rs/hang/examples/video.rs index 8dad03fa532..310775af02d 100644 --- a/rs/hang/examples/video.rs +++ b/rs/hang/examples/video.rs @@ -65,7 +65,9 @@ fn create_track(broadcast: &mut moq_net::broadcast::Producer) -> anyhow::Result< catalog.video.insert(video_track, video_config)?; // Publish the catalog as a "catalog.json" track in the broadcast. - let catalog_track = broadcast.create_track(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info()).context("the track already exists")?; + let catalog_track = broadcast + .create_track(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info()) + .context("the track already exists")?; // This catalog never changes, so its one group starts at zero, where the media's timeline does. let mut group = catalog_track.append_group(moq_net::Timestamp::ZERO)?; group.write_frame(moq_net::Timestamp::ZERO, catalog.to_json()?)?; @@ -74,7 +76,9 @@ fn create_track(broadcast: &mut moq_net::broadcast::Producer) -> anyhow::Result< // Actually create the media track now. // track_info() pins the microsecond timescale that the legacy container encodes with, and // declares the publisher priority so a subscriber orders this against a broadcast's audio. - let track = broadcast.create_track(video_track, hang::container::track_info(hang::catalog::PRIORITY.video)).context("the track already exists")?; + let track = broadcast + .create_track(video_track, hang::container::track_info(hang::catalog::PRIORITY.video)) + .context("the track already exists")?; Ok(track) } diff --git a/rs/moq-archive/src/consumer/mod.rs b/rs/moq-archive/src/consumer/mod.rs index f0a9031cd02..f4cf1a1e424 100644 --- a/rs/moq-archive/src/consumer/mod.rs +++ b/rs/moq-archive/src/consumer/mod.rs @@ -242,7 +242,10 @@ impl Consumer { fn apply(&mut self, refreshed: Refreshed) -> Result<()> { for (name, info, index) in refreshed.added { - let producer = self.broadcast.create_track(name.as_str(), info).ok_or(moq_net::Error::Duplicate)?; + let producer = self + .broadcast + .create_track(name.as_str(), info) + .ok_or(moq_net::Error::Duplicate)?; let dynamic = producer.requests(); self.tracks.insert( name, diff --git a/rs/moq-boy/src/status.rs b/rs/moq-boy/src/status.rs index 6dcc8dcb12d..48a56c297b6 100644 --- a/rs/moq-boy/src/status.rs +++ b/rs/moq-boy/src/status.rs @@ -41,14 +41,15 @@ pub struct StatusPublisher { impl StatusPublisher { pub fn new(broadcast: &mut moq_net::broadcast::Producer) -> anyhow::Result { - let producer = broadcast.create_track( - "status", - moq_net::track::Info::default() - .with_timescale(moq_net::Timescale::MILLI) - // A joiner asks for a fresh snapshot once the deltas outweigh eight of them. - .with_refresh(moq_net::track::Refresh::default().with_ratio(8)), - ) - .ok_or_else(|| anyhow::anyhow!("the status track already exists"))?; + let producer = broadcast + .create_track( + "status", + moq_net::track::Info::default() + .with_timescale(moq_net::Timescale::MILLI) + // A joiner asks for a fresh snapshot once the deltas outweigh eight of them. + .with_refresh(moq_net::track::Refresh::default().with_ratio(8)), + ) + .ok_or_else(|| anyhow::anyhow!("the status track already exists"))?; Ok(Self { producer: moq_json::snapshot::Producer::new(producer, moq_json::snapshot::Config::default()), diff --git a/rs/moq-e2ee/src/tests.rs b/rs/moq-e2ee/src/tests.rs index 0591fcd996d..99f5d3409fc 100644 --- a/rs/moq-e2ee/src/tests.rs +++ b/rs/moq-e2ee/src/tests.rs @@ -780,7 +780,11 @@ fn resolve(subscribing: &kio::Pending) -> Result Fixture { async fn grouped_roundtrip(version: &str, payload: &[u8]) { kio::clock::timeout(TEST_TIMEOUT, async { let fixture = connect_protected(version.parse().unwrap(), "video").await; - let mut producer = fixture.producer.create_track("video", timed()).unwrap().expect("a free name"); + let mut producer = fixture + .producer + .create_track("video", timed()) + .unwrap() + .expect("a free name"); let mut consumer = fixture .consumer .subscribe( @@ -125,7 +129,11 @@ async fn grouped_over_ietf() { async fn datagram_roundtrip(version: &str, plaintext: &[u8]) { kio::clock::timeout(TEST_TIMEOUT, async { let fixture = connect_protected(version.parse().unwrap(), "audio").await; - let mut producer = fixture.producer.create_datagrams("audio", timed_datagrams()).unwrap().expect("a free name"); + let mut producer = fixture + .producer + .create_datagrams("audio", timed_datagrams()) + .unwrap() + .expect("a free name"); let mut consumer = fixture.consumer.datagrams("audio").unwrap(); // A remote subscriber is live once its request reaches the publisher, which sees its priority. consumer.set_priority(1); diff --git a/rs/moq-mux/src/catalog/producer.rs b/rs/moq-mux/src/catalog/producer.rs index 7a2e1d0b7f7..1a7bb6c3257 100644 --- a/rs/moq-mux/src/catalog/producer.rs +++ b/rs/moq-mux/src/catalog/producer.rs @@ -889,11 +889,7 @@ impl Producer { /// handed out, for a rendition whose identity changed: a name always means the same content. /// /// A successor's own successor counts on from the same base, so `v/1` is followed by `v/2`. - pub(crate) fn fresh_track( - &self, - name: &str, - info: moq_net::track::Info, - ) -> moq_net::track::Producer { + pub(crate) fn fresh_track(&self, name: &str, info: moq_net::track::Info) -> moq_net::track::Producer { let mut state = take(&self.current); let base = match name.rsplit_once('/') { Some((base, n)) if n.parse::().is_ok() && state.revisions.contains_key(base) => base, diff --git a/rs/moq-mux/src/container/fmp4/import.rs b/rs/moq-mux/src/container/fmp4/import.rs index 88cada2b367..b93d302745c 100644 --- a/rs/moq-mux/src/container/fmp4/import.rs +++ b/rs/moq-mux/src/container/fmp4/import.rs @@ -607,8 +607,10 @@ impl Import { // Declare the track at the fMP4's native timescale, which the moq-hang draft requires // of a CMAF track: frame timestamps are emitted at this same scale (see `extract`), so // each one carries its fragment's earliest presentation time exactly. - let track = self.broadcast.unique_track(".m4s", - self.catalog.track_info(kind.priority()).with_timescale(timescale)); + let track = self.broadcast.unique_track( + ".m4s", + self.catalog.track_info(kind.priority()).with_timescale(timescale), + ); // Join the broadcast's join interval, measured: an fMP4 declares no GOP. let member = Some(self.catalog.join(None)); @@ -655,8 +657,9 @@ impl Import { Kind::Video => (".mp4-v", crate::container::Kind::Video), Kind::Audio => (".mp4-a", crate::container::Kind::Audio), }; - let track = self.broadcast.unique_track(suffix, - self.catalog.track_info(kind.priority())); + let track = self + .broadcast + .unique_track(suffix, self.catalog.track_info(kind.priority())); let wire = crate::catalog::hang::Container::new(&Container::Legacy, wire_kind)?; Ok(match kind { Kind::Video => Output::Video(reserved.video(track, wire, self.init_video(trak, moov)?)?), @@ -686,8 +689,9 @@ impl Import { // The picker label is the HandlerBox name; `vlab` is an opaque source identifier. config.label = (!trak.mdia.hdlr.name.is_empty()).then(|| trak.mdia.hdlr.name.clone()); let wire = crate::catalog::hang::Container::new(&config.container, crate::container::Kind::Data)?; - let track = self.broadcast.unique_track(".mp4-t", - self.catalog.track_info(hang::catalog::PRIORITY.text)); + let track = self + .broadcast + .unique_track(".mp4-t", self.catalog.track_info(hang::catalog::PRIORITY.text)); let producer = reserved.text(track, wire, config)?; self.text.insert( trak.tkhd.track_id, diff --git a/rs/moq-mux/src/container/mkv/import.rs b/rs/moq-mux/src/container/mkv/import.rs index 0297806204c..415a18ae3f2 100644 --- a/rs/moq-mux/src/container/mkv/import.rs +++ b/rs/moq-mux/src/container/mkv/import.rs @@ -655,8 +655,9 @@ impl Import { return Err(Error::StreamedCmaf.into()); } - let track = self.broadcast.unique_track(suffix, - self.catalog.track_info(kind.priority())); + let track = self + .broadcast + .unique_track(suffix, self.catalog.track_info(kind.priority())); // Build the media producer before publishing the rendition. It is fallible (its // timeline track can collide), and a rendition published for a track we then fail // to produce would be advertised to consumers but never served. diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index 9fea380a753..f65d834fdac 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -1767,8 +1767,7 @@ async fn export_scte35_roundtrip() { // Create and write the SCTE-35 cue track BEFORE moving `broadcast` into // `Import` (which consumes it); the producer stays alive so the exporter can // subscribe to the retained track. - let scte = broadcast - .unique_track(".scte35", hang::container::track_info(hang::catalog::PRIORITY.video)); + let scte = broadcast.unique_track(".scte35", hang::container::track_info(hang::catalog::PRIORITY.video)); let scte_name = scte.name().to_string(); { let track = tscat::Track { @@ -1907,8 +1906,7 @@ async fn assert_unknown_stream_type(pes: bool) { ) .unwrap(); let reserved = catalog.reserve(); - let track = broadcast - .unique_track(".opaque", hang::container::track_info(hang::catalog::PRIORITY.video)); + let track = broadcast.unique_track(".opaque", hang::container::track_info(hang::catalog::PRIORITY.video)); let mut entry = tscat::Track::new(PID); let payload = match pes { true => { @@ -2010,8 +2008,7 @@ async fn export_pes_packet_roundtrip() { // Build the PES track BEFORE moving `broadcast` into `Import`; the // producer stays alive so the exporter can subscribe to the retained track. - let data_track = broadcast - .unique_track(".data", hang::container::track_info(hang::catalog::PRIORITY.video)); + let data_track = broadcast.unique_track(".data", hang::container::track_info(hang::catalog::PRIORITY.video)); let data_name = data_track.name().to_string(); { let mut track = tscat::Track::new(DATA_PID); diff --git a/rs/moq-mux/src/container/ts/release_test.rs b/rs/moq-mux/src/container/ts/release_test.rs index bc30691d2c0..530271ccc48 100644 --- a/rs/moq-mux/src/container/ts/release_test.rs +++ b/rs/moq-mux/src/container/ts/release_test.rs @@ -126,8 +126,7 @@ fn republish_cut( let cut = cut.to_vec(); let mut broadcast = moq_net::broadcast::Info::new().produce(); let mut catalog = crate::catalog::Producer::new(&mut broadcast, config()).unwrap(); - let track = broadcast - .unique_track(".m2ts", catalog.track_info(hang::catalog::PRIORITY.video)); + let track = broadcast.unique_track(".m2ts", catalog.track_info(hang::catalog::PRIORITY.video)); let name = track.name().to_string(); catalog .mutate(|catalog| catalog.ext.mpegts.passthrough = Some(PassthroughTrack::new(name))) diff --git a/rs/moq-mux/src/container/ts/revision_test.rs b/rs/moq-mux/src/container/ts/revision_test.rs index a91eed9fe9c..61f53a55243 100644 --- a/rs/moq-mux/src/container/ts/revision_test.rs +++ b/rs/moq-mux/src/container/ts/revision_test.rs @@ -1474,8 +1474,7 @@ async fn a_revision_out_before_the_one_it_follows_takes_its_version() { // A cue and an AAC track start together, the cue muxed first, on the lower PID: its // revision waits with it for its placement, the AAC track's goes out now. - let track = broadcast - .unique_track(".scte35", hang::container::track_info(hang::catalog::PRIORITY.video)); + let track = broadcast.unique_track(".scte35", hang::container::track_info(hang::catalog::PRIORITY.video)); let entry = super::catalog::Track { pid: DATA_PID, descriptors: Vec::new(), @@ -1556,8 +1555,7 @@ async fn a_stream_taking_a_pid_over_leaves_the_buffer_before_it() { let _finished = before.finish().unwrap(); live(&mut export, &mut frames, start, &mut [(&mut first, 0x21)], 3_000, 6_000).await; - let track = broadcast - .unique_track(".private", hang::container::track_info(hang::catalog::PRIORITY.video)); + let track = broadcast.unique_track(".private", hang::container::track_info(hang::catalog::PRIORITY.video)); let entry = super::catalog::Track { pid: DATA_PID, descriptors: Vec::new(), diff --git a/rs/moq-net/src/coding/writer.rs b/rs/moq-net/src/coding/writer.rs index 8927d7625c0..15c93815e29 100644 --- a/rs/moq-net/src/coding/writer.rs +++ b/rs/moq-net/src/coding/writer.rs @@ -650,11 +650,7 @@ mod tests { self.0.lock().unwrap().written } - fn poll_acked( - &self, - _: &kio::Waiter, - offset: &u64, - ) -> Poll> { + fn poll_acked(&self, _: &kio::Waiter, offset: &u64) -> Poll> { let mut state = self.0.lock().unwrap(); match () { // As the trait's default answers. diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index d5d8c8f3fbc..8403423b294 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -1652,13 +1652,14 @@ impl Serving { match datagrams.poll_info(waiter) { Poll::Ready(Ok(info)) => { let local = crate::broadcast::Producer::new(crate::broadcast::Info::default()); - let producer = local.create_track( - request.msg.track_name.as_ref(), - track::Info::default() - .with_timescale(info.timescale) - .with_priority(info.priority), - ) - .expect("a fresh broadcast holds no track"); + let producer = local + .create_track( + request.msg.track_name.as_ref(), + track::Info::default() + .with_timescale(info.timescale) + .with_priority(info.priority), + ) + .expect("a fresh broadcast holds no track"); let cache = producer.consume(); let mut serve = TrackServe::new( request.publisher.session.clone(), @@ -7289,11 +7290,7 @@ impl crate::transport::poll::SendStream f self.inner.lock().unwrap().stream.offset() } - fn poll_acked( - &self, - waiter: &kio::Waiter, - offset: &Self::Offset, - ) -> Poll> { + fn poll_acked(&self, waiter: &kio::Waiter, offset: &Self::Offset) -> Poll> { self.inner.lock().unwrap().stream.poll_acked(waiter, offset) } @@ -15175,7 +15172,13 @@ mod serve_tests { let request = h._broadcast.broadcast().reserve_track("cam").unwrap(); let dynamic = request.requests(); let fetching = request.consume().fetch_group(4, None); - let mut fetched = dynamic.requested_fill_group().await.unwrap().accept(None).unwrap().expect("a fresh group"); + let mut fetched = dynamic + .requested_fill_group() + .await + .unwrap() + .accept(None) + .unwrap() + .expect("a fresh group"); for object in 0..2 { fetched .write_frame( diff --git a/rs/moq-net/src/model/broadcast.rs b/rs/moq-net/src/model/broadcast.rs index b65a244f635..907ed956f20 100644 --- a/rs/moq-net/src/model/broadcast.rs +++ b/rs/moq-net/src/model/broadcast.rs @@ -339,7 +339,6 @@ impl Producer { name: Arc, info: track::Info, ) -> Option { - // A consumer may have requested this name before it existed (a live // [`Requests`] queues such requests). Creating the track fulfills that // request: its consumers resolve against this very producer. Without @@ -371,11 +370,7 @@ impl Producer { /// Moq-lite 05 and 06 carry it on its name's stream track subscriptions, but only those /// that start once it exists: create it before, or with, a stream track of the same name. /// See [`datagram`](crate::datagram). - pub fn create_datagrams( - &self, - name: impl Into>, - info: datagram::Info, - ) -> Option { + pub fn create_datagrams(&self, name: impl Into>, info: datagram::Info) -> Option { self.insert_datagrams(name.into(), info, true) } @@ -391,12 +386,7 @@ impl Producer { self.insert_datagrams(name.into(), info, false) } - fn insert_datagrams( - &self, - name: Arc, - info: datagram::Info, - listed: bool, - ) -> Option { + fn insert_datagrams(&self, name: Arc, info: datagram::Info, listed: bool) -> Option { let mut state = self.state.lock(); let producer = match state.datagrams.get(name.as_ref()) { Some(live) => { @@ -2349,7 +2339,10 @@ mod test { let track = consumer.track("track1").unwrap(); let pending_fetch = track.fetch_group(0, None); let fetch = dynamic.requested_fill_group().await.unwrap(); - let group = fetch.accept(crate::track::Info::timed()).unwrap().expect("a fresh group"); + let group = fetch + .accept(crate::track::Info::timed()) + .unwrap() + .expect("a fresh group"); group.finish().unwrap(); pending_fetch.await.unwrap(); diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 8fec6adc87f..49d13c30124 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -10115,7 +10115,10 @@ mod tests { let fetch = track.consume().fetch_group(0, None); let fill = requests.requested_fill_group().await.unwrap(); - let mut fetched = fill.accept(crate::track::Info::timed()).unwrap().expect("a fresh group"); + let mut fetched = fill + .accept(crate::track::Info::timed()) + .unwrap() + .expect("a fresh group"); fetched .write_frame(crate::Timestamp::ZERO, b"fetched".as_ref()) .unwrap(); @@ -12240,7 +12243,10 @@ mod tests { let serving = fetched.clone(); let _fetching = kio::clock::sim::spawn(async move { while let Ok(request) = fetches.requested_fill_group().await { - let mut group = request.accept(crate::track::Info::timed()).unwrap().expect("a fresh group"); + let mut group = request + .accept(crate::track::Info::timed()) + .unwrap() + .expect("a fresh group"); for frame in [b"a", b"b", b"c"] { group.write_frame(group.key_time(), frame.as_ref()).unwrap(); } diff --git a/rs/moq-net/src/model/resume.rs b/rs/moq-net/src/model/resume.rs index 2b090a5e1ab..017f7d4c4d2 100644 --- a/rs/moq-net/src/model/resume.rs +++ b/rs/moq-net/src/model/resume.rs @@ -4536,7 +4536,10 @@ mod test { .unwrap(); let copy = request.accept(crate::track::Info::timed()); - let mut group = fill.accept(0, crate::track::Info::timed()).unwrap().expect("a fresh group"); + let mut group = fill + .accept(0, crate::track::Info::timed()) + .unwrap() + .expect("a fresh group"); group.write_frame(ts(0), b"early".as_ref()).unwrap(); group.finish().unwrap(); assert!( @@ -4563,7 +4566,10 @@ mod test { assert!((&mut fetching).now_or_never().is_none()); let fill = refused_dynamic.requested_groups().now_or_never().unwrap().unwrap(); let wrong = refused.accept(crate::track::Info::timed()); - let mut group = fill.accept(0, crate::track::Info::timed()).unwrap().expect("a fresh group"); + let mut group = fill + .accept(0, crate::track::Info::timed()) + .unwrap() + .expect("a fresh group"); group.write_frame(ts(0), b"wrong".as_ref()).unwrap(); group.finish().unwrap(); drop(staged); @@ -4578,7 +4584,10 @@ mod test { .expect("asked again of the next route") .unwrap(); let copy = request.accept(crate::track::Info::timed()); - let mut group = fill.accept(0, crate::track::Info::timed()).unwrap().expect("a fresh group"); + let mut group = fill + .accept(0, crate::track::Info::timed()) + .unwrap() + .expect("a fresh group"); group.write_frame(ts(0), b"right".as_ref()).unwrap(); group.finish().unwrap(); let _logical = logical.accept(crate::track::Info::timed()); @@ -4686,7 +4695,10 @@ mod test { assert!((&mut fetching).now_or_never().is_none()); let fill = dynamic.requested_groups().now_or_never().unwrap().unwrap(); let _staged_copy = request.accept(crate::track::Info::timed()); - let mut group = fill.accept(0, crate::track::Info::timed()).unwrap().expect("a fresh group"); + let mut group = fill + .accept(0, crate::track::Info::timed()) + .unwrap() + .expect("a fresh group"); group.write_frame(ts(0), b"x".as_ref()).unwrap(); group.finish().unwrap(); assert!((&mut fetching).now_or_never().is_none()); @@ -4704,7 +4716,10 @@ mod test { .now_or_never() .expect("asked of the serving copy") .unwrap(); - let mut group = fill.accept(0, crate::track::Info::timed()).unwrap().expect("a fresh group"); + let mut group = fill + .accept(0, crate::track::Info::timed()) + .unwrap() + .expect("a fresh group"); group.write_frame(ts(0), b"x".as_ref()).unwrap(); group.finish().unwrap(); let mut fetched = fetching.now_or_never().expect("answered").unwrap(); diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 5022b6f5f63..f28737ec616 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -14622,7 +14622,10 @@ mod test { fn a_refusal_releases_the_live_edge_a_fill_cached() { let state = TrackState::spawn(Arc::new(broadcast::Info::default())); let mut guard = state.write().ok().unwrap(); - let _group = guard.insert_group_request(0, group::Bounds::default(), None).unwrap().expect("a fresh group"); + let _group = guard + .insert_group_request(0, group::Bounds::default(), None) + .unwrap() + .expect("a fresh group"); assert!(guard.protects(0)); guard.reject(Error::NotFound, None); assert!(!guard.protects(0)); @@ -16904,7 +16907,11 @@ mod test { .now_or_never() .expect("fill request is ready") .unwrap(); - req.accept(None).unwrap().expect("a fresh group").abort(error.clone()).unwrap(); + req.accept(None) + .unwrap() + .expect("a fresh group") + .abort(error.clone()) + .unwrap(); drop(pending); let waiter = kio::Waiter::noop(); assert!( @@ -21406,7 +21413,12 @@ mod test { .unwrap(); drop(req); assert!(fresh.poll_unwanted(&kio::Waiter::noop()).is_pending()); - fresh.accept(Info::timed()).unwrap().expect("a fresh group").finish().unwrap(); + fresh + .accept(Info::timed()) + .unwrap() + .expect("a fresh group") + .finish() + .unwrap(); assert_eq!(retry.await.unwrap().start, 5); } @@ -21451,7 +21463,12 @@ mod test { .now_or_never() .expect("the retry queues a fresh request") .unwrap(); - fresh.accept(Info::timed()).unwrap().expect("a fresh group").finish().unwrap(); + fresh + .accept(Info::timed()) + .unwrap() + .expect("a fresh group") + .finish() + .unwrap(); assert_eq!(retry.await.unwrap().start, 5); } @@ -21479,7 +21496,10 @@ mod test { .expect("the retry queues a fresh request") .unwrap(); - let mut group = req.accept(Info::timed()).expect("a withdrawn request still accepts").expect("a fresh group"); + let mut group = req + .accept(Info::timed()) + .expect("a withdrawn request still accepts") + .expect("a fresh group"); group .write_frame(group.key_time(), bytes::Bytes::from_static(b"hi")) .unwrap(); @@ -21970,7 +21990,11 @@ mod test { .now_or_never() .expect("the retry queues a fresh request") .unwrap(); - req.accept(Info::timed()).unwrap().expect("a fresh group").finish().unwrap(); + req.accept(Info::timed()) + .unwrap() + .expect("a fresh group") + .finish() + .unwrap(); assert!(retry.await.unwrap().read_frame().await.unwrap().is_none()); } @@ -25165,7 +25189,10 @@ mod test { let Poll::Ready(Ok(fill)) = dynamic.poll_requested_groups(&waiter) else { panic!("below the start is a miss"); }; - let _writing = [fill.accept(0, None).unwrap().expect("a fresh group"), fill.accept(1, None).unwrap().expect("a fresh group")]; + let _writing = [ + fill.accept(0, None).unwrap().expect("a fresh group"), + fill.accept(1, None).unwrap().expect("a fresh group"), + ]; for key in 2..10 { fill.group(key).reject(Error::NotFound); } @@ -29675,7 +29702,11 @@ mod test { .unwrap(); } assert_eq!(read_numbered(&mut late), None); - let mut flight = asked(&requests).expect("a flight").accept(0, None).unwrap().expect("a fresh group"); + let mut flight = asked(&requests) + .expect("a flight") + .accept(0, None) + .unwrap() + .expect("a fresh group"); assert_eq!(read_numbered(&mut late), None); for index in 0..1_000 { flight @@ -29815,7 +29846,11 @@ mod test { .unwrap(); } assert_eq!(read_numbered(&mut late), None); - let mut flight = asked(&requests).expect("a flight").accept(0, None).unwrap().expect("a fresh group"); + let mut flight = asked(&requests) + .expect("a flight") + .accept(0, None) + .unwrap() + .expect("a fresh group"); assert_eq!(read_numbered(&mut late), None); // A newer group leaves group 0 cold, and its cached copy goes whole. let mut newer = producer.append_next().unwrap(); @@ -29875,7 +29910,11 @@ mod test { let (mut fast, mut slow) = (live.consume(), live.consume()); assert_eq!(read_numbered(&mut fast), None); assert_eq!(read_numbered(&mut slow), None); - let mut flight = asked(&requests).unwrap().accept(0, None).unwrap().expect("a fresh group"); + let mut flight = asked(&requests) + .unwrap() + .accept(0, None) + .unwrap() + .expect("a fresh group"); assert_eq!(read_numbered(&mut fast), None); assert_eq!(read_numbered(&mut slow), None); assert_eq!(read_numbered(&mut slow), None); diff --git a/rs/moq-net/src/transport/memory.rs b/rs/moq-net/src/transport/memory.rs index 59d36e88ca5..005d78918bc 100644 --- a/rs/moq-net/src/transport/memory.rs +++ b/rs/moq-net/src/transport/memory.rs @@ -1213,10 +1213,7 @@ mod tests { let acked = |send: &SendStream, offset: u64| send.poll_acked(&noop(), &offset); let (a, b) = pair(Config::default()); let (mut send, mut recv) = uni(&a, &b); - assert!(matches!( - acked(&send, send.offset()), - Poll::Ready(Ok(())) - )); + assert!(matches!(acked(&send, send.offset()), Poll::Ready(Ok(())))); ready(write(&mut send, &Bytes::from_static(b"one"))).unwrap(); let one = send.offset(); diff --git a/rs/moq-rtsp/src/client.rs b/rs/moq-rtsp/src/client.rs index e29844e6481..86a80237d4b 100644 --- a/rs/moq-rtsp/src/client.rs +++ b/rs/moq-rtsp/src/client.rs @@ -174,16 +174,14 @@ impl Client { for (index, kind) in &tracks { let track = match kind { Kind::H264 => { - let track = - broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)); + let track = broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)); Track::Video(Box::new(Video::H264 { split: h264::Split::new(), import: h264::Import::new(track, reserved.clone(), Default::default())?, })) } Kind::H265 => { - let track = - broadcast.unique_track(".hev1", catalog.track_info(hang::catalog::PRIORITY.video)); + let track = broadcast.unique_track(".hev1", catalog.track_info(hang::catalog::PRIORITY.video)); Track::Video(Box::new(Video::H265 { split: h265::Split::new(), import: h265::Import::new(track, reserved.clone(), Default::default())?, @@ -194,8 +192,7 @@ impl Client { return Err(Error::Rtsp("AAC stream without an AudioSpecificConfig".to_string())); }; let config = aac::config(params.extra_data())?; - let track = - broadcast.unique_track(".aac", catalog.track_info(hang::catalog::PRIORITY.audio)); + let track = broadcast.unique_track(".aac", catalog.track_info(hang::catalog::PRIORITY.audio)); Track::Aac(Box::new(aac::Import::new(track, reserved.clone(), config)?)) } }; diff --git a/rs/moq-stats/src/produce.rs b/rs/moq-stats/src/produce.rs index 6dac3696aec..d4480e25c7d 100644 --- a/rs/moq-stats/src/produce.rs +++ b/rs/moq-stats/src/produce.rs @@ -631,7 +631,9 @@ fn config() -> moq_json::snapshot::Config { impl Output { fn create(broadcast: &broadcast::Producer, name: &str) -> Result { - Ok(Self::new(broadcast.create_track(name, info()).ok_or(moq_net::Error::Duplicate)?)) + Ok(Self::new( + broadcast.create_track(name, info()).ok_or(moq_net::Error::Duplicate)?, + )) } /// Publish on the track `request` asked for, or create `name` without one. @@ -931,7 +933,9 @@ impl BucketTrack { // an earlier epoch's, and its first MoQ group is where they start. let epoch = Epoch::mint(); let name = crate::bucket_track(bucket, &epoch); - let track = broadcast.create_track(name.as_str(), info()).ok_or(moq_net::Error::Duplicate)?; + let track = broadcast + .create_track(name.as_str(), info()) + .ok_or(moq_net::Error::Duplicate)?; Ok(Self { name, snapshot: Snapshot::new(track, config()).fresh(), diff --git a/rs/moq-tokio/examples/chat.rs b/rs/moq-tokio/examples/chat.rs index 1cdc0508644..5e145f7788f 100644 --- a/rs/moq-tokio/examples/chat.rs +++ b/rs/moq-tokio/examples/chat.rs @@ -53,7 +53,10 @@ async fn run_broadcast(origin: moq_net::origin::Producer) -> anyhow::Result<()> // Frames are stamped with this host's wall clock in milliseconds, so the track declares that // timescale. let info = moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI); - let mut track = route.broadcast().create_track("chat", info).context("the track already exists")?; + let mut track = route + .broadcast() + .create_track("chat", info) + .context("the track already exists")?; // Create a group, which starts at its first frame's timestamp. // Each group is independent and the newest group(s) will be prioritized. diff --git a/rs/moq-tokio/examples/clock.rs b/rs/moq-tokio/examples/clock.rs index 6b9c8032e52..8fe125b540e 100644 --- a/rs/moq-tokio/examples/clock.rs +++ b/rs/moq-tokio/examples/clock.rs @@ -70,7 +70,10 @@ async fn main() -> anyhow::Result<()> { .route(&config.broadcast, moq_net::origin::RouteOptions::hidden()) .context("failed to create broadcast")?; let info = moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI); - let track = route.broadcast().create_track(track, info).context("the track already exists")?; + let track = route + .broadcast() + .create_track(track, info) + .context("the track already exists")?; route.announce().context("failed to announce broadcast")?; let clock = Publisher::new(track); diff --git a/rs/moq-tokio/src/quic/web/send.rs b/rs/moq-tokio/src/quic/web/send.rs index 3951a1fa214..41590830891 100644 --- a/rs/moq-tokio/src/quic/web/send.rs +++ b/rs/moq-tokio/src/quic/web/send.rs @@ -340,11 +340,7 @@ impl moq_net::transport::poll::SendStream for Stream { } /// Once reset, answers from the prefix acknowledged by then, failing for the bytes after it. - fn poll_acked( - &self, - waiter: &kio::Waiter, - offset: &send::Offset, - ) -> Poll> { + fn poll_acked(&self, waiter: &kio::Waiter, offset: &send::Offset) -> Poll> { let acked = match &self.state { State::Open(stream) => stream.poll_acked(waiter, *offset), State::Finished(stream) => stream.poll_acked(waiter, *offset), diff --git a/rs/moq-tokio/src/worker/group.rs b/rs/moq-tokio/src/worker/group.rs index 35e21210d51..d33ce063380 100644 --- a/rs/moq-tokio/src/worker/group.rs +++ b/rs/moq-tokio/src/worker/group.rs @@ -788,13 +788,12 @@ fn run( let built = { let _guard = runtime.enter(); - Server::build(server, crate::server::Parts::Member(member)) - .and_then(|server| { - let addr = server - .local_addr() - .ok_or(crate::Error::NoBackend("no QUIC listener configured"))?; - Ok((server, addr)) - }) + Server::build(server, crate::server::Parts::Member(member)).and_then(|server| { + let addr = server + .local_addr() + .ok_or(crate::Error::NoBackend("no QUIC listener configured"))?; + Ok((server, addr)) + }) }; let (server, addr) = match built { diff --git a/rs/moq-tokio/tests/integration/relay_fill.rs b/rs/moq-tokio/tests/integration/relay_fill.rs index 7c1c91e2ff3..5c9cc78c940 100644 --- a/rs/moq-tokio/tests/integration/relay_fill.rs +++ b/rs/moq-tokio/tests/integration/relay_fill.rs @@ -159,11 +159,13 @@ fn groups(range: std::ops::Range) -> BTreeMap { async fn relay(version: Version) -> anyhow::Result<()> { let publisher = moq_tokio::origin::spawn(); let broadcast = publisher.route("history", moq_net::origin::RouteOptions::hidden())?; - let track = broadcast.broadcast().create_track( - "video", - Info::default().with_timescale(Timescale::MILLI).with_max_age(None), - ) - .expect("a free name"); + let track = broadcast + .broadcast() + .create_track( + "video", + Info::default().with_timescale(Timescale::MILLI).with_max_age(None), + ) + .expect("a free name"); for sequence in 0..GROUPS { let mut group = track.create_group(moq_net::group::Info { start: sequence })?; group.write_frame( diff --git a/rs/moq-transcode/src/lib.rs b/rs/moq-transcode/src/lib.rs index e6e5def7e15..e023eb3bda5 100644 --- a/rs/moq-transcode/src/lib.rs +++ b/rs/moq-transcode/src/lib.rs @@ -1013,7 +1013,10 @@ mod tests { tokio::spawn(async move { while let Ok(request) = source_fetches.requested_fill().await.map(groups) { - let mut group = request.accept(request.start().group, None).unwrap().expect("a fresh group"); + let mut group = request + .accept(request.start().group, None) + .unwrap() + .expect("a fresh group"); write_keyframe(&mut group); group.finish().unwrap(); } diff --git a/rs/moq-transcode/src/rung.rs b/rs/moq-transcode/src/rung.rs index f9f519d8098..5c48827f1ba 100644 --- a/rs/moq-transcode/src/rung.rs +++ b/rs/moq-transcode/src/rung.rs @@ -1230,7 +1230,12 @@ mod tests { panic!("a time lookup"); }; assert_eq!(lookup.time(), 7); - lookup.accept(6, None).unwrap().expect("a fresh group").finish().unwrap(); + lookup + .accept(6, None) + .unwrap() + .expect("a fresh group") + .finish() + .unwrap(); while let Poll::Ready(Ok(Some(_))) = reader.poll_recv_group(&waiter) {} let fill = fills.requested_fill().await.map(groups).unwrap(); assert_eq!((fill.start().group, fill.end()), (7, 10)); @@ -1373,7 +1378,12 @@ mod tests { panic!("a time lookup"); }; assert_eq!(lookup.time(), 1); - lookup.accept(0, None).unwrap().expect("a fresh group").finish().unwrap(); + lookup + .accept(0, None) + .unwrap() + .expect("a fresh group") + .finish() + .unwrap(); while let Poll::Ready(Ok(Some(_))) = reader.poll_recv_group(&waiter) {} let fill = fills.requested_fill().await.map(groups).unwrap(); assert_eq!((fill.start().group, fill.end()), (1, HOUR)); @@ -1441,13 +1451,23 @@ mod tests { panic!("a time lookup"); }; assert_eq!(lookup.time(), 7); - lookup.accept(6, None).unwrap().expect("a fresh group").finish().unwrap(); + lookup + .accept(6, None) + .unwrap() + .expect("a fresh group") + .finish() + .unwrap(); while let Poll::Ready(Ok(Some(_))) = reader.poll_recv_group(&waiter) {} let fill = fills.requested_fill().await.map(groups).unwrap(); assert_eq!((fill.start().group, fill.end()), (7, 10)); // Group 7 is served, and the reader never reads again to pick it up. - fill.clone().accept(7, None).unwrap().expect("a fresh group").finish().unwrap(); + fill.clone() + .accept(7, None) + .unwrap() + .expect("a fresh group") + .finish() + .unwrap(); let mut tasks = tokio::task::JoinSet::new(); spawn_fill(&mut tasks, rung, fill, Arc::new(Semaphore::new(1))); let wait = std::time::Duration::from_secs(5); diff --git a/rs/moq-uring/src/quic/web/send.rs b/rs/moq-uring/src/quic/web/send.rs index c3b6f5bb862..3fcf05fd1d4 100644 --- a/rs/moq-uring/src/quic/web/send.rs +++ b/rs/moq-uring/src/quic/web/send.rs @@ -309,11 +309,7 @@ impl moq_net::transport::poll::SendStream for Stream { } /// Once reset, answers from the prefix acknowledged by then, failing for the bytes after it. - fn poll_acked( - &self, - waiter: &kio::Waiter, - offset: &send::Offset, - ) -> Poll> { + fn poll_acked(&self, waiter: &kio::Waiter, offset: &send::Offset) -> Poll> { let acked = match &self.state { State::Open(stream) => stream.poll_acked(waiter, *offset), State::Finished(stream) => stream.poll_acked(waiter, *offset), diff --git a/rs/moq-uring/tests/integration/web.rs b/rs/moq-uring/tests/integration/web.rs index 41112c4040d..7825be470c1 100644 --- a/rs/moq-uring/tests/integration/web.rs +++ b/rs/moq-uring/tests/integration/web.rs @@ -335,10 +335,7 @@ fn an_offset_stays_acknowledged_through_a_reset() { let cut = SendStream::offset(&send); SendStream::reset(&mut send, 1); let acked = |offset| SendStream::poll_acked(&send, &kio::Waiter::noop(), offset); - assert!( - matches!(acked(&payload), Poll::Ready(Ok(()))), - "the reset forgot it" - ); + assert!(matches!(acked(&payload), Poll::Ready(Ok(()))), "the reset forgot it"); assert!(matches!(acked(&cut), Poll::Ready(Err(_))), "the reset cut it"); assert_eq!(SendStream::offset(&send), cut); diff --git a/rs/moq-video/src/decode/consumer.rs b/rs/moq-video/src/decode/consumer.rs index 131e15d661b..ae1df6460c2 100644 --- a/rs/moq-video/src/decode/consumer.rs +++ b/rs/moq-video/src/decode/consumer.rs @@ -502,8 +502,7 @@ mod tests { }; let rendition = config.probe().await.unwrap(); let reserved = source_catalog.reserve().with_interval(config.effective_join()); - let track = source_broadcast - .unique_track(".avc3", reserved.track_info(hang::catalog::PRIORITY.video)); + let track = source_broadcast.unique_track(".avc3", reserved.track_info(hang::catalog::PRIORITY.video)); let mut producer = EncodePublisher::new(track, reserved, rendition).unwrap(); let mut encoder = Encoder::new(&config).unwrap(); let rgba = vec![0x80u8; 320 * 240 * 4]; diff --git a/rs/moq-video/src/encode/publisher.rs b/rs/moq-video/src/encode/publisher.rs index c42bec84fd1..986157a6c3e 100644 --- a/rs/moq-video/src/encode/publisher.rs +++ b/rs/moq-video/src/encode/publisher.rs @@ -455,8 +455,7 @@ mod tests { selected.container = hang::catalog::Container::Loc; selected.preference = -1; - let track = broadcast - .unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)); + let track = broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)); let _producer = Publisher::new(track, catalog.reserve(), selected).unwrap(); let (_, published) = rendition(&catalog).expect("the rendition publishes before any frame"); @@ -657,8 +656,7 @@ mod finished { })); let finished: Vec<_> = (0..sources) .map(|_| { - let track = broadcast - .unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)); + let track = broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video)); let mut producer = Publisher::new(track, catalog.reserve(), rendition.clone()).unwrap(); for pts in [0, 33_333] { let pts = moq_net::Timestamp::from_micros(pts).unwrap(); diff --git a/test/interop/clients/rust/catalog.rs b/test/interop/clients/rust/catalog.rs index 02db823d93e..c319dbe1111 100644 --- a/test/interop/clients/rust/catalog.rs +++ b/test/interop/clients/rust/catalog.rs @@ -34,7 +34,8 @@ async fn main() -> anyhow::Result<()> { let route = origin.route(&args[2], moq_net::origin::RouteOptions::hidden())?; let track = route .broadcast() - .create_track(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info()).context("the track already exists")?; + .create_track(hang::Catalog::DEFAULT_NAME, hang::Catalog::default_track_info()) + .context("the track already exists")?; ensure!( track.info().compression == moq_net::track::Compression::Deflate, "hang catalogs are compressed" diff --git a/test/interop/clients/rust/control.rs b/test/interop/clients/rust/control.rs index d1f20586d4a..6428bdbf232 100644 --- a/test/interop/clients/rust/control.rs +++ b/test/interop/clients/rust/control.rs @@ -13,7 +13,8 @@ async fn main() -> anyhow::Result<()> { let route = origin.route("control", moq_net::origin::RouteOptions::hidden())?; let track = route .broadcast() - .create_track("video", moq_net::track::Info::default().with_priority(2)).context("the track already exists")?; + .create_track("video", moq_net::track::Info::default().with_priority(2)) + .context("the track already exists")?; let mut group = track.create_group(moq_net::group::Info { start: 4 })?; for byte in [1, 2] { group.write_frame(moq_net::Timestamp::unscaled(group.start), vec![byte])?; diff --git a/test/interop/clients/rust/finish.rs b/test/interop/clients/rust/finish.rs index 49669345ae1..874cb59eb2d 100644 --- a/test/interop/clients/rust/finish.rs +++ b/test/interop/clients/rust/finish.rs @@ -79,7 +79,10 @@ async fn main() -> anyhow::Result<()> { let route = origin.route(&args.broadcast, moq_net::origin::RouteOptions::hidden())?; let mut catalog = moq_mux::catalog::Producer::<()>::new(&mut route.broadcast().clone(), Default::default())?; let mut stream = moq_mux::import::TrackStream::video( - route.broadcast().reserve_track("video").context("the track already exists")?, + route + .broadcast() + .reserve_track("video") + .context("the track already exists")?, catalog.reserve(), moq_mux::import::VideoInit::new(moq_mux::import::VideoFormat::Avc3, Vec::new()), )?; @@ -100,7 +103,8 @@ async fn main() -> anyhow::Result<()> { )?; let track = health .broadcast() - .create_track("live", moq_net::track::Info::default()).context("the track already exists")?; + .create_track("live", moq_net::track::Info::default()) + .context("the track already exists")?; let start = moq_net::Timestamp::unscaled(0); let mut group = track.append_group(start)?; group.write_frame(start, b"session-alive".to_vec())?; diff --git a/test/interop/clients/rust/goaway.rs b/test/interop/clients/rust/goaway.rs index 88d449f37cc..c7945422ee0 100644 --- a/test/interop/clients/rust/goaway.rs +++ b/test/interop/clients/rust/goaway.rs @@ -35,7 +35,8 @@ async fn main() -> anyhow::Result<()> { let route = origin.route("handover", moq_net::origin::RouteOptions::default())?; let mut track = route .broadcast() - .create_track("video", moq_net::track::Info::default()).context("the track already exists")?; + .create_track("video", moq_net::track::Info::default()) + .context("the track already exists")?; let (mut first, first_url) = endpoint(&origin, version).await?; let (mut second, second_url) = endpoint(&origin, version).await?; let script = concat!( diff --git a/test/interop/clients/rust/hls.rs b/test/interop/clients/rust/hls.rs index 2cc8acf3104..f881e46518d 100644 --- a/test/interop/clients/rust/hls.rs +++ b/test/interop/clients/rust/hls.rs @@ -75,11 +75,15 @@ async fn main() -> anyhow::Result<()> { let route = origin.route(path, moq_net::origin::RouteOptions::hidden())?; let mut broadcast = route.broadcast().clone(); let mut catalog = moq_mux::catalog::Producer::<()>::new(&mut broadcast, Default::default())?; - let track = broadcast.create_track("video", catalog.track_info(hang::catalog::PRIORITY.video)).context("the track already exists")?; + let track = broadcast + .create_track("video", catalog.track_info(hang::catalog::PRIORITY.video)) + .context("the track already exists")?; let config = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8); // Each producer owns its catalog entry, so both stay alive until the reader is done. let video_track = write(catalog.video(track, Container::Legacy(Kind::Video), config)?, video())?; - let track = broadcast.create_track("audio", catalog.track_info(hang::catalog::PRIORITY.audio)).context("the track already exists")?; + let track = broadcast + .create_track("audio", catalog.track_info(hang::catalog::PRIORITY.audio)) + .context("the track already exists")?; let config = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2); let audio_track = write(catalog.audio(track, Container::Legacy(Kind::Audio), config)?, audio())?; catalog.finish()?; diff --git a/test/interop/clients/rust/tail.rs b/test/interop/clients/rust/tail.rs index 5861ef4efaa..22cc6351687 100644 --- a/test/interop/clients/rust/tail.rs +++ b/test/interop/clients/rust/tail.rs @@ -118,7 +118,9 @@ async fn main() -> anyhow::Result<()> { if datagram { // Untimed: the OBJECT_DATAGRAM carries no timestamp, so the subscriber can // check the payload alone. Stay open until each one is acknowledged. - let mut track = broadcast.create_datagrams("tail", moq_net::datagram::Info::default()).context("the track already exists")?; + let mut track = broadcast + .create_datagrams("tail", moq_net::datagram::Info::default()) + .context("the track already exists")?; route.announce()?; let session = client .clone() @@ -143,18 +145,20 @@ async fn main() -> anyhow::Result<()> { session.close().await?; eprintln!("tail acknowledged"); } else { - let mut track = broadcast.create_track( - "tail", - moq_net::track::Info::default() - .with_timescale(moq_net::Timescale::MILLI) - .with_compression(match compress { - true => moq_net::track::Compression::Deflate, - false => moq_net::track::Compression::None, - }) - // `cached` and `late` read groups a newer one supersedes, which the default - // zero max age would leave stale. - .with_max_age(None), - ).context("the track already exists")?; + let mut track = broadcast + .create_track( + "tail", + moq_net::track::Info::default() + .with_timescale(moq_net::Timescale::MILLI) + .with_compression(match compress { + true => moq_net::track::Compression::Deflate, + false => moq_net::track::Compression::None, + }) + // `cached` and `late` read groups a newer one supersedes, which the default + // zero max age would leave stale. + .with_max_age(None), + ) + .context("the track already exists")?; route.announce()?; if cached { write(&mut track, mode)?; From 7b764dc221b1db5145a20c3e6b625a17bee80f4e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 18 Nov 2026 23:46:37 -0800 Subject: [PATCH 04/10] wip: migrate demos, tests, and bench; follow-up quest Co-Authored-By: Claude Opus 5.5 --- bench/browser/page/stats.ts | 3 ++ bench/browser/page/transport.ts | 1 + demo/boy/src/game.test.ts | 1 + demo/boy/src/game.ts | 1 + demo/carla/web/src/preview.ts | 6 ++-- demo/carla/web/src/truck.test.ts | 7 ++-- demo/carla/web/src/truck.ts | 1 + demo/web/src/publish.ts | 1 + js/net/src/broadcast.test.ts | 8 ++--- js/net/src/fill.test.ts | 2 +- quest/m2/outcome-enums/create-group.md | 23 +++++++++++++ quest/m2/outcome-enums/small-public.md | 34 ------------------- quest/m3/error-matches.md | 2 +- rs/moq-net/src/model/broadcast.rs | 15 ++++++++ rs/moq-tokio/src/connection.rs | 4 +-- .../clients/js/src/capture.test.ts | 4 +++ test/datagram-tracks/client.ts | 3 ++ test/drain/drain.ts | 1 + test/interop/bare-fin.ts | 1 + test/interop/clients/js-native/claims.ts | 4 ++- test/interop/clients/js-native/hls.ts | 2 ++ test/interop/clients/js-native/replace.ts | 14 ++++++-- test/interop/clients/js-native/server.ts | 2 ++ test/interop/clients/js-native/tail.ts | 3 ++ test/interop/clients/js/open-gop/main.ts | 1 + test/interop/clients/js/src/finish.ts | 15 ++++---- test/interop/compat/client.ts | 8 ++--- test/interop/ietf-compression.ts | 1 + test/interop/ietf-range-updates.ts | 5 ++- test/interop/track-status.ts | 1 + test/interop/tracks.ts | 1 + test/receive-credit/sender.ts | 2 ++ test/stream-credit/driver.ts | 6 +++- test/stream-limits/client.ts | 4 ++- test/video/src/captions.ts | 1 + test/video/src/poster.ts | 1 + 36 files changed, 123 insertions(+), 66 deletions(-) create mode 100644 quest/m2/outcome-enums/create-group.md delete mode 100644 quest/m2/outcome-enums/small-public.md diff --git a/bench/browser/page/stats.ts b/bench/browser/page/stats.ts index fe1d6ab651c..68c659bdcdd 100644 --- a/bench/browser/page/stats.ts +++ b/bench/browser/page/stats.ts @@ -93,6 +93,7 @@ async function allocator(connection: Moq.Connection): Promise { reservation.close(); @@ -151,6 +152,7 @@ async function receive(config: Sampling): Promise { const publishing = new Moq.Origin.Producer(); const publication = publishing.route(Moq.Path.from(`${config.path}/live`), { hidden: true }); const track = publication.broadcast.createTrack("data", { timescale: Moq.Time.Timescale.MILLI }); + if (!track) throw new Error("the track already exists"); publication.announce(); const publisher = await Moq.Connection.connect({ url: new URL(config.url), @@ -252,6 +254,7 @@ async function resume(config: Sampling & { cycles: number; idle_ms: number; limi await new Promise((resolve) => setTimeout(resolve, config.idle_ms)); const publication = origin.route(Moq.Path.from(`${config.path}/resume/${cycle}`), { hidden: true }); const track = publication.broadcast.createTrack("video", { priority: 1 }); + if (!track) throw new Error("the track already exists"); const start = performance.now(); const reservation = handle.reserve(track.demand(), 2_500_000); const deadline = start + config.limit_ms; diff --git a/bench/browser/page/transport.ts b/bench/browser/page/transport.ts index dbe10ee9c09..c17ed839ac0 100644 --- a/bench/browser/page/transport.ts +++ b/bench/browser/page/transport.ts @@ -39,6 +39,7 @@ async function publish(config: Transport): Promise { timescale: Moq.Time.Timescale.MILLI, maxAge: Duration.millis(600_000), }); + if (!track) throw new Error("the track already exists"); const demand = track.demand().wanted; publication.announce(); const connection = await Moq.Connection.connect({ diff --git a/demo/boy/src/game.test.ts b/demo/boy/src/game.test.ts index 0c211516adf..d7a00e21e36 100644 --- a/demo/boy/src/game.test.ts +++ b/demo/boy/src/game.test.ts @@ -65,6 +65,7 @@ test("status skips values that fail the schema and ends when the track errors", const origin = new Moq.Origin.Producer(); const publication = origin.route(Moq.Path.from("game", "test")); const track = publication.broadcast.createTrack("status"); + if (!track) throw new Error("the track already exists"); // One finished group per status, so between statuses the loop waits on the next group. const publish = (value: unknown) => { diff --git a/demo/boy/src/game.ts b/demo/boy/src/game.ts index a9a8d32dd59..6b8d144982b 100644 --- a/demo/boy/src/game.ts +++ b/demo/boy/src/game.ts @@ -334,6 +334,7 @@ export class Game { }); const track = route.broadcast.createTrack("command", { timescale: Moq.Time.Timescale.MILLI }); + if (!track) throw new Error("the track already exists"); const producer = new Json.Snapshot.Producer>({ track }); effect.cleanup(() => producer.finish()); effect.run(this.#runCommandTrack.bind(this, track, producer)); diff --git a/demo/carla/web/src/preview.ts b/demo/carla/web/src/preview.ts index d38e19cd220..7fd448bedac 100644 --- a/demo/carla/web/src/preview.ts +++ b/demo/carla/web/src/preview.ts @@ -13,9 +13,9 @@ export function populatePreview(add: (path: Moq.Path.Valid) => Truck) { ].entries()) { const truck = add(Moq.Path.from(`carla/truck${index + 1}/front.hang`)); const origin = new Moq.Broadcast.Producer(); - const producer = new Json.Snapshot.Producer({ - track: origin.createTrack("status", { compression: "deflate" }), - }); + const track = origin.createTrack("status", { compression: "deflate" }); + if (!track) throw new Error("the status track already exists"); + const producer = new Json.Snapshot.Producer({ track }); (truck.broadcast.out.active as Moq.Signals.Signal).set(origin.consume()); producer.update( { diff --git a/demo/carla/web/src/truck.test.ts b/demo/carla/web/src/truck.test.ts index dc9bf992840..82e66d4f83d 100644 --- a/demo/carla/web/src/truck.test.ts +++ b/demo/carla/web/src/truck.test.ts @@ -69,6 +69,7 @@ describe("Truck status", () => { function statusBroadcast() { const broadcast = new Moq.Broadcast.Producer(); const track = broadcast.createTrack("status", { compression: "deflate" }); + if (!track) throw new Error("the track already exists"); const producer = new Json.Snapshot.Producer({ track }); return { broadcast, producer }; } @@ -408,9 +409,9 @@ describe("Truck control", () => { const driving = new Moq.Signals.Signal(undefined); const focused = new Moq.Signals.Signal(undefined); const camera = origin.route(Moq.Path.from("carla/truck1/front.hang")); - const producer = new Json.Snapshot.Producer({ - track: camera.broadcast.createTrack("status", { compression: "deflate" }), - }); + const track = camera.broadcast.createTrack("status", { compression: "deflate" }); + if (!track) throw new Error("the status track already exists"); + const producer = new Json.Snapshot.Producer({ track }); const truck = new Truck({ broadcastId: Moq.Path.from("carla/truck1/front.hang"), connection, diff --git a/demo/carla/web/src/truck.ts b/demo/carla/web/src/truck.ts index 04fa942dad7..373cdf32a24 100644 --- a/demo/carla/web/src/truck.ts +++ b/demo/carla/web/src/truck.ts @@ -61,6 +61,7 @@ function publishControl( const route = origin.route(path, { hidden: true }); effect.cleanup(() => route.close()); const track = route.broadcast.createTrack("control", { maxAge: CONTROL_HEARTBEAT }); + if (!track) throw new Error("the track already exists"); // Announced once the track exists, under a fresh instance: the truck binds its // single driver to this path and instance. route.announce(); diff --git a/demo/web/src/publish.ts b/demo/web/src/publish.ts index dce7448a724..8c9ecac813c 100644 --- a/demo/web/src/publish.ts +++ b/demo/web/src/publish.ts @@ -410,6 +410,7 @@ meta.run((effect) => { timescale: Net.Time.Timescale.MILLI, maxAge: Duration.millis(86_400_000), }); + if (!track) throw new Error("the track already exists"); effect.cleanup(() => { track.finish(); track.close(); diff --git a/js/net/src/broadcast.test.ts b/js/net/src/broadcast.test.ts index e0bffa8f607..cd000bdeb16 100644 --- a/js/net/src/broadcast.test.ts +++ b/js/net/src/broadcast.test.ts @@ -148,7 +148,7 @@ test("createTrack with invalid info rejects the queued request it answers", asyn const pulled = wireOf(broadcast).requested(); const subscriber = broadcast.track("media").subscribe(); - expect(() => defined(broadcast.createTrack("media", { priority: 256 }))).toThrow(); + expect(() => broadcast.createTrack("media", { priority: 256 })).toThrow(); expect(await subscriber.closed).toBeInstanceOf(Error); // The refused request no longer holds the name. @@ -556,7 +556,7 @@ test("createTrack commits info up front", async () => { expect(info.priority).toBe(3); }); -test("createTrack rejects a duplicate live name", () => { +test("createTrack returns undefined for a duplicate live name", () => { const broadcast = new BroadcastProducer(); defined(broadcast.createTrack("dup", { timescale: Timescale.MILLI })); expect(broadcast.createTrack("dup", { timescale: Timescale.MILLI })).toBeUndefined(); @@ -754,8 +754,8 @@ test("a track name with a lone surrogate is refused where it is named, since UTF const broadcast = new BroadcastProducer(); const consumer = broadcast.consume(); for (const name of ["\uD800", "a\uDC00", "\uDC00\uD800"]) { - expect(() => defined(broadcast.createTrack(name))).toThrow("lone surrogate"); - expect(() => defined(broadcast.createDatagrams(name))).toThrow("lone surrogate"); + expect(() => broadcast.createTrack(name)).toThrow("lone surrogate"); + expect(() => broadcast.createDatagrams(name)).toThrow("lone surrogate"); expect(() => broadcast.track(name)).toThrow("lone surrogate"); expect(() => consumer.track(name)).toThrow("lone surrogate"); expect(() => consumer.datagrams(name)).toThrow("lone surrogate"); diff --git a/js/net/src/fill.test.ts b/js/net/src/fill.test.ts index 1f269aac697..75e115cd760 100644 --- a/js/net/src/fill.test.ts +++ b/js/net/src/fill.test.ts @@ -691,7 +691,7 @@ test("fill: a group arriving live answers the fill", async () => { live.writeFrame({ payload: enc.encode("live"), timestamp: Timestamp.unscaled(live.start) }); live.finish(); expect(fill.wanted()).toBeUndefined(); - expect(() => defined(fill.accept(1n))).toThrow(); + expect(fill.accept(1n)).toBeUndefined(); expect(await frames(await fetching)).toEqual(["live"]); fill.close(); diff --git a/quest/m2/outcome-enums/create-group.md b/quest/m2/outcome-enums/create-group.md new file mode 100644 index 00000000000..a70096ebdeb --- /dev/null +++ b/quest/m2/outcome-enums/create-group.md @@ -0,0 +1,23 @@ +# [M] A held group start is a value, not an error + +## Goal + +`moq_net::track::Producer::create_group` reports a start another live group +already holds as a value (`Result>`), as the fill +`accept`s do, not `Err(Error::Duplicate)`, so moq-transcode's rung and the +ietf subscriber's `open_fill_group` stop matching it. js/net's `createGroup`, +which throws `duplicate group`, returns `undefined` the same way. + +## Plan + +Found by [small-public](https://github.com/moq-dev/moq/pull/9150), which +reshaped `create_track` and the fill `accept`s but left `create_group` out of +its Goal. The matches to remove: `rs/moq-transcode/src/rung.rs` (the live +path and a fetch racing to write one group) and `rs/moq-net/src/ietf/subscriber.rs` +(`open_fill_group`, a widened fetch range refilling a group the copy owns). +Most callers create a fresh start and unwrap, so the migration is mostly +mechanical; the recommendation is `Result>`, matching the fill +`accept`s. + +Public API: breaking in moq-net (`create_group`) and js/net (`createGroup`). +Wire: none. diff --git a/quest/m2/outcome-enums/small-public.md b/quest/m2/outcome-enums/small-public.md deleted file mode 100644 index d23af54144e..00000000000 --- a/quest/m2/outcome-enums/small-public.md +++ /dev/null @@ -1,34 +0,0 @@ -# [M] Four small public returns take the shape their callers use - -## Goal - -- `moq_net` `broadcast::Producer::create_track` and the fill `accept`s - report an already-taken track or group as a value - (`Result>`), not `Err(Error::Duplicate)`, so moq-mux's catalog - producer and the ietf subscriber stop matching it. js/net's `createTrack`, - which throws `duplicate track`, returns `undefined` the same way. -- `moq_net::transport::poll::SendStream::poll_acked` returns no `Acked`. - Its one consumer (`coding/writer.rs`) treats `Sent` like `Delivered`, - though `Sent` is documented as "not an acknowledgment": confirm the writer - is right before folding them. Whether a transport reports acknowledgment - at all is a capability decided once, not a per-call result. -- `moq_tokio::Connection::poll_status`, `status()`, and `Status` are gone. - `Status` is a lossy copy of `Phase`: moq-gst reads `Migrating` as - disconnected while the old session still serves. moq-bench and moq-gst - move to `Monitor::state_changed` or `presence_changed`, as moq-ffi and - libmoq already have. -- `moq_tokio::Server::local_addr` returns `Option` like its - `websocket_local_addr` and `tcp_local_addr` siblings, so moq-relay stops - matching `Err(NoBackend)`. - -## Plan - -From the 2026-11-18 enum-return audit (maintainer, /quest-plan); the shapes -above are the recommendations the epic's goal settled. Each is a mechanical -migration of its callers; find them with -`rg 'Error::Duplicate|Acked::|poll_status|Status::|local_addr\('`. - -Public API: breaking in moq-net (`create_track`, the fill `accept`s, the -`poll::SendStream` trait, which every transport implements), js/net -(`createTrack`), and moq-tokio (`Status`, `poll_status`, `local_addr`). -Wire: none. diff --git a/quest/m3/error-matches.md b/quest/m3/error-matches.md index e32d3a9396d..4f5dcf2df45 100644 --- a/quest/m3/error-matches.md +++ b/quest/m3/error-matches.md @@ -57,7 +57,7 @@ Not here: moq-lite's control streams stream producer and moqsink ([error-outcomes-rest](/quest/m3/error-outcomes-rest.md)), the TS import's `unit_error` ([TS unit abort](/quest/m1/ts-unit-abort.md)), moq-quic's `Blocked` ([quic-streams](/quest/m2/outcome-enums/quic-streams.md)), -`Duplicate` ([small-public](/quest/m2/outcome-enums/small-public.md)), and +`Duplicate` ([create-group](/quest/m2/outcome-enums/create-group.md)), and moq-e2ee ([e2ee-format](/quest/m3/e2ee-format.md)). Public API: none expected, except a moq-net clean end becoming `Ok(None)`, diff --git a/rs/moq-net/src/model/broadcast.rs b/rs/moq-net/src/model/broadcast.rs index 907ed956f20..df07f2dfb06 100644 --- a/rs/moq-net/src/model/broadcast.rs +++ b/rs/moq-net/src/model/broadcast.rs @@ -1594,6 +1594,21 @@ mod test { assert_eq!(producer.unique_name(".opus"), "1.opus"); } + /// A live track holds its name against every creator, a minted name skips it, and the + /// name frees once the track ends. + #[test] + fn a_live_name_is_taken_until_its_track_ends() { + let producer = Info::new().produce(); + let track = producer.create_track("0.opus", crate::track::Info::timed()).unwrap(); + assert!(producer.create_track("0.opus", None).is_none()); + assert!(producer.reserve_track("0.opus").is_none()); + assert!(producer.reserve_unlisted_track("0.opus").is_none()); + assert_eq!(producer.unique_track(".opus", None).name(), "1.opus"); + + drop(track); + assert!(producer.create_track("0.opus", None).is_some()); + } + /// A track handle reads what an open broadcast serves now, so a track that went away /// reads empty rather than its stale cache. #[test] diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index 9053871a2b5..6c8c11e7b67 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -888,8 +888,8 @@ pub struct Snapshot { /// and [`recv_bandwidth`](Self::recv_bandwidth) track the live session and reset while disconnected. /// The extra toggle a plain session doesn't have is the connection lifecycle: [`established`](Self::established) /// waits for the first session, [`connected`](Self::connected) reads the current state synchronously, -/// [`connects`](Self::connects) counts the sessions so far, and [`status`](Self::status) waits for the -/// next change. [`closed`](Self::closed) waits for the loop to stop. Clones share the loop; it +/// [`connects`](Self::connects) counts the sessions so far, and [`Monitor::state_changed`] waits for +/// the next change. [`closed`](Self::closed) waits for the loop to stop. Clones share the loop; it /// stops when the last clone drops (or on an explicit [`abort`](Self::abort)). #[derive(Clone)] #[must_use = "dropping the Connection stops the dial; hold it for as long as you want the session"] diff --git a/test/audio-quality/clients/js/src/capture.test.ts b/test/audio-quality/clients/js/src/capture.test.ts index afe58bc77ce..422cfe27c38 100644 --- a/test/audio-quality/clients/js/src/capture.test.ts +++ b/test/audio-quality/clients/js/src/capture.test.ts @@ -78,6 +78,7 @@ test("the observer shares playback demand and closes without ending playback", a const publishedRoute = origin.route(Path.from("tone.hang"), { hidden: true }); const published = publishedRoute.broadcast; const track = published.createTrack("audio", { timescale: Time.Timescale.MILLI }); + if (!track) throw new Error("the track already exists"); publishedRoute.announce(); const source = new Broadcast({ origin, name: Path.from("tone.hang"), follow: false, catalogFormat: "manual" }); const capture = new Capture({ @@ -125,6 +126,7 @@ test("the observer asks for the decoder's delay plus its stretch and warmup, not const publishedRoute = origin.route(Path.from("tone.hang"), { hidden: true }); const published = publishedRoute.broadcast; const track = published.createTrack("audio", { timescale: Time.Timescale.MILLI }); + if (!track) throw new Error("the track already exists"); publishedRoute.announce(); const source = new Broadcast({ origin, name: Path.from("tone.hang"), follow: false, catalogFormat: "manual" }); const capture = new Capture({ @@ -155,6 +157,7 @@ test("the observer reads the publisher's largest group as its subscription began const publishedRoute = origin.route(Path.from("tone.hang"), { hidden: true }); const published = publishedRoute.broadcast; const track = published.createTrack("audio", { timescale: Time.Timescale.MILLI }); + if (!track) throw new Error("the track already exists"); publishedRoute.announce(); const frame = (group: Group.Producer, micros: number) => group.writeFrame({ @@ -201,6 +204,7 @@ async function captureGroupEnd(end: (group: Group.Producer) => void): Promise { let broadcast = broadcasts.get(request.path); if (!broadcast) { broadcast = new Moq.Broadcast.Producer(); - broadcast.createTrack("value", { maxAge: null }).writeFrame({ + const track = broadcast.createTrack("value", { maxAge: null }); + if (!track) throw new Error("the track already exists"); + track.writeFrame({ payload: new TextEncoder().encode(request.path), timestamp: Moq.Time.Timestamp.unscaled(0n), }); diff --git a/test/interop/clients/js-native/hls.ts b/test/interop/clients/js-native/hls.ts index c39447e94c3..59ae6e0babd 100644 --- a/test/interop/clients/js-native/hls.ts +++ b/test/interop/clients/js-native/hls.ts @@ -57,6 +57,7 @@ try { }; const publish = (kind: "video" | "audio", parts: Frame[][]) => { const media = broadcast.createTrack(kind, Container.trackInfo({ priority: Catalog.PRIORITY[kind] })); + if (!media) throw new Error("the track already exists"); const producer = new Container.Legacy.Producer(media, new Container.Legacy.Format(kind)); for (const [index, part] of parts.entries()) { if (index > 0) producer.discontinuity(); @@ -80,6 +81,7 @@ try { priority: Catalog.PRIORITY.catalog, compression: "deflate", }); + if (!track) throw new Error("the track already exists"); const catalog = new Json.Snapshot.Producer({ track, deltas: false }); catalog.update( Catalog.encode({ diff --git a/test/interop/clients/js-native/replace.ts b/test/interop/clients/js-native/replace.ts index 516161ddda8..90d8a0743d4 100644 --- a/test/interop/clients/js-native/replace.ts +++ b/test/interop/clients/js-native/replace.ts @@ -24,11 +24,18 @@ const received = [new Moq.Origin.Producer(), new Moq.Origin.Producer(), new Moq. const claim = published.claim(Moq.Path.from(prefix)); const broadcast = new Moq.Broadcast.Producer(); const path = Moq.Path.from(`${prefix}/entity`); -let track = broadcast.createTrack("value", { maxAge: null }); +let track = replacement(); const serving = (async () => { for await (const request of claim.requested()) request.serve(broadcast); })(); +// The aborted track no longer holds the name, so its replacement takes it. +function replacement(): Moq.Track.Producer { + const created = broadcast.createTrack("value", { maxAge: null }); + if (!created) throw new Error("the track already exists"); + return created; +} + function write(sequence: bigint): void { const group = track.createGroup(sequence); group.writeFrame({ @@ -78,7 +85,7 @@ try { for (let sequence = 1n; sequence <= 64n; sequence++) { const continued = ordered.readFrame(); track.abort(new Moq.Error.Stream(Moq.StreamCode.Internal, { message: "source failed" })); - track = broadcast.createTrack("value", { maxAge: null }); + track = replacement(); write(sequence); check(await continued, sequence); ordered.close(); @@ -88,7 +95,7 @@ try { for (const [index, sequence] of [66n, 68n].entries()) { const continued: ReturnType = ordered.readFrame(); track.abort(new Moq.Error.Stream(Moq.StreamCode.Internal, { message: "source failed" })); - track = broadcast.createTrack("value", { maxAge: null }); + track = replacement(); const requests = track.requests(); write(sequence); const next: Moq.Track.Ordered = subscribe(index + 1, sequence); @@ -109,6 +116,7 @@ try { assert.equal(fill.end, future + 1n); assert.equal(fill.maxDelay, null); const group = fill.accept(future); + if (!group) throw new Error("the group was already answered"); group.writeFrame({ payload: new TextEncoder().encode(String(future)), timestamp: Moq.Time.Timestamp.unscaled(future), diff --git a/test/interop/clients/js-native/server.ts b/test/interop/clients/js-native/server.ts index a6d47792918..e299a6ff860 100644 --- a/test/interop/clients/js-native/server.ts +++ b/test/interop/clients/js-native/server.ts @@ -23,10 +23,12 @@ const origin = new Moq.Origin.Producer(); const broadcastRoute = origin.route(Moq.Path.from("handover"), { hidden: true }); const broadcast = broadcastRoute.broadcast; const video = broadcast.createTrack("video"); +if (!video) throw new Error("the track already exists"); broadcastRoute.announce(); const markerRoute = origin.route(Moq.Path.from("replacement"), { hidden: true }); const marker = markerRoute.broadcast; const ready = marker.createTrack("ready"); +if (!ready) throw new Error("the track already exists"); const markerGroup = appendNext(ready); markerGroup.writeFrame({ payload: new Uint8Array([42]), timestamp: Moq.Time.Timestamp.unscaled(markerGroup.start) }); markerGroup.finish(); diff --git a/test/interop/clients/js-native/tail.ts b/test/interop/clients/js-native/tail.ts index 03d34e82e38..5b399aebedc 100644 --- a/test/interop/clients/js-native/tail.ts +++ b/test/interop/clients/js-native/tail.ts @@ -102,6 +102,7 @@ function serveHistory(track: Moq.Track.Producer) { } for (let sequence = fill.wanted(); sequence !== undefined; sequence = fill.wanted()) { const group = fill.accept(sequence); + if (!group) throw new Error("the group was already answered"); for (const payload of frames(Number(sequence))) group.writeFrame({ payload, timestamp: Moq.Time.Timestamp.unscaled(group.start) }); group.finish(); @@ -137,6 +138,7 @@ try { if (datagram) { // Untimed: the OBJECT_DATAGRAM carries no timestamp, so the subscriber checks the payload alone. const track = broadcast.createDatagrams("tail"); + if (!track) throw new Error("the track already exists"); broadcastPublication.announce(); const lines = createInterface({ input: process.stdin }); const commands = lines[Symbol.asyncIterator](); @@ -162,6 +164,7 @@ try { maxAge: null, ...(status ? { priority: 2 } : {}), }); + if (!track) throw new Error("the track already exists"); if (cached) write(track); if (history) serveHistory(track); let head: Moq.Group.Producer | undefined; diff --git a/test/interop/clients/js/open-gop/main.ts b/test/interop/clients/js/open-gop/main.ts index 4e980bdd86b..38164fd17a1 100644 --- a/test/interop/clients/js/open-gop/main.ts +++ b/test/interop/clients/js/open-gop/main.ts @@ -63,6 +63,7 @@ window.runRecovery = async (packets) => { const route = origin.route(name); // Every group is written before the decoder reads from the first, so none may go stale. const track = route.broadcast.createTrack("video", { timescale: Moq.Time.Timescale.MICRO, maxAge: null }); + if (!track) throw new Error("the track already exists"); let group: Moq.Group.Producer | undefined; for (const packet of packets) { if (group?.start !== BigInt(packet.group)) { diff --git a/test/interop/clients/js/src/finish.ts b/test/interop/clients/js/src/finish.ts index 0e1124afc12..4731f2ee754 100644 --- a/test/interop/clients/js/src/finish.ts +++ b/test/interop/clients/js/src/finish.ts @@ -84,6 +84,7 @@ export function finish( maxAge: null, priority: Catalog.PRIORITY.video, }); + if (!track) throw new Error("the track already exists"); const media = new Container.Legacy.Producer(track, new Container.Legacy.Format(config)); let encodingError: Error | undefined; const encoder = new VideoEncoder({ @@ -125,13 +126,12 @@ export function finish( root.video = { renditions: { video: config } }; }); const serving = new Effect(); - catalog.serve( - broadcast.createTrack(Catalog.TRACK, { - timescale: Moq.Time.Timescale.MILLI, - priority: Catalog.PRIORITY.catalog, - }), - serving, - ); + const catalogTrack = broadcast.createTrack(Catalog.TRACK, { + timescale: Moq.Time.Timescale.MILLI, + priority: Catalog.PRIORITY.catalog, + }); + if (!catalogTrack) throw new Error("the track already exists"); + catalog.serve(catalogTrack, serving); serving.close(); broadcastRoute.announce(); // Keep the finished broadcast up for the late readers, then take it offline. @@ -142,6 +142,7 @@ export function finish( const healthRoute = origin.route(Moq.Path.from(`${path}.health`), { hidden: true }); const health = healthRoute.broadcast; const healthTrack = health.createTrack("live"); + if (!healthTrack) throw new Error("the track already exists"); const group = healthTrack.appendGroup(Moq.Time.Timestamp.unscaled((healthTrack.largest()?.group ?? -1n) + 1n)); group.writeFrame({ payload: new TextEncoder().encode("session-alive"), diff --git a/test/interop/compat/client.ts b/test/interop/compat/client.ts index 6707400df91..5a77d770e97 100644 --- a/test/interop/compat/client.ts +++ b/test/interop/compat/client.ts @@ -108,11 +108,10 @@ function budget(millis: number): Record { const broadcast = new Moq.Broadcast.Producer(); try { for (const spelling of spellings.slice(0, -1)) { + const track = broadcast.createTrack(`probe-${Object.keys(spelling)[0]}`); + if (!track) throw new Error("the probe track already exists"); try { - broadcast - .createTrack(`probe-${Object.keys(spelling)[0]}`) - .subscribe(spelling as Moq.Track.Subscription) - .close(); + track.subscribe(spelling as Moq.Track.Subscription).close(); return spelling; } catch (err) { if (!(err instanceof TypeError)) throw err; @@ -325,6 +324,7 @@ if (command === "sign") { : (origin as unknown as Released).createBroadcast(path); const broadcast = ("broadcast" in publication ? publication.broadcast : publication) as Moq.Broadcast.Producer; const track = broadcast.createTrack("data", { timescale: Moq.Time.Timescale.MICRO }); + if (!track) throw new Error("the track already exists"); publication.announce(); const connection = await connect({ url: new URL(args[0]), diff --git a/test/interop/ietf-compression.ts b/test/interop/ietf-compression.ts index 9e1b7894eed..67116f990e0 100644 --- a/test/interop/ietf-compression.ts +++ b/test/interop/ietf-compression.ts @@ -48,6 +48,7 @@ try { const track = subscriber.consume(Path.from("room")).track("data").subscribe(); try { const request = await Stream.accept(pair.server, version); + if (!request) throw new Error("the group was already answered"); assert(request); assert.equal(await request.reader.u53(), Subscribe.id); await Subscribe.decode(request.reader, version); diff --git a/test/interop/ietf-range-updates.ts b/test/interop/ietf-range-updates.ts index 36d4ca1184a..e94a4c74cf0 100644 --- a/test/interop/ietf-range-updates.ts +++ b/test/interop/ietf-range-updates.ts @@ -19,7 +19,9 @@ const pair = createMockTransportPair(`moqt-${input.draft}`); const origin = new OriginProducer(); const publication = origin.route(Path.from("room"), { hidden: true }); // The updates replay groups a newer one superseded, which the default zero max age would stale. -const track = publication.broadcast.createTrack("video", { maxAge: null }); +const created = publication.broadcast.createTrack("video", { maxAge: null }); +if (!created) throw new Error("the track already exists"); +const track = created; publication.announce(); const publisher = new Publisher({ quic: pair.server, @@ -30,6 +32,7 @@ const publisher = new Publisher({ const incoming = pair.client.incomingUnidirectionalStreams.getReader(); const client = await Stream.open(pair.client, { version }); const server = await Stream.accept(pair.server, version); +if (!server) throw new Error("the group was already answered"); assert(server); const responses: number[][] = []; const streams: number[][] = []; diff --git a/test/interop/track-status.ts b/test/interop/track-status.ts index acf43b74f95..059ca0757c6 100644 --- a/test/interop/track-status.ts +++ b/test/interop/track-status.ts @@ -26,6 +26,7 @@ const track = broadcast.createTrack("video", { maxAge: Duration.millis(5000), priority: 2, }); +if (!track) throw new Error("the track already exists"); const group = track.createGroup(4n); group.writeFrame({ payload: new Uint8Array([1]), timestamp: Timestamp.fromMillis(0) }); group.writeFrame({ payload: new Uint8Array([2]), timestamp: Timestamp.fromMillis(1) }); diff --git a/test/interop/tracks.ts b/test/interop/tracks.ts index a54bbc7ff23..38b566b6822 100644 --- a/test/interop/tracks.ts +++ b/test/interop/tracks.ts @@ -34,6 +34,7 @@ if (input.mode === "answer") { broadcast.createTrack("b"); // A namespace apart from the track of the same name. const datagrams = broadcast.createDatagrams("a", { timescale: Timescale.MILLI, priority: 2 }); + if (!datagrams) throw new Error("the track already exists"); const publisher = new Publisher(createMockTransportPair().server, version, randomHop(), origin.consume()); const stream = new Stream({ diff --git a/test/receive-credit/sender.ts b/test/receive-credit/sender.ts index 4340cce0ae7..0e0dc1ba2e5 100644 --- a/test/receive-credit/sender.ts +++ b/test/receive-credit/sender.ts @@ -41,7 +41,9 @@ const broadcast = broadcastRoute.broadcast; // No publisher limit, so the open `low` group stays the receiver's to give up on rather than // going stale here once a newer group arrives. const low = broadcast.createTrack("low", { maxAge: null }); +if (!low) throw new Error("the track already exists"); const high = broadcast.createTrack("high", { maxAge: null }); +if (!high) throw new Error("the track already exists"); broadcastRoute.announce(); const session = await Moq.Connection.connect({ diff --git a/test/stream-credit/driver.ts b/test/stream-credit/driver.ts index cca68f0903c..5715472d9d7 100644 --- a/test/stream-credit/driver.ts +++ b/test/stream-credit/driver.ts @@ -106,7 +106,11 @@ const payload = (track: Track, sequence: number, frame: number) => `${track.name const origin = new Moq.Origin.Producer(); const publication = origin.route(Moq.Path.from(broadcastName)); // No publisher age limit: each reader's budget alone decides which groups are still worth sending. -const tracks = plan.tracks.map((track) => publication.broadcast.createTrack(track.name, { maxAge: null })); +const tracks = plan.tracks.map((track) => { + const created = publication.broadcast.createTrack(track.name, { maxAge: null }); + if (!created) throw new Error("the track already exists"); + return created; +}); publication.announce(); // Bun has no WebTransport, so this dials the WebSocket, whose qmux stream limit @moq/net raises // far past what 300 subscriptions need: the only cap in play is the browser's. diff --git a/test/stream-limits/client.ts b/test/stream-limits/client.ts index f287085d968..5d906c19141 100644 --- a/test/stream-limits/client.ts +++ b/test/stream-limits/client.ts @@ -19,7 +19,9 @@ try { const publication = origin.route(path, { hidden: true }); // One group per track, never finished, so every group the reader receives stays live. for (let i = 0; i < count; i++) { - const group = publication.broadcast.createTrack(String(i)).appendGroup(Moq.Time.Timestamp.unscaled(0n)); + const track = publication.broadcast.createTrack(String(i)); + if (!track) throw new Error(`the track ${i} already exists`); + const group = track.appendGroup(Moq.Time.Timestamp.unscaled(0n)); group.writeFrame({ payload: new TextEncoder().encode(String(i)), timestamp: Moq.Time.Timestamp.unscaled(group.start), diff --git a/test/video/src/captions.ts b/test/video/src/captions.ts index 43542d18bb5..003bb844c9f 100644 --- a/test/video/src/captions.ts +++ b/test/video/src/captions.ts @@ -21,6 +21,7 @@ export function captions() { ]) { textCatalog.renditions[name] = { format: "utf8", role: "subtitle", container: { kind: "legacy" } }; const track = producer.createTrack(name); + if (!track) throw new Error("the track already exists"); const group = track.appendGroup(Time.Timestamp.unscaled(0n)); group.writeFrame({ payload: Legacy.encodeFrame(new TextEncoder().encode(text), Duration.micros(1_000_000)), diff --git a/test/video/src/poster.ts b/test/video/src/poster.ts index 769c8d6a9c0..b56825ac242 100644 --- a/test/video/src/poster.ts +++ b/test/video/src/poster.ts @@ -12,6 +12,7 @@ async function poster(audio: boolean, buffered: boolean) { const producerRoute = origin.route(name, { hidden: true }); const producer = producerRoute.broadcast; const track = producer.createTrack("video"); + if (!track) throw new Error("the track already exists"); const group = track.appendGroup(Time.Timestamp.unscaled(0n)); const audioTrack = audio ? producer.createTrack("audio") : undefined; const audioGroup = audioTrack?.appendGroup(Time.Timestamp.unscaled(0n)); From 31db28969596c256ddf6504a54b6dfd0011a1bbe Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 18 Nov 2026 23:53:11 -0800 Subject: [PATCH 05/10] fix(moq-gst): name the taken track in its reserve error Co-Authored-By: Claude Opus 5.5 --- rs/moq-gst/src/sink/pad.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/rs/moq-gst/src/sink/pad.rs b/rs/moq-gst/src/sink/pad.rs index 434f8fcae52..4a1d686d0b8 100644 --- a/rs/moq-gst/src/sink/pad.rs +++ b/rs/moq-gst/src/sink/pad.rs @@ -521,7 +521,7 @@ impl Pad { let broadcast = broadcast.clone(); let request = broadcast .reserve_track(name.clone()) - .with_context(|| format!("cannot reserve track {name}"))?; + .with_context(|| format!("the track {name} already exists"))?; // Raw data declares a short explicit max age for subscribers that buffer its samples. let info = moq_net::track::Info::default() .with_timescale(moq_net::Timescale::MICRO) @@ -617,7 +617,7 @@ impl Pad { let name = Self::track_name(&broadcast, requested, ".mp3"); let request = broadcast .reserve_track(name.clone()) - .with_context(|| format!("cannot reserve track {name}"))?; + .with_context(|| format!("the track {name} already exists"))?; let producer = request.accept(hang::container::track_info(hang::catalog::PRIORITY.audio)); ( moq_mux::codec::mp3::Import::new(producer, reserved, Self::audio_config(config.into(), container))? @@ -650,7 +650,7 @@ impl Pad { let name = Self::track_name(&broadcast, requested, ".opus"); let request = broadcast .reserve_track(name.clone()) - .with_context(|| format!("cannot reserve track {name}"))?; + .with_context(|| format!("the track {name} already exists"))?; let producer = request.accept(hang::container::track_info(hang::catalog::PRIORITY.audio)); ( moq_mux::codec::opus::Import::new(producer, reserved, Self::audio_config(config, container))? @@ -727,7 +727,7 @@ impl Pad { let name = Self::track_name(broadcast, requested, &format!(".{format}")); let request = broadcast .reserve_track(name.clone()) - .with_context(|| format!("cannot reserve track {name}"))?; + .with_context(|| format!("the track {name} already exists"))?; let mut video = import::VideoInit::new(format, init.to_vec()); video.hint.container = container; let track = import::Track::video(request, reserved, video)?; @@ -746,7 +746,7 @@ impl Pad { let name = Self::track_name(broadcast, requested, &format!(".{format}")); let request = broadcast .reserve_track(name.clone()) - .with_context(|| format!("cannot reserve track {name}"))?; + .with_context(|| format!("the track {name} already exists"))?; let mut audio = import::AudioInit::new(format, init.to_vec()); audio.container = container; let track = import::Track::audio(request, reserved, audio)?; @@ -1482,7 +1482,7 @@ mod tests { ); assert_eq!( second.observe_caps(&broadcast, &catalog, producer_options(&h264_caps(), Some("camera")),), - CapsOutcome::Failed("cannot reserve track camera: duplicate".to_string()), + CapsOutcome::Failed("the track camera already exists".to_string()), "the duplicate reservation is rejected" ); assert!(second.is_failed(), "the collision fails the second pad"); From e8cc6317ec9284675cb885a96229a9207d8be405 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 00:14:51 -0800 Subject: [PATCH 06/10] fix(moq-net): a listed stream without acks reads as acknowledged Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/transport/boxed.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/rs/moq-net/src/transport/boxed.rs b/rs/moq-net/src/transport/boxed.rs index 5e65e8d34ac..45611abaccf 100644 --- a/rs/moq-net/src/transport/boxed.rs +++ b/rs/moq-net/src/transport/boxed.rs @@ -395,8 +395,8 @@ impl Listed { open::Rank::new(state.group.as_ref().map(|group| group.read()), state.priority) } - /// Whether the peer acknowledged everything written to it, never assumed when the transport - /// cannot tell. + /// Whether the peer acknowledged everything written to it, always so for a transport that + /// cannot see acknowledgments. pub(super) fn acknowledged(&self) -> bool { let state = self.lock(); let offset = state.stream.offset(); @@ -1300,7 +1300,6 @@ mod test { open::Rank::Ungrouped { .. } => panic!("the stream is in a group"), }; assert_eq!(grouped(&session), (1, 2)); - assert!(!session.open_streams()[0].1.acknowledged()); poll::SendGroup::set_priority(&mut low, 3); assert_eq!(grouped(&session), (3, 2)); From 8fee00084acb95bddae02ea7eeb599c0a359afbd Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 02:25:03 -0800 Subject: [PATCH 07/10] test(moq-net): pin that a sink without acks reads as acknowledged Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/transport/boxed.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/rs/moq-net/src/transport/boxed.rs b/rs/moq-net/src/transport/boxed.rs index 45611abaccf..4639dca791d 100644 --- a/rs/moq-net/src/transport/boxed.rs +++ b/rs/moq-net/src/transport/boxed.rs @@ -1282,7 +1282,7 @@ mod test { } /// A grouped stream ranks by its group's current priority, and follows a move to another - /// group; a transport that cannot tell reports no acknowledgement. + /// group; a transport that cannot see acknowledgements reports its bytes acknowledged. #[test] fn a_listed_stream_ranks_by_its_group() { let session = Session::new(SinkSession::new(Default::default()).with_groups()); @@ -1305,6 +1305,7 @@ mod test { assert_eq!(grouped(&session), (3, 2)); poll::SendStream::set_group(&mut stream, &high); assert_eq!(grouped(&session), (5, 2)); + assert!(session.open_streams()[0].1.acknowledged()); } /// A stream accepted while the connection window was held back, such as one buffered From b50c71a22affb30e1263923946da9f54cf366d17 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 07:35:51 -0800 Subject: [PATCH 08/10] style: format the merge's call-site updates Co-Authored-By: Claude Opus 5.5 --- js/net/src/ietf/publisher.test.ts | 4 +++- rs/moq-bench/src/replay.rs | 16 +++++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index 2424957df66..e27a2c6f2a5 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -4710,7 +4710,9 @@ test.each(["plain", "routed"])( }, }); spyOn(fx.pair.server, "createUnidirectionalStream").mockImplementationOnce(async () => unacknowledged); - const track = defined(fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Duration.millis(500) })); + const track = defined( + fx.broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Duration.millis(500) }), + ); writeGroup(track, 1); const { client } = await runSubscribe( fx, diff --git a/rs/moq-bench/src/replay.rs b/rs/moq-bench/src/replay.rs index 5f60ac14dae..b0a173b8c02 100644 --- a/rs/moq-bench/src/replay.rs +++ b/rs/moq-bench/src/replay.rs @@ -131,13 +131,15 @@ pub async fn run(args: Args) -> anyhow::Result<()> { let mut tracks = Vec::new(); for path in &args.publish { let route = publish.route(path.as_str(), moq_net::origin::RouteOptions::hidden())?; - let track = route.broadcast().create_track( - TRACK, - track::Info::default() - .with_timescale(moq_net::Timescale::MILLI) - .with_max_age(None), - ) - .context("the replay track is already published")?; + let track = route + .broadcast() + .create_track( + TRACK, + track::Info::default() + .with_timescale(moq_net::Timescale::MILLI) + .with_max_age(None), + ) + .context("the replay track is already published")?; route.announce()?; routes.push(route); tracks.push(track.clone()); From 48478050e61fa1807d74d5847abcc888d2a83457 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 08:32:00 -0800 Subject: [PATCH 09/10] fix(js/net): a relayed-fetch test unwraps its created track --- js/net/src/lite/publisher.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index 0db04df2046..e15417981c7 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -3527,7 +3527,7 @@ test("lite draft-07: a relayed fetch sent whole resets as too old when it goes s const upstream = createMockTransportPair(ALPN_07_WIP); const source = new OriginProducer(); const broadcast = publish(source, Path.from("live")); - const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null }); + const track = defined(broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: null })); const frame = (ms: number) => ({ payload: new TextEncoder().encode("x"), timestamp: Timestamp.fromMillis(ms) }); const whole = track.createGroup(0n); whole.writeFrame(frame(0)); From d241c841cc4bd2ce8153debea5465f2fd91ae064 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 08:50:37 -0800 Subject: [PATCH 10/10] docs(js): snippets guard createTrack's undefined --- doc/lib/js/net.md | 2 ++ doc/lib/js/publish.md | 2 ++ js/e2ee/README.md | 2 ++ 3 files changed, 6 insertions(+) diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index e81f8ac33a4..61b037dc397 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -32,6 +32,8 @@ const connection = await Moq.Connection.connect({ // Hidden until its first track exists, then announced. const route = origin.route(Moq.Path.from("chat.room"), { hidden: true }); const track = route.broadcast.createTrack("messages", { timescale: Moq.Time.Timescale.MILLI }); +// Undefined while a live track already holds the name. +if (!track) throw new Error("track name taken"); const now = Moq.Time.Timestamp.now(); const group = track.appendGroup(now); group.writeFrame({ payload: new TextEncoder().encode("hello"), timestamp: now }); diff --git a/doc/lib/js/publish.md b/doc/lib/js/publish.md index c96077e88cb..a35df9925f8 100644 --- a/doc/lib/js/publish.md +++ b/doc/lib/js/publish.md @@ -170,6 +170,8 @@ signals.run((effect) => { // still replays the last value. Each value is stamped with when it was // written, so the track declares a timescale. const track = net.createTrack("meta.json", { timescale: Moq.Time.Timescale.MILLI }); + // Undefined while a live track already holds the name. + if (!track) return; effect.cleanup(() => { track.finish(); track.close(); diff --git a/js/e2ee/README.md b/js/e2ee/README.md index 9ccbda860cc..240c7abe158 100644 --- a/js/e2ee/README.md +++ b/js/e2ee/README.md @@ -44,6 +44,8 @@ const route = origin.route(await credential.path("meeting.hang"), { const video = await new Broadcast.Producer(route.broadcast, generation).createTrack("video", { timescale: Time.Timescale.MILLI, }); +// Undefined while a live track already holds the name. +if (!video) throw new Error("track name taken"); route.announce(); const now = Time.Timestamp.now();