From 7f13ad27161ac01199e936c022c966829651c448 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 09:25:26 -0800 Subject: [PATCH 01/12] chore(quest): claim quest/m2/route-roles.md Quest-Claim: cf9e58f94ac5faca From 2cfd9eb5c2ab30c51e12b15b8bbf3c988acab114 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 10:24:17 -0800 Subject: [PATCH 02/12] feat(moq-net)!: prototype the split shape, route_prefix returns a Claim Co-Authored-By: Claude Opus 5.5 --- rs/moq-c/src/origin.rs | 89 +- rs/moq-c/src/test.rs | 2 +- rs/moq-cli/tests/integration/instances.rs | 2 +- rs/moq-ffi/src/origin.rs | 63 +- rs/moq-net-tests/tests/announce_allocs.rs | 2 +- .../tests/integration/hop_limit.rs | 2 +- .../tests/integration/ietf_conformance.rs | 2 +- rs/moq-net-tests/tests/integration/restart.rs | 6 +- rs/moq-net/benches/origin.rs | 4 +- rs/moq-net/src/fuzz.rs | 8 +- rs/moq-net/src/ietf/cluster.rs | 2 +- rs/moq-net/src/ietf/publisher.rs | 130 +-- rs/moq-net/src/ietf/session.rs | 4 +- rs/moq-net/src/ietf/subscriber.rs | 10 +- rs/moq-net/src/lite/publisher.rs | 70 +- rs/moq-net/src/lite/subscriber.rs | 10 +- rs/moq-net/src/lite/subscriber/routed.rs | 2 +- rs/moq-net/src/model/announced.rs | 2 +- rs/moq-net/src/model/broadcast.rs | 2 +- rs/moq-net/src/model/follow.rs | 10 +- rs/moq-net/src/model/mod.rs | 2 +- rs/moq-net/src/model/origin.rs | 801 ++++++++++-------- rs/moq-net/src/model/resume_model.rs | 2 +- rs/moq-net/src/server.rs | 4 +- .../tests/integration/claim_continues.rs | 2 +- rs/moq-net/tests/integration/drained_claim.rs | 2 +- rs/moq-stats/Cargo.toml | 2 +- rs/moq-stats/src/aggregate.rs | 4 +- 28 files changed, 707 insertions(+), 534 deletions(-) diff --git a/rs/moq-c/src/origin.rs b/rs/moq-c/src/origin.rs index 4555090edd6..63fd6e534a2 100644 --- a/rs/moq-c/src/origin.rs +++ b/rs/moq-c/src/origin.rs @@ -148,17 +148,68 @@ impl State { } struct RouteEntry { - inner: moq_net::origin::Route, driver: crate::ffi::Background, /// The instance last read, borrowed by [Origin::route_instance]. instance: String, - /// An exact route's broadcast fill handle, or a prefix route's request delivery task. + /// An exact route with its broadcast fill handle, or a prefix claim with its request + /// delivery task. kind: RouteKind, } enum RouteKind { - Exact { broadcast: Id }, - Prefix { requests: Id }, + Exact { + route: moq_net::origin::Route, + broadcast: Id, + }, + Prefix { + claim: moq_net::origin::Claim, + requests: Id, + }, +} + +/// The native route behind a handle, as [Origin::route_with] lends it. +pub enum Held<'a> { + Route(&'a moq_net::origin::Route), + Claim(&'a moq_net::origin::Claim), +} + +impl Held<'_> { + pub fn instance(&self) -> moq_net::Instance { + match self { + Self::Route(route) => route.instance(), + Self::Claim(claim) => claim.instance(), + } + } + + pub fn announce(&self) -> Result<(), moq_net::Error> { + match self { + Self::Route(route) => route.announce(), + Self::Claim(claim) => claim.announce(), + } + } + + pub fn withdraw(&self) { + match self { + Self::Route(route) => route.withdraw(), + Self::Claim(claim) => claim.withdraw(), + } + } + + pub fn set_cost(&self, cost: u64) -> Result<(), moq_net::Error> { + match self { + Self::Route(route) => route.set_cost(cost), + Self::Claim(claim) => claim.set_cost(cost), + } + } +} + +impl RouteEntry { + fn held(&self) -> Held<'_> { + match &self.kind { + RouteKind::Exact { route, .. } => Held::Route(route), + RouteKind::Prefix { claim, .. } => Held::Claim(claim), + } + } } impl Origin { @@ -412,9 +463,8 @@ impl Origin { // Read only on request: reading a hidden job's instance binds it. self.routes.insert(RouteEntry { instance: String::new(), - inner: route, driver, - kind: RouteKind::Exact { broadcast }, + kind: RouteKind::Exact { route, broadcast }, }) } @@ -431,18 +481,17 @@ impl Origin { let driver = origin.driver.clone(); let result = origin.producer.route_prefix(prefix, options); driver.check()?; - let route = result?; - let instance = route.instance().to_string(); + let claim = result?; + let instance = claim.instance().to_string(); // The route first, so the delivery task finds it once it runs; it cannot lock the // state before this call returns. let (task, close) = Task::new(on_request); let requests = self.route_requests.insert(task)?; let id = match self.routes.insert(RouteEntry { - inner: route, driver: driver.clone(), instance, - kind: RouteKind::Prefix { requests }, + kind: RouteKind::Prefix { claim, requests }, }) { Ok(id) => id, Err(err) => { @@ -474,9 +523,9 @@ impl Origin { _ = &mut close => return Ok(()), request = kio::wait(|waiter| { let state = State::lock(); - match state.origin.routes.get(route) { - Some(entry) => entry.inner.poll_requested(waiter), - None => std::task::Poll::Ready(None), + match state.origin.routes.get(route).map(|entry| &entry.kind) { + Some(RouteKind::Prefix { claim, .. }) => claim.poll_requested(waiter), + _ => std::task::Poll::Ready(None), } }) => match request { Some(request) => request, @@ -504,10 +553,10 @@ impl Origin { pub fn route_with( &self, route: Id, - f: impl FnOnce(&moq_net::origin::Route) -> Result, + f: impl FnOnce(Held<'_>) -> Result, ) -> Result { let entry = self.route_entry(route)?; - let result = f(&entry.inner); + let result = f(entry.held()); entry.driver.check()?; Ok(result?) } @@ -515,7 +564,7 @@ impl Origin { /// An exact route's broadcast fill handle, or [`Error::BroadcastNotFound`] on a prefix route. pub fn route_broadcast(&self, route: Id) -> Result { match self.route_entry(route)?.kind { - RouteKind::Exact { broadcast } => Ok(broadcast), + RouteKind::Exact { broadcast, .. } => Ok(broadcast), RouteKind::Prefix { .. } => Err(Error::BroadcastNotFound), } } @@ -523,7 +572,7 @@ impl Origin { pub fn route_instance(&mut self, route: Id, dst: &mut moq_string) -> Result<(), Error> { let entry = self.routes.get_mut(route).ok_or(Error::NotFound)?; entry.driver.check()?; - entry.instance = entry.inner.instance().to_string(); + entry.instance = entry.held().instance().to_string(); *dst = moq_string { data: entry.instance.as_ptr().cast::(), len: entry.instance.len(), @@ -533,13 +582,13 @@ impl Origin { /// Release a route handle and stop a prefix route's request delivery, returning the route /// for the caller to retract by dropping it. - pub fn route_take(&mut self, route: Id) -> Result { + pub fn route_take(&mut self, route: Id) -> Result, Error> { let entry = self.routes.remove(route).ok_or(Error::NotFound)?; - if let RouteKind::Prefix { requests } = entry.kind { + if let RouteKind::Prefix { requests, .. } = entry.kind { // Already gone once the origin closed and the task delivered its terminal callback. let _ = self.route_requests.close(requests, Error::NotFound); } - Ok(entry.inner) + Ok(entry.kind) } pub fn broadcast_request_path(&self, request: Id, dst: &mut crate::moq_string) -> Result<(), Error> { diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index 07807c53564..ff4d8a68f52 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -5817,7 +5817,7 @@ fn an_instance_pins_request_and_follow() { } /// Serve `prefix` on `origin` dynamically. -fn serve_dynamic(origin: u32, prefix: &str) -> moq_net::origin::Route { +fn serve_dynamic(origin: u32, prefix: &str) -> moq_net::origin::Claim { let _runtime = crate::ffi::RUNTIME.enter(); let origin = crate::Id::try_from(origin).unwrap(); State::lock() diff --git a/rs/moq-cli/tests/integration/instances.rs b/rs/moq-cli/tests/integration/instances.rs index 029df508218..9b955159da5 100644 --- a/rs/moq-cli/tests/integration/instances.rs +++ b/rs/moq-cli/tests/integration/instances.rs @@ -287,7 +287,7 @@ versions! { /// A worker claiming `live`, answering each request with a job's exact route: the catalog, /// which names `./media` under the job's instance, and the media it references. struct Worker { - claim: origin::Route, + claim: origin::Claim, jobs: std::sync::Arc>>, } diff --git a/rs/moq-ffi/src/origin.rs b/rs/moq-ffi/src/origin.rs index d1b252fc084..c34d195d8ab 100644 --- a/rs/moq-ffi/src/origin.rs +++ b/rs/moq-ffi/src/origin.rs @@ -149,7 +149,7 @@ pub struct MoqAnnounceConsumer { #[derive(uniffi::Object)] pub struct MoqRoute { /// The route itself, released on cancel. - reads: Polled, + reads: Polled, /// An exact route's broadcast, wrapped once so every caller shares its catalog. broadcast: Option>, /// The instance last read, reported once the route is cancelled. @@ -412,6 +412,57 @@ impl MoqOriginConsumer { // ---- MoqRoute ---- +/// The native route a [`MoqRoute`] holds: an exact route or a prefix claim. +enum Held { + Route(moq_net::origin::Route), + Claim(moq_net::origin::Claim), +} + +impl Held { + fn instance(&self) -> moq_net::Instance { + match self { + Self::Route(route) => route.instance(), + Self::Claim(claim) => claim.instance(), + } + } + + fn is_announced(&self) -> bool { + match self { + Self::Route(route) => route.is_announced(), + Self::Claim(claim) => claim.is_announced(), + } + } + + fn announce(&self) -> Result<(), moq_net::Error> { + match self { + Self::Route(route) => route.announce(), + Self::Claim(claim) => claim.announce(), + } + } + + fn withdraw(&self) { + match self { + Self::Route(route) => route.withdraw(), + Self::Claim(claim) => claim.withdraw(), + } + } + + fn set_cost(&self, cost: u64) -> Result<(), moq_net::Error> { + match self { + Self::Route(route) => route.set_cost(cost), + Self::Claim(claim) => claim.set_cost(cost), + } + } + + /// A claim's next request; an exact route yields none. + fn poll_requested(&self, waiter: &kio::Waiter) -> Poll> { + match self { + Self::Route(_) => Poll::Ready(None), + Self::Claim(claim) => claim.poll_requested(waiter), + } + } +} + impl MoqRoute { /// An exact route's native options, always hidden so [`Self::exact`] attaches the catalog /// track before anyone can find the route, and whether the caller asked it visible. @@ -432,14 +483,14 @@ impl MoqRoute { if visible { route.announce()?; } - Ok(Self::new(route, Some(Arc::new(broadcast)), driver)) + Ok(Self::new(Held::Route(route), Some(Arc::new(broadcast)), driver)) } - fn prefix(route: moq_net::origin::Route, driver: Background) -> Self { - Self::new(route, None, driver) + fn prefix(claim: moq_net::origin::Claim, driver: Background) -> Self { + Self::new(Held::Claim(claim), None, driver) } - fn new(route: moq_net::origin::Route, broadcast: Option>, driver: Background) -> Self { + fn new(route: Held, broadcast: Option>, driver: Background) -> Self { // Reading a hidden job's instance binds it, so one is cached only once it announces or // is read. let instance = if route.is_announced() || broadcast.is_none() { @@ -456,7 +507,7 @@ impl MoqRoute { } /// Run `f` against the route, refused with `Cancelled` once it was cancelled. - fn with(&self, f: impl FnOnce(&moq_net::origin::Route) -> Result) -> Result { + fn with(&self, f: impl FnOnce(&Held) -> Result) -> Result { let _guard = crate::ffi::enter(); self.driver.check()?; let result = self.reads.peek(f).ok_or(MoqError::Cancelled)?; diff --git a/rs/moq-net-tests/tests/announce_allocs.rs b/rs/moq-net-tests/tests/announce_allocs.rs index 7e01c4bdd7c..2e781ce17d5 100644 --- a/rs/moq-net-tests/tests/announce_allocs.rs +++ b/rs/moq-net-tests/tests/announce_allocs.rs @@ -77,7 +77,7 @@ unsafe impl GlobalAlloc for Counting { static ALLOCATOR: Counting = Counting; /// Land `peer`'s route at `path`, as a session does: one hop, at `cost`. -fn peer_route(producer: &origin::Producer, path: &'static str, peer: u64, cost: u64) -> origin::Route { +fn peer_route(producer: &origin::Producer, path: &'static str, peer: u64, cost: u64) -> origin::Claim { moq_net::fuzz::requests_route( producer, Path::from_static(path), diff --git a/rs/moq-net-tests/tests/integration/hop_limit.rs b/rs/moq-net-tests/tests/integration/hop_limit.rs index 8c36f23ec50..6fb90d9caf6 100644 --- a/rs/moq-net-tests/tests/integration/hop_limit.rs +++ b/rs/moq-net-tests/tests/integration/hop_limit.rs @@ -22,7 +22,7 @@ fn produce_origin(hop: u64) -> origin::Producer { } /// Land a peer's route at `path` on `origin`, as its session does. -fn forward(origin: &origin::Producer, path: &str, route: origin::RouteInfo) -> origin::Route { +fn forward(origin: &origin::Producer, path: &str, route: origin::RouteInfo) -> origin::Claim { moq_net::fuzz::requests_route(origin, moq_net::Path::new(path).unwrap(), route).unwrap() } diff --git a/rs/moq-net-tests/tests/integration/ietf_conformance.rs b/rs/moq-net-tests/tests/integration/ietf_conformance.rs index cd9cb6c9ac4..8881c19c3b1 100644 --- a/rs/moq-net-tests/tests/integration/ietf_conformance.rs +++ b/rs/moq-net-tests/tests/integration/ietf_conformance.rs @@ -23,7 +23,7 @@ async fn routing(version: &str, cluster: bool) { let relay = origin(2); let reader = origin(4); let prefix = Arc::new( - moq_net::fuzz::requests_route(&publisher, moq_net::Path::new(PREFIX).unwrap(), Default::default()).unwrap(), + moq_net::fuzz::requests_route(&publisher, moq_net::Path::new(PREFIX).unwrap(), moq_net::fuzz::route_info([], 0, None)).unwrap(), ); let broadcast = broadcast::Info::new().produce(); let track = broadcast.create_track("test", moq_net::track::Info::default()).unwrap(); diff --git a/rs/moq-net-tests/tests/integration/restart.rs b/rs/moq-net-tests/tests/integration/restart.rs index b6c6a776042..4c2dd24f942 100644 --- a/rs/moq-net-tests/tests/integration/restart.rs +++ b/rs/moq-net-tests/tests/integration/restart.rs @@ -176,7 +176,7 @@ relay_chain_tests! { /// the hidden `fuzz` module as a session lands it, so its answers carry no exact route. struct Worker { origin: origin::Producer, - _claim: Rc, + _claim: Rc, _outputs: Rc>>, } @@ -290,7 +290,7 @@ async fn prefix_pool_lite07() { /// claim moves to another instance or re-prices in place, so it lands through the hidden /// `fuzz` module as a session lands it. struct Claim { - dynamic: Rc, + dynamic: Rc, outputs: Rc>>, /// The price the claim advertises, kept across an instance move. cost: std::cell::Cell, @@ -642,7 +642,7 @@ async fn a_more_specific_source_cannot_fill_a_held_covering_track() { /// exact route, which carries the claim's instance until it ends, and `outputs[path]` /// holds the latest. struct Pool { - _claim: Rc, + _claim: Rc, outputs: Rc>>, answered: Rc>, } diff --git a/rs/moq-net/benches/origin.rs b/rs/moq-net/benches/origin.rs index 67000f6f818..b3c4da140a6 100644 --- a/rs/moq-net/benches/origin.rs +++ b/rs/moq-net/benches/origin.rs @@ -655,7 +655,7 @@ fn bench_announce_fronts(c: &mut Criterion) { } /// Answer the claim's request for `path`, dropping any other it queued. -fn answer(claim: &origin::Route, path: &str) -> origin::Route { +fn answer(claim: &origin::Claim, path: &str) -> origin::Route { loop { let request = claim .requested() @@ -886,7 +886,7 @@ const POOL_HOP: u64 = 1_000; struct Pool { producer: origin::Producer, driver: origin::Driver, - _members: Vec, + _members: Vec, _producers: Vec, _consumers: Vec, cursors: Vec, diff --git a/rs/moq-net/src/fuzz.rs b/rs/moq-net/src/fuzz.rs index 20548c21a4c..081a5499e79 100644 --- a/rs/moq-net/src/fuzz.rs +++ b/rs/moq-net/src/fuzz.rs @@ -461,7 +461,7 @@ pub fn route_info( cost: u64, instance: Option<(crate::Instance, u64)>, ) -> crate::origin::RouteInfo { - let info = crate::origin::RouteInfo::default() + let info = crate::origin::RouteInfo::new() .with_hops(hop_chain(hops)) .with_cost(cost); match instance { @@ -475,12 +475,12 @@ pub fn requests_route( origin: &crate::origin::Producer, prefix: impl Into, route: crate::origin::RouteInfo, -) -> Result { +) -> Result { origin.forward(prefix, route) } /// Replace a peer claim's route in place, as a session does on a route update. -pub fn update_route(dynamic: &crate::origin::Route, route: crate::origin::RouteInfo) -> Result<(), crate::Error> { +pub fn update_route(dynamic: &crate::origin::Claim, route: crate::origin::RouteInfo) -> Result<(), crate::Error> { dynamic.update(route) } @@ -1917,7 +1917,7 @@ pub struct RequestValidity { impl RequestValidity { /// Watch which instance this route's peer selects for a path. - pub fn new(route: &crate::origin::Route, path: &crate::Path) -> Self { + pub fn new(route: &crate::origin::Claim, path: &crate::Path) -> Self { Self { watch: crate::model::broadcast::RequestValidity::for_source(route, path), periods: Vec::new(), diff --git a/rs/moq-net/src/ietf/cluster.rs b/rs/moq-net/src/ietf/cluster.rs index d3a633dee82..96183b57a6d 100644 --- a/rs/moq-net/src/ietf/cluster.rs +++ b/rs/moq-net/src/ietf/cluster.rs @@ -162,7 +162,7 @@ impl Advert { let advertised = crate::origin::Cost::new(self.cost); // The prefix travels separately: it is stamped where the advertisement // attaches (the namespace). - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_hops(self.hops.hops().clone()) .with_cost(advertised.charged(link_cost)) } diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index c8a18f6278e..8180ff9b384 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -10723,11 +10723,11 @@ mod serve_tests { let h = serve(version); let _old = h ._origin - .announce("old/first", crate::origin::RouteInfo::default()) + .announce("old/first", crate::origin::RouteInfo::new()) .unwrap(); let _new = h ._origin - .announce("new/second", crate::origin::RouteInfo::default()) + .announce("new/second", crate::origin::RouteInfo::new()) .unwrap(); settle().await; let session = ScriptedSession::new(Vec::new()); @@ -10880,7 +10880,7 @@ mod serve_tests { let other = h ._origin - .announce("other", crate::origin::RouteInfo::default()) + .announce("other", crate::origin::RouteInfo::new()) .unwrap(); settle().await; assert!(futures::poll!(running.as_mut()).is_pending()); @@ -11055,7 +11055,7 @@ mod serve_tests { session.log.fail_writes(); let _other = h ._origin - .announce("other", crate::origin::RouteInfo::default()) + .announce("other", crate::origin::RouteInfo::new()) .unwrap(); for _ in 0..10 { assert!( @@ -11401,7 +11401,7 @@ mod serve_tests { for version in ALL_VERSIONS { let mut h = serve(version); - let claim = h._origin.forward("live", crate::origin::RouteInfo::default()).unwrap(); + let claim = h._origin.forward("live", crate::origin::RouteInfo::new()).unwrap(); let auth = crate::auth::Link::new(false); auth.handle().authorize(¬hing()); h.publisher = h.publisher.clone().with_auth(auth); @@ -11421,7 +11421,7 @@ mod serve_tests { for version in ALL_VERSIONS { let mut h = serve(version); - let claim = h._origin.forward("live", crate::origin::RouteInfo::default()).unwrap(); + let claim = h._origin.forward("live", crate::origin::RouteInfo::new()).unwrap(); let auth = crate::auth::Link::new(false); h.publisher = h.publisher.clone().with_auth(auth.clone()); @@ -11738,7 +11738,7 @@ mod serve_tests { let version = Version::Draft22; for path in [".", "./child", ".session", ".session/extension"] { let h = serve(version); - let claim = h._origin.forward("", crate::origin::RouteInfo::default()).unwrap(); + let claim = h._origin.forward("", crate::origin::RouteInfo::new()).unwrap(); settle().await; let stream = Stream::open(&crate::driver::Transport::new(h.session.clone()), version) .await @@ -13884,7 +13884,7 @@ mod serve_tests { { *namespace = crate::Path::from_static("lobby"); } - Some(h._origin.forward("lobby", crate::origin::RouteInfo::default()).unwrap()) + Some(h._origin.forward("lobby", crate::origin::RouteInfo::new()).unwrap()) } FetchParked::Responding => None, }; @@ -15492,7 +15492,7 @@ mod serve_tests { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let (claim, published) = match parked { Parked::Resolving => ( - Some(origin.forward("room", crate::origin::RouteInfo::default()).unwrap()), + Some(origin.forward("room", crate::origin::RouteInfo::new()).unwrap()), None, ), Parked::Acking | Parked::Ending => { @@ -15729,7 +15729,7 @@ mod serve_tests { let mut idle = None; match setup { Setup::Resolving => { - let route = origin.forward("room", crate::origin::RouteInfo::default()).unwrap(); + let route = origin.forward("room", crate::origin::RouteInfo::new()).unwrap(); let request = { let requested = std::pin::pin!(route.requested()); match futures::future::select(requested, serving.as_mut()).await { @@ -18036,7 +18036,7 @@ mod tests { let echoed = origin .announce( "from/peer", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_hops(echoed_hops) .with_via(assigned), ) @@ -18045,7 +18045,7 @@ mod tests { let mut local_hops = crate::Hops::new(); local_hops.push(other).unwrap(); let local = origin - .announce("from/us", crate::origin::RouteInfo::default().with_hops(local_hops)) + .announce("from/us", crate::origin::RouteInfo::new().with_hops(local_hops)) .unwrap(); (publisher, consumer, vec![echoed, local]) @@ -18095,7 +18095,7 @@ mod tests { let _echoed = origin .announce( "from/peer", - crate::origin::RouteInfo::default().with_hops(hops.clone()).with_via(r1), + crate::origin::RouteInfo::new().with_hops(hops.clone()).with_via(r1), ) .unwrap(); @@ -18167,7 +18167,7 @@ mod tests { let _echoed = origin .announce( "from/peer", - crate::origin::RouteInfo::default().with_hops(hops).with_via(assigned), + crate::origin::RouteInfo::new().with_hops(hops).with_via(assigned), ) .unwrap(); @@ -18211,13 +18211,13 @@ mod tests { let mut clean = crate::Hops::new(); clean.push(crate::Hop::new(778).unwrap()).unwrap(); let _clean = origin - .announce("cam-clean", crate::origin::RouteInfo::default().with_hops(clean)) + .announce("cam-clean", crate::origin::RouteInfo::new().with_hops(clean)) .unwrap(); // A chain with no room left for our own hop cannot be forwarded. let mut full = crate::Hops::new(); while full.push(crate::Hop::new(100 + full.len() as u64).unwrap()).is_ok() {} let _full = origin - .announce("cam-full", crate::origin::RouteInfo::default().with_hops(full)) + .announce("cam-full", crate::origin::RouteInfo::new().with_hops(full)) .unwrap(); settle().await; @@ -18286,7 +18286,7 @@ mod tests { let _tainted = origin .announce( "route-flip-cam", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_hops(tainted_hops) .with_via(assigned), ) @@ -18316,7 +18316,7 @@ mod tests { let clean = origin .announce( "route-flip-cam", - crate::origin::RouteInfo::default().with_hops(clean_hops), + crate::origin::RouteInfo::new().with_hops(clean_hops), ) .unwrap(); settle().await; @@ -18373,7 +18373,7 @@ mod tests { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _cam = origin - .announce("lonely-cam", crate::origin::RouteInfo::default()) + .announce("lonely-cam", crate::origin::RouteInfo::new()) .unwrap(); settle().await; @@ -18447,7 +18447,7 @@ mod tests { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _local = origin - .announce("local-cam", crate::origin::RouteInfo::default()) + .announce("local-cam", crate::origin::RouteInfo::new()) .unwrap(); settle().await; @@ -18493,7 +18493,7 @@ mod tests { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let local = origin - .announce("local-cam", crate::origin::RouteInfo::default()) + .announce("local-cam", crate::origin::RouteInfo::new()) .unwrap(); settle().await; @@ -18559,7 +18559,7 @@ mod tests { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _local = origin - .announce("local-cam", crate::origin::RouteInfo::default()) + .announce("local-cam", crate::origin::RouteInfo::new()) .unwrap(); settle().await; @@ -18651,9 +18651,9 @@ mod tests { scoped, } = case; let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let _cam = origin.announce("cam", crate::origin::RouteInfo::default()).unwrap(); + let _cam = origin.announce("cam", crate::origin::RouteInfo::new()).unwrap(); let _stats = origin - .announce(".stats/node", crate::origin::RouteInfo::default()) + .announce(".stats/node", crate::origin::RouteInfo::new()) .unwrap(); settle().await; @@ -18801,7 +18801,7 @@ mod tests { for version in [Version::Draft18] { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let early = origin - .announce("early-cam", crate::origin::RouteInfo::default()) + .announce("early-cam", crate::origin::RouteInfo::new()) .unwrap(); settle().await; @@ -18847,7 +18847,7 @@ mod tests { ); let _late = origin - .announce("late-cam", crate::origin::RouteInfo::default()) + .announce("late-cam", crate::origin::RouteInfo::new()) .unwrap(); for _ in 0..100 { assert!(futures::poll!(run.as_mut()).is_pending()); @@ -18896,7 +18896,7 @@ mod tests { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let first = origin - .announce("first-cam", crate::origin::RouteInfo::default()) + .announce("first-cam", crate::origin::RouteInfo::new()) .unwrap(); settle().await; @@ -18933,7 +18933,7 @@ mod tests { // Send capacity runs out before the second advertisement can send its header. set_gate(&gate, false); let _second = origin - .announce("second-cam", crate::origin::RouteInfo::default()) + .announce("second-cam", crate::origin::RouteInfo::new()) .unwrap(); settle().await; @@ -19000,7 +19000,7 @@ mod tests { // The state a refused or failed offer leaves behind: the peer holds nothing, and // the loop is coming back to it on a timer. let suffix: crate::Path = crate::Path::from_static("from/peer"); - let mut watch = Watched::new(crate::origin::RouteInfo::default().with_hops(hops)); + let mut watch = Watched::new(crate::origin::RouteInfo::new().with_hops(hops)); watch.deferred = true; let mut ns = Namespaces::new(cluster::Peer::default(), Target::Requests); @@ -19027,7 +19027,7 @@ mod tests { let cam = origin .announce( "solo-cam", - crate::origin::RouteInfo::default().with_instance(instance.clone(), 0), + crate::origin::RouteInfo::new().with_instance(instance.clone(), 0), ) .unwrap(); settle().await; @@ -19063,7 +19063,7 @@ mod tests { let _standby = origin .announce( "solo-cam", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_instance(instance, 0) .with_cost(0), ) @@ -19133,7 +19133,7 @@ mod tests { let _cold = origin .announce( "cam", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_instance(instance.clone(), 0) .with_cost(4), ) @@ -19170,7 +19170,7 @@ mod tests { let _warm = origin .announce( "cam", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_instance(instance, 0) .with_cost(0), ) @@ -19212,7 +19212,7 @@ mod tests { let _cold = origin .announce( "cam", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_instance(instance.clone(), 0) .with_cost(4), ) @@ -19266,7 +19266,7 @@ mod tests { let _warm = origin .announce( "cam", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_instance(instance, 0) .with_cost(0), ) @@ -19301,7 +19301,7 @@ mod tests { let _from_a = origin .announce( "cam", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_instance(instance.clone(), 0) .with_hops(publisher_a) .with_cost(4), @@ -19339,7 +19339,7 @@ mod tests { let _from_b = origin .announce( "cam", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_instance(instance, 0) .with_hops(publisher_b) .with_cost(0), @@ -19442,7 +19442,7 @@ mod tests { .present(bytes::Bytes::from_static(b"second-secret"), false) .unwrap(); let cam = origin - .announce("cam", crate::origin::RouteInfo::default().with_auth(first)) + .announce("cam", crate::origin::RouteInfo::new().with_auth(first)) .unwrap(); settle().await; @@ -19464,7 +19464,7 @@ mod tests { "{version}: PUBLISH_NAMESPACE carries the auth" ); - cam.update(crate::origin::RouteInfo::default().with_auth(second)) + cam.update(crate::origin::RouteInfo::new().with_auth(second)) .unwrap(); let expected = request_update( version, @@ -19508,7 +19508,7 @@ mod tests { .present(bytes::Bytes::from_static(b"foreign-secret"), false) .unwrap(); let _cam = origin - .announce("cam", crate::origin::RouteInfo::default().with_auth(foreign)) + .announce("cam", crate::origin::RouteInfo::new().with_auth(foreign)) .unwrap(); settle().await; @@ -19534,7 +19534,7 @@ mod tests { let origin = unheld_origin(); let auth = crate::auth::Link::ietf(false); let token = auth.present(bytes::Bytes::from_static(b"late-secret"), false).unwrap(); - let cam = origin.announce("cam", crate::origin::RouteInfo::default()).unwrap(); + let cam = origin.announce("cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; let ok = publish_namespace_ok(VERSION).await; @@ -19543,7 +19543,7 @@ mod tests { poll_until(&mut run, &log, b"cam", 1).await; assert_eq!(occurrences(&log, b"late-secret"), 0, "named before it had an auth"); - cam.update(crate::origin::RouteInfo::default().with_auth(token)) + cam.update(crate::origin::RouteInfo::new().with_auth(token)) .unwrap(); poll_until(&mut run, &log, b"cam", 2).await; @@ -19564,13 +19564,13 @@ mod tests { let a = origin .announce( "cam-a", - crate::origin::RouteInfo::default().with_auth(present(b"a-first")), + crate::origin::RouteInfo::new().with_auth(present(b"a-first")), ) .unwrap(); let b = origin .announce( "cam-b", - crate::origin::RouteInfo::default().with_auth(present(b"b-first")), + crate::origin::RouteInfo::new().with_auth(present(b"b-first")), ) .unwrap(); settle().await; @@ -19583,9 +19583,9 @@ mod tests { assert_eq!(occurrences(&log, b"cam-a"), 1, "cam-a was never advertised"); assert_eq!(occurrences(&log, b"cam-b"), 1, "cam-b was never advertised"); - a.update(crate::origin::RouteInfo::default().with_auth(present(b"a-second"))) + a.update(crate::origin::RouteInfo::new().with_auth(present(b"a-second"))) .unwrap(); - b.update(crate::origin::RouteInfo::default().with_auth(present(b"b-second"))) + b.update(crate::origin::RouteInfo::new().with_auth(present(b"b-second"))) .unwrap(); poll_until(&mut run, &log, b"b-second", 1).await; assert_eq!(occurrences(&log, b"a-second"), 1, "cam-a's renewal never went out"); @@ -19595,7 +19595,7 @@ mod tests { "cam-b's renewal waited on cam-a's answer" ); - let _c = origin.announce("cam-c", crate::origin::RouteInfo::default()).unwrap(); + let _c = origin.announce("cam-c", crate::origin::RouteInfo::new()).unwrap(); poll_until(&mut run, &log, b"cam-c", 1).await; assert_eq!( occurrences(&log, b"cam-c"), @@ -19614,7 +19614,7 @@ mod tests { for fin in [true, false] { let origin = unheld_origin(); - let _cam = origin.announce("cam", crate::origin::RouteInfo::default()).unwrap(); + let _cam = origin.announce("cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; let (session, peer) = memory::pair(memory::Config::default()); @@ -19685,7 +19685,7 @@ mod tests { .map(|name| { ( name, - origin.announce(name, crate::origin::RouteInfo::default()).unwrap(), + origin.announce(name, crate::origin::RouteInfo::new()).unwrap(), ) }) .collect(); @@ -19772,7 +19772,7 @@ mod tests { let auth = crate::auth::Link::ietf(false); let token = auth.present(bytes::Bytes::from(vec![0; 70_000]), false).unwrap(); let _cam = origin - .announce("cam", crate::origin::RouteInfo::default().with_auth(token)) + .announce("cam", crate::origin::RouteInfo::new().with_auth(token)) .unwrap(); settle().await; @@ -19819,7 +19819,7 @@ mod tests { let auth = crate::auth::Link::ietf(false); let present = |token: &'static [u8]| auth.present(bytes::Bytes::from_static(token), false).unwrap(); let cam = origin - .announce("cam", crate::origin::RouteInfo::default().with_auth(present(b"first"))) + .announce("cam", crate::origin::RouteInfo::new().with_auth(present(b"first"))) .unwrap(); settle().await; @@ -19842,7 +19842,7 @@ mod tests { // The idle request has read its OK and parked, so the reset waits for the renewal // to wake it. peer.close(crate::lite::test_transport::Close::Reset); - cam.update(crate::origin::RouteInfo::default().with_auth(present(b"second"))) + cam.update(crate::origin::RouteInfo::new().with_auth(present(b"second"))) .unwrap(); poll_until(&mut run, &log, b"second", 1).await; assert!(futures::poll!(run.as_mut()).is_pending()); @@ -19872,7 +19872,7 @@ mod tests { let auth = crate::auth::Link::ietf(false); let present = |token: &'static [u8]| auth.present(bytes::Bytes::from_static(token), false).unwrap(); let cam = origin - .announce("cam", crate::origin::RouteInfo::default().with_auth(present(b"first"))) + .announce("cam", crate::origin::RouteInfo::new().with_auth(present(b"first"))) .unwrap(); settle().await; @@ -19880,7 +19880,7 @@ mod tests { let (publisher, log) = auth_publisher(&origin, &auth, vec![ok.clone(), ok], version); let mut run = std::pin::pin!(publisher.run_publish_namespaces()); poll_until(&mut run, &log, b"first", 1).await; - cam.update(crate::origin::RouteInfo::default().with_auth(present(b"second"))) + cam.update(crate::origin::RouteInfo::new().with_auth(present(b"second"))) .unwrap(); poll_until(&mut run, &log, b"second", 1).await; assert_eq!(occurrences(&log, b"second"), 1, "the renewal never went out"); @@ -19912,7 +19912,7 @@ mod tests { } .produce(); let _old = origin - .announce("cam", crate::origin::RouteInfo::default().with_cost(4)) + .announce("cam", crate::origin::RouteInfo::new().with_cost(4)) .unwrap(); settle().await; @@ -19941,7 +19941,7 @@ mod tests { assert_eq!(occurrences(&log, b"cam"), 1, "the advertisement never went out"); let _new = origin - .announce("cam", crate::origin::RouteInfo::default().with_cost(0)) + .announce("cam", crate::origin::RouteInfo::new().with_cost(0)) .unwrap(); for _ in 0..100 { assert!(futures::poll!(run.as_mut()).is_pending()); @@ -19968,7 +19968,7 @@ mod tests { let _cold = origin .announce( "cam", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_instance(instance.clone(), 0) .with_cost(4), ) @@ -20008,7 +20008,7 @@ mod tests { let _warm = origin .announce( "cam", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_instance(instance, 0) .with_cost(0), ) @@ -20044,10 +20044,10 @@ mod tests { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _first = origin - .announce("first-cam", crate::origin::RouteInfo::default()) + .announce("first-cam", crate::origin::RouteInfo::new()) .unwrap(); let _second = origin - .announce("second-cam", crate::origin::RouteInfo::default()) + .announce("second-cam", crate::origin::RouteInfo::new()) .unwrap(); settle().await; @@ -20112,7 +20112,7 @@ mod tests { let first = auth.present(bytes::Bytes::from_static(b"first"), false).unwrap(); let mut first_grant = first.grant(); let cam = origin - .announce("cam", crate::origin::RouteInfo::default().with_auth(first)) + .announce("cam", crate::origin::RouteInfo::new().with_auth(first)) .unwrap(); settle().await; @@ -20153,7 +20153,7 @@ mod tests { assert!(futures::poll!(run.as_mut()).is_pending()); if matches!(stage, Stage::UpdateWrite) { let second = auth.present(bytes::Bytes::from_static(b"second"), false).unwrap(); - cam.update(crate::origin::RouteInfo::default().with_auth(second)) + cam.update(crate::origin::RouteInfo::new().with_auth(second)) .unwrap(); settle().await; assert!(futures::poll!(run.as_mut()).is_pending()); @@ -20206,7 +20206,7 @@ mod tests { async fn an_unanswered_advertisement_is_withdrawn() { for version in [Version::Draft18] { let origin = unheld_origin(); - let _cam = origin.announce("cam", crate::origin::RouteInfo::default()).unwrap(); + let _cam = origin.announce("cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; // The peer takes the request and answers nothing. @@ -20247,7 +20247,7 @@ mod tests { for version in [Version::Draft18] { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _cam = origin - .announce("lonely-cam", crate::origin::RouteInfo::default()) + .announce("lonely-cam", crate::origin::RouteInfo::new()) .unwrap(); settle().await; let session = @@ -20299,7 +20299,7 @@ mod tests { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _cam = origin - .announce("lonely-cam", crate::origin::RouteInfo::default()) + .announce("lonely-cam", crate::origin::RouteInfo::new()) .unwrap(); settle().await; diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index 68551d383cb..65cd449cc71 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -2643,7 +2643,7 @@ mod tests { async fn announce_occurrences(peer_declared: Option) -> usize { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _cam = origin - .announce("solo-cam", crate::origin::RouteInfo::default()) + .announce("solo-cam", crate::origin::RouteInfo::new()) .unwrap(); // An open gate: an unsolicited PUBLISH_NAMESPACE can reach the wire. @@ -2750,7 +2750,7 @@ mod tests { fn auth_session(auth: bool) -> AuthSession { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let cam = origin - .announce("solo-cam", crate::origin::RouteInfo::default()) + .announce("solo-cam", crate::origin::RouteInfo::new()) .unwrap(); let gate = kio::Producer::new(true); diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index c33f213180e..a7516e9ce5b 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -928,7 +928,7 @@ struct BroadcastState { // The served route: dropping it (and the serve task's clone) retracts the // route and rejects its queued requests. `None` while the session's limit holds // it back, though the peer still advertises it. - dynamic: Option, + dynamic: Option, // Bumped each time the route attaches, so a serve task outlived by a limit that // took the route away and gave it back ends rather than serve beside the new one. @@ -1346,7 +1346,7 @@ impl Subscriber { let mut hops = crate::Hops::new(); hops.push(crate::Hop::UNKNOWN) .expect("an empty hop chain has room for one entry"); - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_hops(hops) .with_via(self.via(peer)) // A peer without Cluster contributes only the arriving link price. @@ -10722,7 +10722,7 @@ mod tests { let _source = origin .announce( "room/host", - crate::origin::RouteInfo::default().with_hops(upstream.clone()), + crate::origin::RouteInfo::new().with_hops(upstream.clone()), ) .unwrap(); announced.expect_next_active("room/host").await; @@ -11337,7 +11337,7 @@ mod tests { let path = crate::Path::from_static("room/host"); let first = Advertised { - route: crate::origin::RouteInfo::default() + route: crate::origin::RouteInfo::new() .with_hops(hop_path(&[7, 9]).hops().clone()) .with_cost(4), }; @@ -11348,7 +11348,7 @@ mod tests { // A new chain and cost: the route updates in place. let rerouted = Advertised { - route: crate::origin::RouteInfo::default() + route: crate::origin::RouteInfo::new() .with_hops(hop_path(&[7, 11]).hops().clone()) .with_cost(2), }; diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 023a8eee12e..45a268df05f 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -1949,7 +1949,7 @@ impl RequestServe { if requesting.is_none() { // The peer requested this exact path, so it has already seen an // announcement for it. The immediate lookup resolves it at once, is - // served on demand by the route covering it (an `origin::Route`), or + // served on demand by the route covering it (an `origin::Claim`), or // errors when there is none. let origin = ready!(self.shared.poll_serving_origin(waiter)); let origin = self.shared.node_filter(origin, R::node(msg)); @@ -3602,7 +3602,7 @@ mod announce_test { let update = |prefix: &'static str, cost| crate::announce::Announce { prefix: crate::Path::try_from(prefix).unwrap(), captures: None, - route: origin::RouteInfo::default().with_cost(cost), + route: origin::RouteInfo::new().with_cost(cost), }; let events = [ origin::RouteEvent::Start(update("a", 1)), @@ -3634,7 +3634,7 @@ mod announce_test { let origin = Hop::new(1).unwrap().produce(); let root = "r".repeat(100); let _route = origin - .announce(format!("{root}/x"), origin::RouteInfo::default()) + .announce(format!("{root}/x"), origin::RouteInfo::new()) .unwrap(); let consumer = origin .consume() @@ -3713,7 +3713,7 @@ mod announce_test { "{announces:?}" ); - let _route = origin.announce("x", origin::RouteInfo::default()).unwrap(); + let _route = origin.announce("x", origin::RouteInfo::new()).unwrap(); // The origin feeds its node from a task. kio::clock::sim::yield_now().await; assert!(answer.poll(&mut stream, false, &waiter).is_pending()); @@ -3729,8 +3729,8 @@ mod announce_test { #[test] fn synced_survives_a_removed_initial_route_and_live_churn() { let origin = Hop::new(1).unwrap().produce(); - let removed = origin.announce("z/removed", origin::RouteInfo::default()).unwrap(); - let _initial = origin.announce("z/retained", origin::RouteInfo::default()).unwrap(); + let removed = origin.announce("z/removed", origin::RouteInfo::new()).unwrap(); + let _initial = origin.announce("z/retained", origin::RouteInfo::new()).unwrap(); let consumer = origin.consume(); let mut announced = consumer.routes(); let budget = kio::Producer::new(0usize); @@ -3759,7 +3759,7 @@ mod announce_test { for limit in 1..=4 { churn.push( origin - .announce(format!("a/{limit}"), origin::RouteInfo::default()) + .announce(format!("a/{limit}"), origin::RouteInfo::new()) .unwrap(), ); *budget.write().ok().unwrap() = limit; @@ -3779,8 +3779,8 @@ mod announce_test { #[test] fn a_partial_regrant_cannot_overtake_an_initial_route() { let origin = Hop::new(1).unwrap().produce(); - let _a = origin.announce("a", origin::RouteInfo::default()).unwrap(); - let _b = origin.announce("b", origin::RouteInfo::default()).unwrap(); + let _a = origin.announce("a", origin::RouteInfo::new()).unwrap(); + let _b = origin.announce("b", origin::RouteInfo::new()).unwrap(); let consumer = origin.consume(); let mut announced = consumer.routes(); let budget = kio::Producer::new(1usize); @@ -3825,8 +3825,8 @@ mod announce_test { #[test] fn synced_cuts_a_regrant_burst_at_the_initial_bound() { let origin = Hop::new(1).unwrap().produce(); - let _a = origin.announce("a", origin::RouteInfo::default()).unwrap(); - let _b = origin.announce("b", origin::RouteInfo::default()).unwrap(); + let _a = origin.announce("a", origin::RouteInfo::new()).unwrap(); + let _b = origin.announce("b", origin::RouteInfo::new()).unwrap(); let consumer = origin.consume(); let mut announced = consumer.routes(); let budget = kio::Producer::new(0usize); @@ -3856,7 +3856,7 @@ mod announce_test { panic!("the changed grant is ready"); }; run.regrant(&mut stream, &consumer, restricted).unwrap(); - let _live = origin.announce("c", origin::RouteInfo::default()).unwrap(); + let _live = origin.announce("c", origin::RouteInfo::new()).unwrap(); run.regrant(&mut stream, &consumer, crate::auth::Permit::default()) .unwrap(); *budget.write().ok().unwrap() = 4; @@ -3885,8 +3885,8 @@ mod announce_test { #[test] fn a_seen_retraction_can_precede_synced() { let origin = Hop::new(1).unwrap().produce(); - let first = origin.announce("a", origin::RouteInfo::default()).unwrap(); - let unseen = origin.announce("b", origin::RouteInfo::default()).unwrap(); + let first = origin.announce("a", origin::RouteInfo::new()).unwrap(); + let unseen = origin.announce("b", origin::RouteInfo::new()).unwrap(); let consumer = origin.consume(); let mut announced = consumer.routes(); let budget = kio::Producer::new(1usize); @@ -4049,7 +4049,7 @@ mod announce_test { #[kio::test] async fn a_silent_upstream_never_delays_the_answer() { let origin = Hop::new(1).unwrap().produce(); - let _route = origin.announce("cam", crate::origin::RouteInfo::default()).unwrap(); + let _route = origin.announce("cam", crate::origin::RouteInfo::new()).unwrap(); // An upstream that never answers its announce request. let _silent = origin.clone().with_link(crate::origin::Link::Upstream).snapshot(""); @@ -4083,7 +4083,7 @@ mod announce_test { let announcement = origin .announce( "cam", - crate::origin::RouteInfo::default().with_hops(pub_hops()).with_cost(7), + crate::origin::RouteInfo::new().with_hops(pub_hops()).with_cost(7), ) .unwrap(); @@ -4140,7 +4140,7 @@ mod announce_test { let late = h .origin - .announce("mic", crate::origin::RouteInfo::default().with_hops(pub_hops())) + .announce("mic", crate::origin::RouteInfo::new().with_hops(pub_hops())) .unwrap(); settle().await; match h.wire.take_announces().as_slice() { @@ -4164,7 +4164,7 @@ mod announce_test { let mut h = harness().await; h.announcement - .update(crate::origin::RouteInfo::default().with_hops(pub_hops()).with_cost(3)) + .update(crate::origin::RouteInfo::new().with_hops(pub_hops()).with_cost(3)) .unwrap(); kio::clock::sleep(crate::origin::Config::default().update_hold).await; settle().await; @@ -4183,7 +4183,7 @@ mod announce_test { async fn identical_update_is_quiet() { let h = harness().await; h.announcement - .update(crate::origin::RouteInfo::default().with_hops(pub_hops()).with_cost(7)) + .update(crate::origin::RouteInfo::new().with_hops(pub_hops()).with_cost(7)) .unwrap(); settle().await; h.assert_idle(); @@ -4197,7 +4197,7 @@ mod announce_test { async fn source_flip_restarts() { for version in [Version::Lite06, Version::Lite07] { let mut h = harness_on(version).await; - let route = crate::origin::RouteInfo::default().with_hops(pub_hops()).with_cost(7); + let route = crate::origin::RouteInfo::new().with_hops(pub_hops()).with_cost(7); let newer = h.origin.announce("cam", route.clone()).unwrap(); // A restart waits out the update hold like an update. kio::clock::sleep(crate::origin::Config::default().update_hold).await; @@ -4244,7 +4244,7 @@ mod announce_test { let mut h = harness_on(Version::Lite07).await; let instance = crate::Instance::random(); let route = |epoch| { - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_instance(instance.clone(), epoch) .with_hops(pub_hops()) .with_cost(7) @@ -4287,7 +4287,7 @@ mod announce_test { let mut h = harness_with(Version::Lite07, Some(auth.clone())).await; // Same chain and cost, so only the instance changed. Both land before the loop polls. - let route = crate::origin::RouteInfo::default().with_hops(pub_hops()).with_cost(7); + let route = crate::origin::RouteInfo::new().with_hops(pub_hops()).with_cost(7); let named = (!anonymous).then(crate::Instance::random); let route = match &named { Some(instance) => route.with_instance(instance.clone(), 0), @@ -4318,7 +4318,7 @@ mod announce_test { async fn clamped_cost_change_is_quiet() { let mut h = harness().await; let route = |cost| { - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_hops(pub_hops()) .with_cost(cost) }; @@ -4342,10 +4342,10 @@ mod announce_test { let tainted = Hops::try_from(vec![peer]).unwrap(); let _tainted = origin - .announce("echoed", crate::origin::RouteInfo::default().with_hops(tainted)) + .announce("echoed", crate::origin::RouteInfo::new().with_hops(tainted)) .unwrap(); let _clean = origin - .announce("local", crate::origin::RouteInfo::default().with_hops(pub_hops())) + .announce("local", crate::origin::RouteInfo::new().with_hops(pub_hops())) .unwrap(); let log = Log::default(); @@ -4381,7 +4381,7 @@ mod announce_test { let mut h = harness().await; let _late = h .origin - .announce("mic", crate::origin::RouteInfo::default().with_hops(pub_hops())) + .announce("mic", crate::origin::RouteInfo::new().with_hops(pub_hops())) .unwrap(); settle().await; match h.wire.take_announces().as_slice() { @@ -4397,7 +4397,7 @@ mod announce_test { let mut h = harness().await; h.announcement .update( - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_hops(pub_hops()) .with_cost(u64::MAX), ) @@ -9652,7 +9652,7 @@ mod tests { let _echoed = origin .forward( "echoed", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_hops(echoed_hops) .with_via(assigned), ) @@ -9661,7 +9661,7 @@ mod tests { let mut local_hops = Hops::new(); local_hops.push(upstream).unwrap(); let _local = origin - .forward("local", crate::origin::RouteInfo::default().with_hops(local_hops)) + .forward("local", crate::origin::RouteInfo::new().with_hops(local_hops)) .unwrap(); // A SETUP that declares no origin of its own, so only the assigned one applies. @@ -9712,7 +9712,7 @@ mod tests { let _tainted = origin .announce( "echoed", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_hops(tainted_hops) .with_via(assigned), ) @@ -9721,7 +9721,7 @@ mod tests { let mut clean_hops = Hops::new(); clean_hops.push(clean_publisher).unwrap(); let _clean = origin - .announce("local", crate::origin::RouteInfo::default().with_hops(clean_hops)) + .announce("local", crate::origin::RouteInfo::new().with_hops(clean_hops)) .unwrap(); let gate = kio::Producer::new(true); @@ -9766,7 +9766,7 @@ mod tests { let _broadcasts: Vec<_> = (0..max / 500 + 1) .map(|i| { origin - .announce(format!("{name}{i}"), crate::origin::RouteInfo::default()) + .announce(format!("{name}{i}"), crate::origin::RouteInfo::new()) .unwrap() }) .collect(); @@ -9797,7 +9797,7 @@ mod tests { async fn announce_init_broadcast_ends() { let self_origin = crate::Hop::new(1).unwrap(); let origin = crate::origin::Config::from(self_origin).produce(); - let cam = origin.announce("cam", crate::origin::RouteInfo::default()).unwrap(); + let cam = origin.announce("cam", crate::origin::RouteInfo::new()).unwrap(); let gate = kio::Producer::new(true); let session = SinkSession::gated_bi(gate.consume()); @@ -9833,7 +9833,7 @@ mod tests { async fn withdraw_before_init_sends_the_initial_burst() { let self_origin = crate::Hop::new(1).unwrap(); let origin = crate::origin::Config::from(self_origin).produce(); - let _cam = origin.announce("cam", crate::origin::RouteInfo::default()).unwrap(); + let _cam = origin.announce("cam", crate::origin::RouteInfo::new()).unwrap(); let gate = kio::Producer::new(true); let session = SinkSession::gated_bi(gate.consume()); @@ -10235,7 +10235,7 @@ mod tests { let mut _route = None; let mut held = None; match wait { - Wait::Broadcast => _route = Some(origin.forward("room", crate::origin::RouteInfo::default()).unwrap()), + Wait::Broadcast => _route = Some(origin.forward("room", crate::origin::RouteInfo::new()).unwrap()), Wait::Track => { let broadcast = origin.route("room", crate::origin::RouteOptions::hidden()).unwrap(); let dynamic = broadcast.broadcast().requests(); diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber.rs index 9d8f83f46a7..e51b0f6ee24 100644 --- a/rs/moq-net/src/lite/subscriber.rs +++ b/rs/moq-net/src/lite/subscriber.rs @@ -728,8 +728,8 @@ impl Subscriber { announced: &Announced, ) -> crate::origin::RouteInfo { let mut route = match announced.instance(path) { - Some((instance, epoch)) => crate::origin::RouteInfo::default().with_instance(instance, epoch), - None => crate::origin::RouteInfo::default(), + Some((instance, epoch)) => crate::origin::RouteInfo::new().with_instance(instance, epoch), + None => crate::origin::RouteInfo::new(), } .with_hops(hops) .with_cost(cost.charged(link_cost)) @@ -9668,7 +9668,7 @@ impl Announced { } /// Attach a route, queued for its first serve pass. - fn attach(&mut self, path: Path, route: crate::origin::RouteInfo, dynamic: crate::origin::Route) { + fn attach(&mut self, path: Path, route: crate::origin::RouteInfo, dynamic: crate::origin::Claim) { let wake = crate::util::QueueWake::new(path.clone(), self.ready.clone()); let route = AnnouncedRoute::new(route, dynamic, wake); route.waker.wake_by_ref(); @@ -9878,7 +9878,7 @@ struct AnnouncedRoute { /// without recomputing the chain. route: crate::origin::RouteInfo, /// Dropping it retracts the route and rejects its queued requests. - dynamic: crate::origin::Route, + dynamic: crate::origin::Claim, /// Closes as the route goes, which closes every source it minted. live: kio::Producer<()>, /// Whether the GOAWAY drain already re-priced this route. @@ -9893,7 +9893,7 @@ struct AnnouncedRoute { impl AnnouncedRoute { fn new( route: crate::origin::RouteInfo, - dynamic: crate::origin::Route, + dynamic: crate::origin::Claim, wake: Arc>, ) -> Self { Self { diff --git a/rs/moq-net/src/lite/subscriber/routed.rs b/rs/moq-net/src/lite/subscriber/routed.rs index 1372fdbc5d6..28ba6df8f97 100644 --- a/rs/moq-net/src/lite/subscriber/routed.rs +++ b/rs/moq-net/src/lite/subscriber/routed.rs @@ -426,7 +426,7 @@ impl Routed { true => crate::origin::Cost::DRAIN, false => crate::origin::Cost::new(served.claim.cost.saturating_add(served.metric)), }; - let route = crate::origin::RouteInfo::default() + let route = crate::origin::RouteInfo::new() .with_instance(served.claim.instance.clone(), served.claim.epoch) .with_hops(hops(id)) .with_cost(cost) diff --git a/rs/moq-net/src/model/announced.rs b/rs/moq-net/src/model/announced.rs index def40197835..4b2d6b8877e 100644 --- a/rs/moq-net/src/model/announced.rs +++ b/rs/moq-net/src/model/announced.rs @@ -168,7 +168,7 @@ mod tests { first .announce_info( - RouteInfo::default() + RouteInfo::new() .with_instance(Instance::random(), 0) .with_cost(Cost::new(5)), ) diff --git a/rs/moq-net/src/model/broadcast.rs b/rs/moq-net/src/model/broadcast.rs index 36a45e63326..9cdd5c76a3f 100644 --- a/rs/moq-net/src/model/broadcast.rs +++ b/rs/moq-net/src/model/broadcast.rs @@ -629,7 +629,7 @@ impl RequestValidity { } #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] - pub(crate) fn for_source(route: &crate::origin::Route, path: &crate::Path) -> Self { + pub(crate) fn for_source(route: &crate::origin::Claim, path: &crate::Path) -> Self { route .request_validity(path) .map(|selected| Self::Selected(std::sync::Arc::new(selected))) diff --git a/rs/moq-net/src/model/follow.rs b/rs/moq-net/src/model/follow.rs index d4468c5bbc0..624bd6dc3ae 100644 --- a/rs/moq-net/src/model/follow.rs +++ b/rs/moq-net/src/model/follow.rs @@ -409,7 +409,7 @@ mod tests { } fn route(instance: &Instance) -> RouteInfo { - RouteInfo::default().with_instance(instance.clone(), 0) + RouteInfo::new().with_instance(instance.clone(), 0) } fn options(instance: &Instance) -> RouteOptions { @@ -458,7 +458,7 @@ mod tests { #[kio::test] async fn follow_starts_on_the_serving_route_when_joining_late() { let origin = Hop::new(1).unwrap().produce(); - let _pool = origin.forward("pool", RouteInfo::default()).unwrap(); + let _pool = origin.forward("pool", RouteInfo::new()).unwrap(); let _exact = origin.route("pool/job", RouteOptions::default()).unwrap(); let mut follow = origin.consume().path_routes("pool/job").unwrap(); @@ -514,7 +514,7 @@ mod tests { let origin = Hop::new(1).unwrap().produce(); let mut follow = origin.consume().path_routes("pool/job").unwrap(); - let _pool = origin.forward("pool", RouteInfo::default()).unwrap(); + let _pool = origin.forward("pool", RouteInfo::new()).unwrap(); assert_eq!(followed(&mut follow).await, ("start", "pool".into())); let _exact = origin.route("pool/job", RouteOptions::default()).unwrap(); @@ -530,7 +530,7 @@ mod tests { let _chat = origin .scope("", &chat) .unwrap() - .forward("room/alice", RouteInfo::default()) + .forward("room/alice", RouteInfo::new()) .unwrap(); let mut follow = origin.consume().path_routes("room/alice").unwrap(); @@ -593,7 +593,7 @@ mod tests { } /// The next request a dynamic route receives for its path. - async fn requested(dynamic: &crate::origin::Route) -> crate::origin::Request { + async fn requested(dynamic: &crate::origin::Claim) -> crate::origin::Request { kio::clock::timeout(Duration::from_secs(1), dynamic.requested()) .await .expect("never asked") diff --git a/rs/moq-net/src/model/mod.rs b/rs/moq-net/src/model/mod.rs index cf3d12ce01b..dd6a79083e6 100644 --- a/rs/moq-net/src/model/mod.rs +++ b/rs/moq-net/src/model/mod.rs @@ -64,7 +64,7 @@ pub mod origin { #[cfg(feature = "async")] pub(crate) use super::origin_impl::NodeFilter; pub use super::origin_impl::{ - Config, Consumer, Cost, Driver, Link, Preference, Producer, Request, Requesting, Route, RouteInfo, + Claim, Config, Consumer, Cost, Driver, Link, Preference, Producer, Request, Requesting, Route, RouteInfo, RouteOptions, Source, }; pub use crate::route::RouteKey; diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 1fa50366b06..8b1ab53ce54 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -505,8 +505,10 @@ pub struct RouteInfo { pub(crate) node: Option, } -impl Default for RouteInfo { - fn default() -> Self { +impl RouteInfo { + /// No route yet: no instance, hops, cost or credential, entered here. Crate-private + /// because a delivered route always names an instance. + pub(crate) fn new() -> Self { Self { instance: None, epoch: 0, @@ -691,7 +693,7 @@ impl RouteOptions { RouteInfo { cost: self.cost, auth: self.auth.clone(), - ..RouteInfo::default() + ..RouteInfo::new() } } } @@ -1242,7 +1244,7 @@ struct RouteEntry { /// The origin node serving the route; see [`RouteInfo::node`]. node: Option, /// The queue requests under this route are served from, when the announcer - /// serves content on demand (a prefix [`Route`]). `None` for an advertise-only + /// serves content on demand (a [`Claim`]). `None` for an advertise-only /// announcement ([`Producer::announce`]) and for a local broadcast. server: Option>, /// The broadcast published on this origin at exactly `prefix`, when the @@ -1255,7 +1257,7 @@ struct RouteEntry { advertised: bool, /// Whether a peer the chain passes through has since withdrawn this prefix. /// The route was derived from that peer's advertisement, so it serves nobody - /// until the peer announces again. See [`Route::withdrawn`]. + /// until the peer announces again. See [`Claim::withdrawn`]. stale: bool, /// [`prefix_claim`] of [`Self::prefix`], built once at announce time. /// @@ -1377,7 +1379,7 @@ fn prefix_claim(prefix: &Path) -> Result { /// A served route's request queue: what materializes a requested path on demand. /// /// Shared by every requester resolving through the owning route and the -/// prefix [`Route`] draining it, so both sides work under one lock. +/// [`Claim`] draining it, so both sides work under one lock. #[derive(Default)] pub(super) struct ServeState { // Result channels for pending requests, keyed by absolute path so concurrent @@ -2415,14 +2417,14 @@ impl Producer { )?; let hidden = options.hidden; let control = RouteControl::new(options, &entry, request); - let route = Route::new(RouteState { - announcement: entry, - broadcast: Some(source.clone()), - server: None, - publisher: None, - control: kio::Lock::new(control), - _keepalive: self.tasks.keepalive(), - }); + let route = Route { + state: Arc::new(RouteState { + announcement: entry, + control: kio::Lock::new(control), + _keepalive: self.tasks.keepalive(), + }), + broadcast: source.clone(), + }; // Closing the broadcast retracts the route, and refuses the request a job's route // has not answered yet. The broadcast holds only a weak reference, so it never // keeps the route alive. @@ -2471,7 +2473,7 @@ impl Producer { /// A request under an advertise-only route resolves [`Error::Unroutable`] /// unless an announced broadcast or a prefix route ([`Self::route_prefix`]) covers /// the path too. Tests use it to shape the route table; everything else - /// advertises through an exact or prefix [`Route`], which serves what it claims. + /// advertises through a [`Route`] or [`Claim`], which serves what it claims. #[cfg(test)] pub(crate) fn announce( &self, @@ -2553,17 +2555,17 @@ impl Producer { self.link != Link::Local } - /// Create a route over `prefix` that serves the requests beneath it. + /// Create a [`Claim`] over `prefix` that serves the requests beneath it. /// - /// A route is always a prefix on the wire: it claims `prefix` and every path beneath - /// it (the empty prefix claims every path). A service that only serves some of + /// A route is always a prefix on the wire: a claim covers `prefix` and every path + /// beneath it (the empty prefix claims every path). A service that only serves some of /// them, say `pid/*.hang`, advertises the covering prefix and refuses the /// rest as they are requested; consumers narrow with a [`Pattern`] locally. /// This is the one shape every wire carries, so a route means the same /// thing on every hop. /// /// A consumer resolving a path under it through this route is handed to - /// [`Route::poll_requested`] as a [`Request`]: answer it by serving a broadcast already + /// [`Claim::poll_requested`] as a [`Request`]: answer it by serving a broadcast already /// held ([`Request::serve`]), under this route's instance, or by creating the path's /// own exact route ([`Request::route`]). This is how a service answers a whole /// subtree without publishing each path ahead of time; a publisher that @@ -2575,11 +2577,11 @@ impl Producer { /// continues on that path's answer rather than restarting. Once an exact route holding /// the lent instance stops serving it (withdrawn, closed, or renamed), this route moves /// to a fresh instance, as a restarted job's sequences are another stream: see - /// [`Route::instance`]. A route naming a stable instance lends nothing, and its + /// [`Claim::instance`]. A claim naming a stable instance lends nothing, and its /// answers each mint their own. /// - /// The route is priced, credentialed and shown like an exact one. It is visible - /// for as long as the returned [`Route`] (and every clone) lives, unless withdrawn. + /// The claim is priced, credentialed and shown like an exact route. It is visible + /// for as long as the returned [`Claim`] (and every clone) lives, unless withdrawn. /// /// The prefix must overlap this producer's pattern scope. Individual requests /// remain authoritative and are refused when they do not match the scope. @@ -2587,7 +2589,7 @@ impl Producer { &self, prefix: impl TryInto>, options: RouteOptions, - ) -> Result { + ) -> Result { // A minted instance lives in the table, which moves it on as its jobs end; see // [`OriginState::advance`]. let info = RouteInfo { @@ -2606,7 +2608,7 @@ impl Producer { &self, prefix: impl TryInto>, mut info: RouteInfo, - ) -> Result { + ) -> Result { // A handle that names no instance serves one of its own. let instance = info.instance.get_or_insert_with(Instance::random).clone(); let options = RouteOptions { @@ -2626,7 +2628,7 @@ impl Producer { advertised: bool, lends: bool, options: RouteOptions, - ) -> Result { + ) -> Result { let announcing = Announcing::new(self, prefix)?; let serve = kio::Shared::::default(); serve.lock().requests.add_handler(); @@ -2641,14 +2643,15 @@ impl Producer { None, )?; let control = RouteControl::new(options, &announcement, None); - Ok(Route::new(RouteState { - announcement, - broadcast: None, - server: Some(serve), + Ok(Claim { + state: Arc::new(RouteState { + announcement, + control: kio::Lock::new(control), + _keepalive: self.tasks.keepalive(), + }), + server: serve, publisher, - control: kio::Lock::new(control), - _keepalive: self.tasks.keepalive(), - })) + }) } /// Returns a producer rooted at `root` and restricted to matching `patterns`. @@ -2914,12 +2917,11 @@ struct Serving { lends: bool, } -/// A route on an origin: an exact path owning one broadcast, or a prefix serving the -/// requests beneath it. +/// An exact route on an origin: one path, owning the broadcast published there. /// /// On the publishing side ownership runs origin → route → broadcast → track → group → -/// frame. Created by [`Producer::route`] (exact), [`Producer::route_prefix`] (prefix), -/// or [`Request::route`] (the path's own exact route, answering a request). +/// frame. Created by [`Producer::route`], or by [`Request::route`] to answer a request +/// with the path's own route. A prefix served on demand is a [`Claim`] instead. /// /// A route mints its instance when it is created and keeps it for its lifetime, across /// [`withdraw`](Self::withdraw), [`announce`](Self::announce) and reconnects, since it @@ -2946,19 +2948,34 @@ struct Serving { #[derive(Clone)] #[must_use = "dropping the last clone of a route retracts it"] pub struct Route { + // Declared first so the advertisement retracts before the broadcast handle drops. state: Arc, + broadcast: broadcast::Producer, +} + +/// A prefix route on an origin: a claim that every path beneath a prefix can be served, +/// answering each request as it arrives. +/// +/// Created by [`Producer::route_prefix`]. Requests arrive on [`Self::requested`]; answer +/// each by serving a broadcast already held or by creating the path's own [`Route`]. +/// +/// Clones share one claim. Dropping the last clone retracts it and refuses the requests +/// still waiting. The claim keeps the origin's [`Driver`] running. +#[derive(Clone)] +#[must_use = "dropping the last clone of a claim retracts it"] +pub struct Claim { + state: Arc, + /// The queue requests arrive on. + server: kio::Shared, + /// Present for an application's claim, whose requests may create their own exact + /// routes. A session-forwarded request can only serve its peer's broadcast. + publisher: Option, } +/// What a [`Route`] and a [`Claim`] share: the advertisement and how it is changed. struct RouteState { /// The advertisement, retracted on drop. announcement: AnnounceProducer, - /// The broadcast an exact route owns. - broadcast: Option, - /// The queue a prefix route's requests arrive on. - server: Option>, - /// Present for an application's prefix route, whose requests may create their own - /// exact routes. A session-forwarded request can only serve its peer's broadcast. - publisher: Option, control: kio::Lock, /// A route is lifecycle work: the origin's driver keeps running for as long as one /// lives, even once every producer handle is gone. @@ -3024,43 +3041,57 @@ impl RouteState { } } -impl Route { - fn new(state: RouteState) -> Self { - Self { state: Arc::new(state) } +impl RouteState { + /// See [`Route::instance`] and [`Claim::instance`]. + fn instance(&self) -> Instance { + let mut control = self.control.lock(); + if control.held && !control.bound { + let lender = control.request.as_ref().map(|request| &request.home); + if let Some(current) = self.announcement.instance(lender) { + control.instance = current; + } + control.bound = control.request.is_some(); + } + control.instance.0.clone() } - /// The broadcast this exact route owns, to fill with tracks. - /// - /// # Panics - /// - /// On a prefix route ([`Producer::route_prefix`]), which owns none: answer its - /// requests instead. + /// See [`Route::withdraw`] and [`Claim::withdraw`]. + fn withdraw(&self) { + let _control = self.control.lock(); + self.announcement.withdraw(); + } + + /// See [`Route::is_announced`] and [`Claim::is_announced`]. + fn is_announced(&self) -> bool { + self.announcement.route().is_some() + } + + /// Apply `update` to the options, re-advertising a visible route in place. + fn change(&self, update: impl FnOnce(&mut RouteOptions)) -> Result<(), Error> { + let mut control = self.control.lock(); + update(&mut control.options); + if !self.announcement.is_live()? { + return Ok(()); + } + self.announcement.update_if(control.info(), None, |_| true).map(|_| ()) + } +} + +impl Route { + /// The broadcast this route owns, to fill with tracks. pub fn broadcast(&self) -> &broadcast::Producer { - self.state - .broadcast - .as_ref() - .expect("a prefix route owns no broadcast; answer its requests") + &self.broadcast } /// The stream this route serves, minted when it was created unless /// [`RouteOptions::with_instance`] named one. /// - /// Unnamed, a prefix route's ([`Producer::route_prefix`]) can change: it moves to a fresh - /// instance each time an answer holding its current one ends. A job's route - /// ([`Request::route`]) takes its prefix route's current one when it first announces, - /// or when this reads it first. Read before announcing, it is the one the job announces - /// under, and [`Self::announce`] fails with [`Error::Unroutable`] once the prefix route - /// has moved past it. + /// A job's route ([`Request::route`]) naming none takes its claim's current one when it + /// first announces, or when this reads it first. Read before announcing, it is the one + /// the job announces under, and [`Self::announce`] fails with [`Error::Unroutable`] once + /// the claim has moved past it. pub fn instance(&self) -> Instance { - let mut control = self.state.control.lock(); - if control.held && !control.bound { - let lender = control.request.as_ref().map(|request| &request.home); - if let Some(current) = self.state.announcement.instance(lender) { - control.instance = current; - } - control.bound = control.request.is_some(); - } - control.instance.0.clone() + self.state.instance() } /// Make the route visible, or keep it so. Idempotent. @@ -3070,10 +3101,10 @@ impl Route { /// /// Fails with [`Error::Closed`] once the route's broadcast closed or the origin's /// [`Driver`] was dropped, and with [`Error::Unroutable`], announcing nothing, when a - /// job's request was released or its prefix route retracted meanwhile, or when the job - /// read its [`instance`](Self::instance) and its prefix route has moved past it since: - /// that route can never announce. In that last case the request goes back to the prefix - /// route's handler, its requesters still waiting. + /// job's request was released or its claim retracted meanwhile, or when the job read + /// its [`instance`](Self::instance) and its claim has moved past it since: that route + /// can never announce. In that last case the request goes back to the claim's handler, + /// its requesters still waiting. pub fn announce(&self) -> Result<(), Error> { let mut control = self.state.control.lock(); let info = control.info(); @@ -3082,16 +3113,16 @@ impl Route { }; let bound = std::mem::take(&mut control.bound).then(|| control.instance.0.clone()); let mut moved = false; - let answer = self.broadcast().consume(); + let answer = self.broadcast.consume(); let mut resolved = None; // Answered under the table lock that every release takes first, so the route // lands only for a request still pending and no release can slip in between. - // A job's route naming no instance takes its prefix route's current one as it - // lands, so whatever resolved through the prefix route for the path continues on - // it rather than restarting. + // A job's route naming no instance takes its claim's current one as it lands, so + // whatever resolved through the claim for the path continues on it rather than + // restarting. let lender = control.held.then_some(&request.home); let admitted = self.state.announcement.update_if(info, lender, |table| { - // The prefix route's entries leave the table before its retraction releases the + // The claim's entries leave the table before its retraction releases the // request, so one gone from it no longer answers, even before that release. let home = table.routes.covering(&request.path).any(|entry| { entry @@ -3102,8 +3133,8 @@ impl Route { if !home { return false; } - // A job that read its instance announces under it or not at all. A prefix route - // that lends nothing never moves, and one no longer serving released the request. + // A job that read its instance announces under it or not at all. A claim that + // lends nothing never moves, and one no longer serving released the request. if let Some(bound) = &bound && table .lender(&request.path, &request.home) @@ -3113,7 +3144,7 @@ impl Route { return false; } // The exact route owns this answer's availability. Caching it under the - // prefix would keep serving it after this route is withdrawn. + // claim would keep serving it after this route is withdrawn. resolved = request .home .lock() @@ -3127,8 +3158,8 @@ impl Route { // advertising through the ordinary branch now that the request is taken. self.state.announcement.retract(false); drop(control); - // The prefix route moved past the instance the job read: its requesters wait on - // for the handler to prepare the job again under the new one. + // The claim moved past the instance the job read: its requesters wait on for + // the handler to prepare the job again under the new one. request.requeue = moved; drop(request); return Err(admitted.err().unwrap_or(Error::Unroutable)); @@ -3146,13 +3177,12 @@ impl Route { /// fail with [`Error::Unroutable`] meanwhile, while tracks already in flight carry /// on to their own end. Idempotent. pub fn withdraw(&self) { - let _control = self.state.control.lock(); - self.state.announcement.withdraw(); + self.state.withdraw() } /// Whether the route is visible. pub fn is_announced(&self) -> bool { - self.state.announcement.route().is_some() + self.state.is_announced() } /// Re-price the route: lower wins among routes covering the same prefix and anonymity. @@ -3163,7 +3193,7 @@ impl Route { /// [`Driver`] was dropped. pub fn set_cost(&self, cost: impl Into) -> Result<(), Error> { let cost = cost.into(); - self.change(|options| options.cost = cost) + self.state.change(|options| options.cost = cost) } /// Swap the credential the advertising request carries; see [`RouteOptions::with_auth`]. @@ -3172,33 +3202,96 @@ impl Route { /// Fails with [`Error::Closed`] once the route's broadcast closed or the origin's /// [`Driver`] was dropped. pub fn set_auth(&self, auth: Option) -> Result<(), Error> { - self.change(|options| options.auth = auth) + self.state.change(|options| options.auth = auth) } - fn change(&self, update: impl FnOnce(&mut RouteOptions)) -> Result<(), Error> { + /// The route metadata as advertised, or `None` while hidden. + #[cfg(test)] + pub(crate) fn route(&self) -> Option { + self.state.announcement.route() + } + + /// Announce with `info` as given, instance included when it names one, as a + /// session's update does: for tests that shape an exact route's metadata. + #[cfg(all(test, feature = "async"))] + pub(crate) fn announce_info(&self, mut info: RouteInfo) -> Result<(), Error> { let mut control = self.state.control.lock(); - update(&mut control.options); - if !self.state.announcement.is_live()? { - return Ok(()); + match &info.instance { + Some(instance) => { + control.instance = (instance.clone(), info.epoch); + control.held = false; + } + None => { + info.instance = Some(control.instance.0.clone()); + info.epoch = control.instance.1; + } } + control.options.cost = info.cost; + control.options.auth = info.auth.clone(); + self.state.announcement.update_if(info, None, |_| true).map(|_| ()) + } +} + +impl Claim { + /// The stream this claim serves, minted when it was created unless + /// [`RouteOptions::with_instance`] named one. + /// + /// Unnamed, it can change: the claim moves to a fresh instance each time an answer + /// holding its current one ends. See [`Producer::route_prefix`]. + pub fn instance(&self) -> Instance { + self.state.instance() + } + + /// Make the claim visible, or keep it so. Idempotent. Visible to local consumers + /// before it returns. + /// + /// Fails with [`Error::Closed`] once the origin's [`Driver`] was dropped. + pub fn announce(&self) -> Result<(), Error> { + let control = self.state.control.lock(); self.state .announcement .update_if(control.info(), None, |_| true) .map(|_| ()) } - /// The next path a consumer requests under this prefix route, as a [`Request`] to answer. + /// Hide the claim from everyone, local and remote alike, keeping its instance: + /// [`Self::announce`] brings it back. Requests beneath it fail with + /// [`Error::Unroutable`] meanwhile. Idempotent. + pub fn withdraw(&self) { + self.state.withdraw() + } + + /// Whether the claim is visible. + pub fn is_announced(&self) -> bool { + self.state.is_announced() + } + + /// Re-price the claim: lower wins among routes covering the same prefix and anonymity. + /// A visible claim changes in place, as an update to its readers; a hidden one + /// keeps the price for when it next announces. + /// + /// Fails with [`Error::Closed`] once the origin's [`Driver`] was dropped. + pub fn set_cost(&self, cost: impl Into) -> Result<(), Error> { + let cost = cost.into(); + self.state.change(|options| options.cost = cost) + } + + /// Swap the credential the advertising request carries; see [`RouteOptions::with_auth`]. + /// `None` advertises under the session's scope. + /// + /// Fails with [`Error::Closed`] once the origin's [`Driver`] was dropped. + pub fn set_auth(&self, auth: Option) -> Result<(), Error> { + self.state.change(|options| options.auth = auth) + } + + /// The next path a consumer requests beneath this claim, as a [`Request`] to answer. /// /// Takes `&self` so a handler can answer from one task while another re-prices the - /// route; concurrent callers each receive distinct requests. Returns `None` once the - /// route is retracted or the origin's [`Driver`] was dropped, so handler loops end, - /// and at once on an exact route, which yields no requests. + /// claim; concurrent callers each receive distinct requests. Returns `None` once the + /// claim is retracted or the origin's [`Driver`] was dropped, so handler loops end. #[cfg_attr(feature = "async", kio::wrapper)] pub fn poll_requested(&self, waiter: &kio::Waiter) -> Poll> { - let Some(server) = &self.state.server else { - return Poll::Ready(None); - }; - let mut state = ready!(server.poll(waiter, |state| { + let mut state = ready!(self.server.poll(waiter, |state| { if state.closed || state.requests.has_queued() { Poll::Ready(()) } else { @@ -3221,47 +3314,27 @@ impl Route { Poll::Ready(Some(Request { path, producer, - home: server.clone(), - publisher: self.state.publisher.clone(), + home: self.server.clone(), + publisher: self.publisher.clone(), requeue: false, })) } - /// The route metadata as advertised, or `None` while hidden. + /// The claim metadata as advertised, or `None` while hidden. #[cfg(test)] pub(crate) fn route(&self) -> Option { self.state.announcement.route() } - /// Announce with `info` as given, instance included when it names one, as a - /// session's update does: for tests that shape an exact route's metadata. - #[cfg(all(test, feature = "async"))] - pub(crate) fn announce_info(&self, mut info: RouteInfo) -> Result<(), Error> { - let mut control = self.state.control.lock(); - match &info.instance { - Some(instance) => { - control.instance = (instance.clone(), info.epoch); - control.held = false; - } - None => { - info.instance = Some(control.instance.0.clone()); - info.epoch = control.instance.1; - } - } - control.options.cost = info.cost; - control.options.auth = info.auth.clone(); - self.state.announcement.update_if(info, None, |_| true).map(|_| ()) - } - - /// The queue a prefix route's requests arrive on, for tests that inspect it. + /// The queue the claim's requests arrive on, for tests that inspect it. #[cfg(test)] fn server(&self) -> &kio::Shared { - self.state.server.as_ref().expect("a prefix route has a server") + &self.server } - /// Replace a forwarded route's metadata in place, taken as given. + /// Replace a forwarded claim's metadata in place, taken as given. /// - /// A route naming no [`RouteInfo::instance`], or the same one, re-prices: consumers + /// A claim naming no [`RouteInfo::instance`], or the same one, re-prices: consumers /// observe an update and every handle survives. Another instance is another stream: /// consumers see a restart, and a re-request never joins what was resolved under the /// old one. Requests still waiting on this handle carry over: the handler is asked @@ -3319,7 +3392,7 @@ pub(crate) struct AnnounceProducer { impl AnnounceProducer { /// Replace the route in place, instance included when it names one; see - /// [`Route::update`]. + /// [`Claim::update`]. /// /// The prefix is fixed at announce time and a [`RouteInfo`] cannot name one: to /// move an advertisement, drop this and announce again. Fails with @@ -5872,7 +5945,7 @@ struct OriginState { fronts: WeakCache, // Peers that withdrew a prefix while routes there still passed through them, - // which are stale. See [`Route::withdrawn`]. + // which are stale. See [`Claim::withdrawn`]. withdrawn: HashMap>, // Set when the origin's driver dropped: new requests fail with `Closed` @@ -6371,11 +6444,11 @@ struct PendingFront { refused: bool, } -impl Route { +impl Claim { #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] pub(super) fn request_validity(&self, path: &Path) -> Option { let shared = &self.state.announcement.shared; - let server = self.state.server.as_ref()?; + let server = &self.server; let mut table = shared.lock(); if table.closed { return None; @@ -6517,7 +6590,7 @@ impl ServeState { /// A pending request for a broadcast to be served on demand. /// -/// Yielded by [`Route::poll_requested`]. The requester is awaiting inside +/// Yielded by [`Claim::poll_requested`]. The requester is awaiting inside /// [`Consumer::request`]. Answer it one of three ways: [`serve`](Self::serve) a /// broadcast already held, under the prefix route's instance; create the path's own /// exact route with [`route`](Self::route), which continues the instance the prefix route @@ -8344,8 +8417,8 @@ impl From for Config { #[cfg(all(test, feature = "async"))] pub(crate) struct TestSelection { origin: Producer, - route: Option, - replacement: Option, + route: Option, + replacement: Option, } #[cfg(all(test, feature = "async"))] @@ -8355,7 +8428,7 @@ impl TestSelection { pub(crate) fn new() -> Self { let origin = Hop::new(1).unwrap().produce(); let route = origin - .forward("room", RouteInfo::default().with_via(Hop::new(Self::PEER).unwrap())) + .forward("room", RouteInfo::new().with_via(Hop::new(Self::PEER).unwrap())) .unwrap(); Self { origin, @@ -8376,7 +8449,7 @@ impl TestSelection { /// Another instance of the peer takes the path. pub(crate) fn replace(&mut self) { - let route = RouteInfo::default().with_via(Hop::new(Self::PEER).unwrap()); + let route = RouteInfo::new().with_via(Hop::new(Self::PEER).unwrap()); self.replacement = Some(self.origin.forward("room/a", route).unwrap()); } } @@ -8440,7 +8513,7 @@ mod tests { let waiter = kio::Waiter::noop(); let (producer, mut driver) = Producer::new(Config::from(origin(1))); let server = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let broadcast = broadcast::Info::new().produce(); let track = broadcast.reserve_track("video").unwrap(); @@ -8557,7 +8630,7 @@ mod tests { /// Yield to the driver until the server's front watcher delivers a request. #[cfg(feature = "async")] - async fn queued(server: &Route) -> Request { + async fn queued(server: &Claim) -> Request { let mut request = None; settle(|| match server.poll_requested(&kio::Waiter::noop()) { Poll::Ready(Some(popped)) => { @@ -8592,7 +8665,7 @@ mod tests { let mut announced = consumer.routes(); announced.assert_next_wait(); - let announcement = producer.announce("room/alice", RouteInfo::default()).unwrap(); + let announcement = producer.announce("room/alice", RouteInfo::new()).unwrap(); let route = announced.expect_next_active("room/alice").await; assert!(route.hops.is_empty()); assert_eq!(route.cost, Cost::default()); @@ -8611,7 +8684,7 @@ mod tests { let mut announced = producer.consume().routes(); assert!(!announced.is_synced(), "a snapshot in flight holds it"); - let _alice = producer.announce("room/alice", RouteInfo::default()).unwrap(); + let _alice = producer.announce("room/alice", RouteInfo::new()).unwrap(); drop(snapshot); assert!(!announced.is_synced(), "never before an earlier event is read"); @@ -8619,7 +8692,7 @@ mod tests { assert!(announced.is_synced()); // A later announcement is news, not part of what it synced with. - let _bob = producer.announce("room/bob", RouteInfo::default()).unwrap(); + let _bob = producer.announce("room/bob", RouteInfo::new()).unwrap(); assert!(announced.is_synced()); } @@ -8631,7 +8704,7 @@ mod tests { assert!(empty.is_synced(), "nothing to wait on"); empty.assert_next_wait(); - let _alice = producer.announce("room/alice", RouteInfo::default()).unwrap(); + let _alice = producer.announce("room/alice", RouteInfo::new()).unwrap(); let mut announced = producer.consume().routes(); assert!(!announced.is_synced(), "the replay is owed"); announced.assert_next_active("room/alice"); @@ -8641,9 +8714,9 @@ mod tests { #[test] fn initial_routes_precede_live_prefixes() { let producer = origin(1).produce(); - let _initial = producer.announce("z/initial", RouteInfo::default()).unwrap(); + let _initial = producer.announce("z/initial", RouteInfo::new()).unwrap(); let mut announced = producer.consume().routes(); - let _live = producer.announce("a/live", RouteInfo::default()).unwrap(); + let _live = producer.announce("a/live", RouteInfo::new()).unwrap(); announced.assert_next_active("z/initial"); assert!(announced.is_synced()); } @@ -8651,11 +8724,11 @@ mod tests { #[test] fn stalled_initial_replay_collapses_churn_without_a_backlog() { let producer = origin(1).produce(); - let initial = producer.announce("z/initial", RouteInfo::default()).unwrap(); + let initial = producer.announce("z/initial", RouteInfo::new()).unwrap(); let mut announced = producer.consume().routes(); for i in 0..1_000 { - let transient = producer.announce(format!("a/{i}"), RouteInfo::default()).unwrap(); - initial.update(RouteInfo::default().with_cost(i)).unwrap(); + let transient = producer.announce(format!("a/{i}"), RouteInfo::new()).unwrap(); + initial.update(RouteInfo::new().with_cost(i)).unwrap(); drop(transient); assert_eq!(announced.state.read().pending.len(), 1); } @@ -8671,7 +8744,7 @@ mod tests { let snapshot = producer.snapshot(""); let mut announced = producer.consume().routes(); - let alice = producer.announce("room/alice", RouteInfo::default()).unwrap(); + let alice = producer.announce("room/alice", RouteInfo::new()).unwrap(); drop(snapshot); assert!(!announced.is_synced()); drop(alice); @@ -8684,11 +8757,11 @@ mod tests { fn an_update_is_not_owed() { let producer = origin(1).produce(); let mut announced = producer.consume().routes(); - let alice = producer.announce("room/alice", RouteInfo::default()).unwrap(); + let alice = producer.announce("room/alice", RouteInfo::new()).unwrap(); announced.assert_next_active("room/alice"); let snapshot = producer.snapshot(""); - alice.update(RouteInfo::default().with_cost(5)).unwrap(); + alice.update(RouteInfo::new().with_cost(5)).unwrap(); drop(snapshot); assert!(announced.is_synced()); } @@ -8816,11 +8889,11 @@ mod tests { async fn hidden_routes_need_an_opt_in() { let producer = origin(1).produce(); let consumer = producer.consume(); - let _visible = producer.announce("room/alice", RouteInfo::default()).unwrap(); - let _stats = producer.announce(".stats/node", RouteInfo::default()).unwrap(); - let _nested = producer.announce("room/.internal", RouteInfo::default()).unwrap(); + let _visible = producer.announce("room/alice", RouteInfo::new()).unwrap(); + let _stats = producer.announce(".stats/node", RouteInfo::new()).unwrap(); + let _nested = producer.announce("room/.internal", RouteInfo::new()).unwrap(); // Only a leading dot hides: a suffix is part of the name. - let _suffix = producer.announce("room/catalog.pro", RouteInfo::default()).unwrap(); + let _suffix = producer.announce("room/catalog.pro", RouteInfo::new()).unwrap(); let mut announced = consumer.routes(); announced.expect_next_active("room/alice").await; @@ -8866,7 +8939,7 @@ mod tests { #[cfg(feature = "async")] async fn exclude_hides_and_refuses_the_subtree() { let producer = origin(1).produce(); - let _claim = producer.announce("p1", RouteInfo::default()).unwrap(); + let _claim = producer.announce("p1", RouteInfo::new()).unwrap(); let _cam = producer.route("p1/cam", RouteOptions::default()).unwrap(); let _private = producer.route("p1/.private/cam", RouteOptions::default()).unwrap(); let _overlay = producer.route("p1/.pro/cam", RouteOptions::default()).unwrap(); @@ -8945,7 +9018,7 @@ mod tests { #[cfg(feature = "async")] async fn mount_resolves_on_the_target_front() { let producer = origin(1).produce(); - let server = producer.forward(".svc", RouteInfo::default()).unwrap(); + let server = producer.forward(".svc", RouteInfo::new()).unwrap(); let project = mounted(&producer, "p1", &["**"]); let through = project.request(".svc/foo", None); @@ -8970,7 +9043,7 @@ mod tests { #[cfg(feature = "async")] async fn mount_presents_target_routes_under_the_mount() { let producer = origin(1).produce(); - let _claim = producer.announce(".svc", RouteInfo::default()).unwrap(); + let _claim = producer.announce(".svc", RouteInfo::new()).unwrap(); let foo = producer.route(".svc/p1/foo", RouteOptions::default()).unwrap(); let _other = producer.route(".svc/p2/bar", RouteOptions::default()).unwrap(); let _cam = producer.route("p1/cam", RouteOptions::default()).unwrap(); @@ -9132,11 +9205,11 @@ mod tests { Err(Error::Unauthorized) )); assert!(matches!( - project.forward(".svc", RouteInfo::default()), + project.forward(".svc", RouteInfo::new()), Err(Error::Unauthorized) )); assert!(matches!( - project.forward(".svc/foo", RouteInfo::default()), + project.forward(".svc/foo", RouteInfo::new()), Err(Error::Unauthorized) )); let _cam = project.route("cam", RouteOptions::default()).unwrap(); @@ -9274,7 +9347,7 @@ mod tests { let mut announced = consumer.routes(); let mut opted = consumer.clone().with_hidden(true).routes(); - let hidden = producer.announce(".stats/node", RouteInfo::default()).unwrap(); + let hidden = producer.announce(".stats/node", RouteInfo::new()).unwrap(); announced.assert_next_wait(); opted.expect_next_active(".stats/node").await; @@ -9286,7 +9359,7 @@ mod tests { #[kio::test] async fn a_replayed_route_retracted_before_delivery_cancels() { let producer = origin(1).produce(); - let alice = producer.announce("alice", RouteInfo::default()).unwrap(); + let alice = producer.announce("alice", RouteInfo::new()).unwrap(); let mut announced = producer.consume().routes(); drop(alice); announced.assert_next_wait(); @@ -9367,8 +9440,8 @@ mod tests { #[kio::test] async fn announce_replays_to_late_cursor() { let producer = origin(1).produce(); - let _a = producer.announce("room/alice", RouteInfo::default()).unwrap(); - let _b = producer.announce("room/bob", RouteInfo::default()).unwrap(); + let _a = producer.announce("room/alice", RouteInfo::new()).unwrap(); + let _b = producer.announce("room/bob", RouteInfo::new()).unwrap(); let mut announced = producer.consume().routes(); // Replay follows the table traversal order. @@ -9383,13 +9456,13 @@ mod tests { let scoped = producer.scope("", &scopes(&["room"])).unwrap(); // Prefix advertisements stay prefixes. The scope filters requests locally. - let _a = scoped.announce("", RouteInfo::default()).unwrap(); + let _a = scoped.announce("", RouteInfo::new()).unwrap(); let mut announced = producer.consume().routes(); announced.expect_next_active("").await; // Disjoint prefixes cannot be claimed at all. assert!(matches!( - scoped.announce("other", RouteInfo::default()), + scoped.announce("other", RouteInfo::new()), Err(Error::Unauthorized) )); } @@ -9397,7 +9470,7 @@ mod tests { #[kio::test] async fn cursor_keeps_an_overlapping_prefix_above_its_scope() { let producer = origin(1).produce(); - let _a = producer.announce("", RouteInfo::default()).unwrap(); + let _a = producer.announce("", RouteInfo::new()).unwrap(); let consumer = producer.consume().scope("", &scopes(&["room"])).unwrap(); let mut announced = consumer.clone().covering().routes(); @@ -9408,7 +9481,7 @@ mod tests { #[kio::test] async fn cursor_root_strips_prefix() { let producer = origin(1).produce(); - let _a = producer.announce("room/alice", RouteInfo::default()).unwrap(); + let _a = producer.announce("room/alice", RouteInfo::new()).unwrap(); let consumer = producer .consume() @@ -9424,14 +9497,14 @@ mod tests { let mut announced = producer.consume().routes(); let expensive = producer - .announce("room", RouteInfo::default().with_hops(hops(&[10])).with_cost(5)) + .announce("room", RouteInfo::new().with_hops(hops(&[10])).with_cost(5)) .unwrap(); let route = announced.expect_next_active("room").await; assert_eq!(route.cost, Cost::new(5)); // A cheaper route for the same prefix takes over in place. let cheap = producer - .announce("room", RouteInfo::default().with_hops(hops(&[20])).with_cost(1)) + .announce("room", RouteInfo::new().with_hops(hops(&[20])).with_cost(1)) .unwrap(); let route = announced.expect_next_active("room").await; assert_eq!(route.cost, Cost::new(1)); @@ -9468,12 +9541,12 @@ mod tests { // arrived in `order`. fn winners(order: impl Iterator) -> Vec { let producer = origin(1).produce(); - let _pool: Vec = order + let _pool: Vec = order .map(|id| { producer .forward( "pool", - RouteInfo::default() + RouteInfo::new() .with_instance(format!("worker-{id}").parse().unwrap(), 0) .with_hops(hops(&[id])) .with_cost(3), @@ -9523,7 +9596,7 @@ mod tests { for named in [None, Some(instance())] { let producer = origin(1).produce(); let mut announced = producer.consume().routes(); - let mut route = RouteInfo::default().with_hops(hops(&[10])); + let mut route = RouteInfo::new().with_hops(hops(&[10])); route.instance = named.clone(); let old = producer.announce("room", route.clone()).unwrap(); @@ -9547,10 +9620,10 @@ mod tests { async fn a_reprice_is_an_update() { let producer = origin(1).produce(); let mut announced = producer.consume().routes(); - let route = producer.forward("room", RouteInfo::default().with_cost(3)).unwrap(); + let route = producer.forward("room", RouteInfo::new().with_cost(3)).unwrap(); announced.expect_next_active("room").await; - route.update(RouteInfo::default().with_cost(5)).unwrap(); + route.update(RouteInfo::new().with_cost(5)).unwrap(); match announced.next().await.expect("no next") { RouteEvent::Update(update) => assert_eq!(update.route.cost, Cost::new(5)), other => panic!("should be an update: got {other:?}"), @@ -9568,11 +9641,11 @@ mod tests { let producer = origin(1).produce(); let mut announced = producer.consume().routes(); let route = producer - .forward("room", RouteInfo::default().with_auth(first.clone())) + .forward("room", RouteInfo::new().with_auth(first.clone())) .unwrap(); assert_eq!(announced.expect_next_active("room").await.auth, Some(first)); - route.update(RouteInfo::default().with_auth(second.clone())).unwrap(); + route.update(RouteInfo::new().with_auth(second.clone())).unwrap(); match announced.next().await.expect("no next") { RouteEvent::Update(update) => assert_eq!(update.route.auth, Some(second)), other => panic!("should be an update: got {other:?}"), @@ -9599,7 +9672,7 @@ mod tests { let old = peer .forward( "pool/job-0", - RouteInfo::default() + RouteInfo::new() .with_instance("a".parse().unwrap(), 0) .with_hops(hops(&[11])), ) @@ -9609,7 +9682,7 @@ mod tests { let new = peer .forward( "pool/job-0", - RouteInfo::default() + RouteInfo::new() .with_instance("b".parse().unwrap(), 0) .with_hops(hops(&[10])), ) @@ -9649,12 +9722,12 @@ mod tests { let consumer = producer.consume(); let mut announced = consumer.routes(); let _old = producer - .forward("pool/job-0", RouteInfo::default().with_hops(hops(&[old_hop]))) + .forward("pool/job-0", RouteInfo::new().with_hops(hops(&[old_hop]))) .unwrap(); announced.expect_next_active("pool/job-0").await; let new = producer - .forward("pool/job-0", RouteInfo::default().with_hops(hops(&[new_hop]))) + .forward("pool/job-0", RouteInfo::new().with_hops(hops(&[new_hop]))) .unwrap(); assert_eq!( announced.expect_next_restarted("pool/job-0").await.hops, @@ -9670,7 +9743,7 @@ mod tests { /// An origin delivering restarts at once, and a way to claim `prefix` with a /// producer scoped to `scope`, from `hop` at `cost`. #[cfg(feature = "async")] - fn scoped_pool() -> (Producer, impl Fn(&str, &str, u64, u64) -> Route) { + fn scoped_pool() -> (Producer, impl Fn(&str, &str, u64, u64) -> Claim) { let producer = Config { update_hold: Duration::ZERO, ..Config::from(origin(1)) @@ -9681,7 +9754,7 @@ mod tests { claims .scope("", &scopes(&[scope])) .unwrap() - .forward(prefix, RouteInfo::default().with_hops(hops(&[hop])).with_cost(cost)) + .forward(prefix, RouteInfo::new().with_hops(hops(&[hop])).with_cost(cost)) .unwrap() }; (producer, claim) @@ -9690,7 +9763,7 @@ mod tests { /// Request `path` from `consumer` and have `server` answer it: the answer, and /// the requester's broadcast. #[cfg(feature = "async")] - async fn hold(consumer: &Consumer, path: &str, server: &Route) -> (broadcast::Producer, broadcast::Consumer) { + async fn hold(consumer: &Consumer, path: &str, server: &Claim) -> (broadcast::Producer, broadcast::Consumer) { let pending = consumer.request(path, None); let answer = broadcast::Info::new().produce(); queued(server).await.serve(&answer); @@ -9719,7 +9792,7 @@ mod tests { assert_eq!(announced.expect_next_active("room").await.cost, Cost::new(5)); let _sticky = hold(&consumer, "room/job", &a).await; - b.update(RouteInfo::default().with_hops(hops(&[11])).with_cost(3)) + b.update(RouteInfo::new().with_hops(hops(&[11])).with_cost(3)) .unwrap(); assert_eq!(announced.expect_next_restarted("room").await.cost, Cost::new(3)); quiet(&mut announced).await; @@ -9729,7 +9802,7 @@ mod tests { async fn exclude_hides_routes_through_the_peer() { let producer = origin(1).produce(); let _a = producer - .announce("room", RouteInfo::default().with_hops(hops(&[7]))) + .announce("room", RouteInfo::new().with_hops(hops(&[7]))) .unwrap(); let mut hidden = producer.consume().excluding(origin(7)).routes(); @@ -9744,10 +9817,10 @@ mod tests { let producer = origin(1).produce(); let assigned = origin(777); let _echoed = producer - .announce("echoed", RouteInfo::default().with_hops(hops(&[0])).with_via(assigned)) + .announce("echoed", RouteInfo::new().with_hops(hops(&[0])).with_via(assigned)) .unwrap(); let _local = producer - .announce("local", RouteInfo::default().with_hops(hops(&[10]))) + .announce("local", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let mut hidden = producer.consume().excluding(assigned).routes(); @@ -9761,14 +9834,14 @@ mod tests { let mut announced = producer.consume().routes(); let _anonymous = producer - .announce("room", RouteInfo::default().with_hops(hops(&[0])).with_cost(1)) + .announce("room", RouteInfo::new().with_hops(hops(&[0])).with_cost(1)) .unwrap(); let route = announced.expect_next_active("room").await; assert!(route.is_anonymous()); assert_eq!(route.cost, Cost::new(1)); let _identified = producer - .announce("room", RouteInfo::default().with_hops(hops(&[10])).with_cost(5)) + .announce("room", RouteInfo::new().with_hops(hops(&[10])).with_cost(5)) .unwrap(); let route = announced.expect_next_active("room").await; assert!(!route.is_anonymous()); @@ -9781,13 +9854,13 @@ mod tests { let mut announced = producer.consume().routes(); let expensive = producer - .announce("room", RouteInfo::default().with_hops(hops(&[0])).with_cost(5)) + .announce("room", RouteInfo::new().with_hops(hops(&[0])).with_cost(5)) .unwrap(); let route = announced.expect_next_active("room").await; assert_eq!(route.cost, Cost::new(5)); let _cheap = producer - .announce("room", RouteInfo::default().with_hops(hops(&[0, 7])).with_cost(1)) + .announce("room", RouteInfo::new().with_hops(hops(&[0, 7])).with_cost(1)) .unwrap(); let route = announced.expect_next_active("room").await; assert!(route.is_anonymous()); @@ -9805,7 +9878,7 @@ mod tests { let _anonymous = producer .announce( "room", - RouteInfo::default() + RouteInfo::new() .with_hops(hops(&[0, 7])) .with_cost(1) .with_via(origin(7)), @@ -9814,7 +9887,7 @@ mod tests { announced.expect_next_active("room").await; let _identified = producer - .announce("room", RouteInfo::default().with_hops(hops(&[10, 20])).with_cost(5)) + .announce("room", RouteInfo::new().with_hops(hops(&[10, 20])).with_cost(5)) .unwrap(); let route = announced.expect_next_active("room").await; assert!(!route.is_anonymous()); @@ -9828,10 +9901,10 @@ mod tests { let consumer = producer.consume(); let anonymous = producer - .forward("room", RouteInfo::default().with_hops(hops(&[0])).with_cost(1)) + .forward("room", RouteInfo::new().with_hops(hops(&[0])).with_cost(1)) .unwrap(); let identified = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10])).with_cost(5)) + .forward("room", RouteInfo::new().with_hops(hops(&[10])).with_cost(5)) .unwrap(); let _pending = consumer.request("room/alice", None); @@ -9852,10 +9925,10 @@ mod tests { let demoted = producer .clone() .with_preference(Preference::new(-1)) - .forward("room", RouteInfo::default().with_hops(hops(&[10])).with_cost(1)) + .forward("room", RouteInfo::new().with_hops(hops(&[10])).with_cost(1)) .unwrap(); let unranked = producer - .forward("room", RouteInfo::default().with_hops(hops(&[11])).with_cost(5)) + .forward("room", RouteInfo::new().with_hops(hops(&[11])).with_cost(5)) .unwrap(); let _pending = consumer.request("room/alice", None); @@ -9872,10 +9945,10 @@ mod tests { let producer = origin(1).produce(); let mut announced = producer.consume().routes(); - let announcement = producer.announce("room", RouteInfo::default()).unwrap(); + let announcement = producer.announce("room", RouteInfo::new()).unwrap(); announced.expect_next_active("room").await; - announcement.update(RouteInfo::default().with_cost(9)).unwrap(); + announcement.update(RouteInfo::new().with_cost(9)).unwrap(); let route = announced.expect_next_active("room").await; assert_eq!(route.cost, Cost::new(9)); } @@ -9887,7 +9960,7 @@ mod tests { let mut announced = producer.consume().routes(); let dynamic = producer - .forward("room", RouteInfo::default().with_instance(instance(), 0).with_cost(5)) + .forward("room", RouteInfo::new().with_instance(instance(), 0).with_cost(5)) .unwrap(); announced.expect_next_active("room").await; dynamic.update(dynamic.route().unwrap().with_cost(1)).unwrap(); @@ -9912,13 +9985,13 @@ mod tests { let producer = origin(1).produce(); let mut announced = producer.consume().routes(); - let announcement = producer.announce("room", RouteInfo::default()).unwrap(); + let announcement = producer.announce("room", RouteInfo::new()).unwrap(); announced.expect_next_active("room").await; // Reprice, then retract before the consumer observes the reprice: the // pending metadata update must not cancel the retraction the delivered // announce still owes. - announcement.update(RouteInfo::default().with_cost(9)).unwrap(); + announcement.update(RouteInfo::new().with_cost(9)).unwrap(); drop(announcement); announced.expect_next_ended("room").await; announced.assert_next_wait(); @@ -9929,9 +10002,9 @@ mod tests { let producer = origin(1).produce(); // Broad and cheap; narrow and expensive. Both present relative to a cursor // rooted below them, and the narrow one is what a request there resolves. - let _broad = producer.announce("room", RouteInfo::default().with_cost(1)).unwrap(); + let _broad = producer.announce("room", RouteInfo::new().with_cost(1)).unwrap(); let _narrow = producer - .announce("room/alice", RouteInfo::default().with_cost(9)) + .announce("room/alice", RouteInfo::new().with_cost(9)) .unwrap(); let consumer = producer @@ -9948,8 +10021,8 @@ mod tests { #[cfg(feature = "async")] async fn capture_change_retracts_before_reannouncing_a_presented_prefix() { let producer = origin(1).produce(); - let _broad = producer.announce("room", RouteInfo::default()).unwrap(); - let exact = producer.announce("room/alice", RouteInfo::default()).unwrap(); + let _broad = producer.announce("room", RouteInfo::new()).unwrap(); + let exact = producer.announce("room/alice", RouteInfo::new()).unwrap(); let consumer = producer .consume() .scope("", &Patterns::from("room/*".parse::().unwrap())) @@ -10030,7 +10103,7 @@ mod tests { let server = producer .forward( "room/alice", - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(&[10])) .with_cost(1), @@ -10088,7 +10161,7 @@ mod tests { let server = producer .forward( "room/alice", - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(&[10])) .with_cost(1), @@ -10211,7 +10284,7 @@ mod tests { let server = producer .forward( "room/alice", - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(&[10])) .with_cost(1), @@ -10233,7 +10306,7 @@ mod tests { async fn a_front_through_a_covering_prefix_lists_nothing() { let producer = origin(1).produce(); let consumer = producer.consume(); - let server = producer.forward("room", RouteInfo::default()).unwrap(); + let server = producer.forward("room", RouteInfo::new()).unwrap(); let pending = consumer.request("room/alice", None); let upstream = broadcast::Info::new().produce(); let _video = upstream.create_track("video", None).unwrap(); @@ -10254,7 +10327,7 @@ mod tests { let consumer = producer.consume(); let _local = producer.route("room/alice", RouteOptions::default()).unwrap(); - let server = producer.forward("room/alice", RouteInfo::default()).unwrap(); + let server = producer.forward("room/alice", RouteInfo::new()).unwrap(); // Were the claim to win, the request would park on its handler forever. let resolved = kio::clock::timeout(Duration::from_secs(1), consumer.request("room/alice", None)) @@ -10308,7 +10381,7 @@ mod tests { let server = producer .forward( "room/alice", - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(&[10])) .with_cost(2), @@ -10386,7 +10459,7 @@ mod tests { producer .forward( "room/alice", - RouteInfo::default() + RouteInfo::new() .with_instance(crate::Instance::random(), 0) .with_hops(hops(&[10])), ) @@ -10427,11 +10500,11 @@ mod tests { /// A front resolved through a served route, as a relay's upstream session serves /// one: the upstream broadcast's track requests arrive on the returned handle. #[cfg(feature = "async")] - async fn served_front() -> (Route, broadcast::Producer, broadcast::Requests, broadcast::Consumer) { + async fn served_front() -> (Claim, broadcast::Producer, broadcast::Requests, broadcast::Consumer) { let producer = origin(1).produce(); let consumer = producer.consume(); let server = producer - .forward("room/alice", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room/alice", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let pending = consumer.request("room/alice", None); let upstream = broadcast::Info::new().produce(); @@ -10512,7 +10585,7 @@ mod tests { let producer = origin(1).produce(); // A prefix route, which resolves any path beneath it optimistically. let server = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let upstream = broadcast::Info::new().produce(); let source = upstream.create_track("video", crate::track::Info::timed()).unwrap(); @@ -10564,7 +10637,7 @@ mod tests { async fn a_hop_in_a_chain_gets_its_own_front() { let producer = origin(1).produce(); let _incumbent = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let fronts = || producer.shared.lock().fronts.len(); @@ -10575,7 +10648,7 @@ mod tests { // The same publisher, now also reached through the peer. let _echo = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10, 7]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10, 7]))) .unwrap(); let _filtered = peer.request("room/alice", None); assert_eq!(fronts(), 2, "the peer still shares the plain front"); @@ -10591,7 +10664,7 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); let server = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let upstream = broadcast::Info::new().produce(); let source = upstream.create_track("video", crate::track::Info::timed()).unwrap(); @@ -10652,7 +10725,7 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); let server = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let upstream = broadcast::Info::new().produce(); let source = upstream.create_track("video", None).unwrap(); @@ -10720,11 +10793,11 @@ mod tests { async fn a_peers_filtered_front_ends_once_unread() { let producer = origin(1).produce(); let server = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); // The same publisher, also reached through the peer, at a price the plain front skips. let _echo = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10, 7])).with_cost(100)) + .forward("room", RouteInfo::new().with_hops(hops(&[10, 7])).with_cost(100)) .unwrap(); let upstream = broadcast::Info::new().produce(); let source = upstream.create_track("video", crate::track::Info::timed()).unwrap(); @@ -10762,7 +10835,7 @@ mod tests { let incumbent = producer .forward( "room", - RouteInfo::default().with_instance(instance(), 0).with_hops(hops(&[10])), + RouteInfo::new().with_instance(instance(), 0).with_hops(hops(&[10])), ) .unwrap(); view.expect_next_active("room").await; @@ -10776,7 +10849,7 @@ mod tests { let echo = producer .forward( "room", - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(&[10, 7])), ) @@ -10810,7 +10883,7 @@ mod tests { let first_server = producer .forward( "room/alice", - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(&[10])) .with_cost(5), @@ -10868,7 +10941,7 @@ mod tests { let replacement_server = producer .forward( "room/alice", - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(&[10])) .with_cost(cost), @@ -11181,8 +11254,8 @@ mod tests { #[cfg(feature = "async")] async fn duplicate_routes_aggregate_until_the_last_leaves() { let producer = origin(1).produce(); - let first = producer.forward("live", RouteInfo::default().with_cost(3)).unwrap(); - let second = producer.forward("live", RouteInfo::default().with_cost(1)).unwrap(); + let first = producer.forward("live", RouteInfo::new().with_cost(3)).unwrap(); + let second = producer.forward("live", RouteInfo::new().with_cost(1)).unwrap(); let mut announced = producer.consume().routes(); let Some(Some(RouteEvent::Start(update))) = announced.next().now_or_never() else { @@ -11206,14 +11279,14 @@ mod tests { let producer = origin(1).produce(); let scoped = producer.scope("", &scopes(&["room"])).unwrap(); let _broad = scoped - .forward("", RouteInfo::default()) + .forward("", RouteInfo::new()) .expect("an overlapping prefix is accepted"); let _ok = scoped - .forward("room/alice", RouteInfo::default()) + .forward("room/alice", RouteInfo::new()) .expect("a contained prefix is accepted"); assert!(matches!( - scoped.forward("other", RouteInfo::default()), + scoped.forward("other", RouteInfo::new()), Err(Error::Unauthorized) )); } @@ -11224,7 +11297,7 @@ mod tests { let producer = origin(1).produce(); let scope = Patterns::from("*/chat".parse::().unwrap()); let scoped = producer.scope("", &scope).unwrap(); - let dynamic = scoped.forward("", RouteInfo::default()).unwrap(); + let dynamic = scoped.forward("", RouteInfo::new()).unwrap(); let mut matching = producer .consume() @@ -11262,9 +11335,9 @@ mod tests { .scope("", &Patterns::from(pattern.parse::().unwrap())) .unwrap() }; - let _chat = scoped("*/chat").forward("", RouteInfo::default().with_cost(1)).unwrap(); + let _chat = scoped("*/chat").forward("", RouteInfo::new().with_cost(1)).unwrap(); let _video = scoped("*/video") - .forward("", RouteInfo::default().with_cost(5)) + .forward("", RouteInfo::new().with_cost(5)) .unwrap(); let mut video = producer @@ -11297,7 +11370,7 @@ mod tests { let chat = producer .scope("", &scopes(&["room/live/chat"])) .unwrap() - .forward("room/live", RouteInfo::default().with_hops(hops(&[7])).with_cost(1)) + .forward("room/live", RouteInfo::new().with_hops(hops(&[7])).with_cost(1)) .unwrap(); assert_eq!(all.expect_next_active("room/live").await.cost, Cost::new(1)); assert_eq!(rooted.expect_next_active("").await.cost, Cost::new(1)); @@ -11307,14 +11380,14 @@ mod tests { let video_route = producer .scope("", &scopes(&["room/live/video"])) .unwrap() - .forward("room/live", RouteInfo::default().with_hops(hops(&[8])).with_cost(5)) + .forward("room/live", RouteInfo::new().with_hops(hops(&[8])).with_cost(5)) .unwrap(); all.assert_next_wait(); rooted.assert_next_wait(); assert_eq!(excluded.expect_next_active("room/live").await.cost, Cost::new(5)); assert_eq!(video.expect_next_active("room/live").await.cost, Cost::new(5)); - chat.update(RouteInfo::default().with_hops(hops(&[7])).with_cost(9)) + chat.update(RouteInfo::new().with_hops(hops(&[7])).with_cost(9)) .unwrap(); assert_eq!(all.expect_next_active("room/live").await.cost, Cost::new(5)); assert_eq!(rooted.expect_next_active("").await.cost, Cost::new(5)); @@ -11332,9 +11405,9 @@ mod tests { #[cfg(feature = "async")] async fn root_cursor_keeps_the_more_specific_covering_route() { let producer = origin(1).produce(); - let broad = producer.forward("room", RouteInfo::default().with_cost(1)).unwrap(); + let broad = producer.forward("room", RouteInfo::new().with_cost(1)).unwrap(); let narrow = producer - .forward("room/live", RouteInfo::default().with_cost(9)) + .forward("room/live", RouteInfo::new().with_cost(9)) .unwrap(); let mut announced = producer .consume() @@ -11344,9 +11417,9 @@ mod tests { .routes(); assert_eq!(announced.expect_next_active("").await.cost, Cost::new(9)); - broad.update(RouteInfo::default().with_cost(0)).unwrap(); + broad.update(RouteInfo::new().with_cost(0)).unwrap(); announced.assert_next_wait(); - narrow.update(RouteInfo::default().with_cost(8)).unwrap(); + narrow.update(RouteInfo::new().with_cost(8)).unwrap(); assert_eq!(announced.expect_next_active("").await.cost, Cost::new(8)); drop(narrow); assert_eq!(announced.expect_next_active("").await.cost, Cost::new(0)); @@ -11363,7 +11436,7 @@ mod tests { let mut announced = producer.consume().routes(); let dynamic = producer - .forward(&path, RouteInfo::default()) + .forward(&path, RouteInfo::new()) .expect("max depth is allowed"); announced.expect_next_active(&path).await; @@ -11376,7 +11449,7 @@ mod tests { async fn dynamic_exclusion_skips_routes_through_the_subscriber() { let producer = origin(1).produce(); let _server = producer - .forward("live", RouteInfo::default().with_hops(hops(&[7]))) + .forward("live", RouteInfo::new().with_hops(hops(&[7]))) .unwrap(); let mut excluded = producer.consume().excluding(origin(7)).routes(); @@ -11392,7 +11465,7 @@ mod tests { async fn announce_consumer_is_a_stream() { use futures::StreamExt; let producer = origin(1).produce(); - let server = producer.forward("live", RouteInfo::default()).unwrap(); + let server = producer.forward("live", RouteInfo::new()).unwrap(); let mut announced = producer.consume().routes(); let mut next = || StreamExt::next(&mut announced).now_or_never(); let Some(Some(RouteEvent::Start(update))) = next() else { @@ -11407,7 +11480,7 @@ mod tests { #[kio::test] async fn dynamic_retracts() { let producer = origin(1).produce(); - let server = producer.forward("live", RouteInfo::default()).unwrap(); + let server = producer.forward("live", RouteInfo::new()).unwrap(); let mut announced = producer.consume().routes(); announced.expect_next_active("live").await; @@ -11486,7 +11559,7 @@ mod tests { async fn served_requests_coalesce() { let producer = origin(1).produce(); let consumer = producer.consume(); - let server = producer.forward("room", RouteInfo::default()).unwrap(); + let server = producer.forward("room", RouteInfo::new()).unwrap(); let first = consumer.request("room/alice", None); let second = consumer.request("room/alice", None); @@ -11508,7 +11581,7 @@ mod tests { async fn retract_rejects_pending_requests() { let producer = origin(1).produce(); let consumer = producer.consume(); - let server = producer.forward("room", RouteInfo::default()).unwrap(); + let server = producer.forward("room", RouteInfo::new()).unwrap(); let pending = consumer.request("room/alice", None); drop(server); @@ -11534,9 +11607,9 @@ mod tests { // Three identical routes, oldest first: the newest identical route wins // requests, and swapping between them emits no announce update. - let standby_server = producer.forward("room", RouteInfo::default()).unwrap(); - let second_server = producer.forward("room", RouteInfo::default()).unwrap(); - let incumbent_server = producer.forward("room", RouteInfo::default()).unwrap(); + let standby_server = producer.forward("room", RouteInfo::new()).unwrap(); + let second_server = producer.forward("room", RouteInfo::new()).unwrap(); + let incumbent_server = producer.forward("room", RouteInfo::new()).unwrap(); let mut following = consumer.follow("room/alice", None).unwrap(); let mut resolving = Box::pin(following.available()); @@ -11564,7 +11637,7 @@ mod tests { async fn split_horizon_skips_routes_through_the_requester() { let producer = origin(1).produce(); let _server = producer - .forward("room", RouteInfo::default().with_hops(hops(&[7]))) + .forward("room", RouteInfo::new().with_hops(hops(&[7]))) .unwrap(); // The requester's own bytes must not be served back to it. @@ -11590,13 +11663,13 @@ mod tests { let mut announced = producer.consume().routes(); let _ingest = producer - .forward("client", RouteInfo::default().with_hops(hops(&[5])).with_via(origin(5))) + .forward("client", RouteInfo::new().with_hops(hops(&[5])).with_via(origin(5))) .unwrap(); let _gateway = producer.route("gateway", RouteOptions::default()).unwrap(); let _forwarded = peer .forward( "forwarded", - RouteInfo::default().with_hops(hops(&[5, 7])).with_via(origin(7)), + RouteInfo::new().with_hops(hops(&[5, 7])).with_via(origin(7)), ) .unwrap(); @@ -11609,7 +11682,7 @@ mod tests { // The mark survives narrowing the handle. let scoped = peer.scope("room", &Patterns::from(Pattern::all())).unwrap(); - let _nested = scoped.forward("x", RouteInfo::default().with_via(origin(8))).unwrap(); + let _nested = scoped.forward("x", RouteInfo::new().with_via(origin(8))).unwrap(); assert_eq!(announced.expect_next_active("room/x").await.source(), Source::Peer(8)); } @@ -11635,7 +11708,7 @@ mod tests { // One instance, so the winner moving between routes is an update, not a restart. let route = |chain: &[u64], via| { - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(chain)) .with_via(origin(via)) @@ -11670,7 +11743,7 @@ mod tests { let peer = producer.clone().with_link(Link::Peer); // One instance, so the winner moving between routes is an update, not a restart. let route = |chain: &[u64], via| { - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(chain)) .with_via(origin(via)) @@ -11719,7 +11792,7 @@ mod tests { // One instance, so the winner moving between routes is an update, not a restart. let route = |chain: &[u64], via| { - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(chain)) .with_via(origin(via)) @@ -11757,7 +11830,7 @@ mod tests { // Every path is to one publisher, so to one instance. let route = |chain: &[u64], via| { - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(chain)) .with_via(origin(via)) @@ -11818,12 +11891,12 @@ mod tests { let mut announced = producer.consume().routes(); // Publisher 9 ingests at relay 2; relay 3 relays 2's route. - let direct = || RouteInfo::default().with_hops(hops(&[9, 2])).with_via(origin(2)); + let direct = || RouteInfo::new().with_hops(hops(&[9, 2])).with_via(origin(2)); let first = peer.forward("room", direct()).unwrap(); let relayed = peer .forward( "room", - RouteInfo::default().with_hops(hops(&[9, 2, 3])).with_via(origin(3)), + RouteInfo::new().with_hops(hops(&[9, 2, 3])).with_via(origin(3)), ) .unwrap(); announced.expect_next_active("room").await; @@ -11854,7 +11927,7 @@ mod tests { let producer = origin(1).produce(); let peer = producer.clone().with_link(Link::Peer); let mut announced = producer.consume().routes(); - let route = RouteInfo::default() + let route = RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(&[9, 2])); let first = peer.forward("room", route.clone()).unwrap(); @@ -11881,10 +11954,10 @@ mod tests { let producer = origin(1).produce(); let peer = producer.clone().with_link(Link::Peer); let direct = peer - .forward("room", RouteInfo::default().with_hops(hops(&[9, 2]))) + .forward("room", RouteInfo::new().with_hops(hops(&[9, 2]))) .unwrap(); let _relayed = peer - .forward("room", RouteInfo::default().with_hops(hops(&[9, 2, 3]))) + .forward("room", RouteInfo::new().with_hops(hops(&[9, 2, 3]))) .unwrap(); let path = Path::from_static("room/video"); let id = producer @@ -11910,7 +11983,7 @@ mod tests { let peer = producer.clone().with_link(Link::Peer); let mut announced = producer.consume().routes(); - let route = RouteInfo::default() + let route = RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(&[7])) .with_via(origin(7)); @@ -11935,7 +12008,7 @@ mod tests { let mut local = producer.consume().local().routes(); let _forwarded = peer - .forward("remote", RouteInfo::default().with_hops(hops(&[7])).with_via(origin(7))) + .forward("remote", RouteInfo::new().with_hops(hops(&[7])).with_via(origin(7))) .unwrap(); local.assert_next_wait(); @@ -11943,12 +12016,12 @@ mod tests { // and retracts from the local view when the local route goes, even though // the peer's still covers it. let _shadow = peer - .forward("both", RouteInfo::default().with_hops(hops(&[7])).with_via(origin(7))) + .forward("both", RouteInfo::new().with_hops(hops(&[7])).with_via(origin(7))) .unwrap(); let ingest = producer .forward( "both", - RouteInfo::default() + RouteInfo::new() .with_hops(hops(&[5])) .with_via(origin(5)) .with_cost(9), @@ -11990,25 +12063,25 @@ mod tests { let mut everyone = producer.consume().routes(); let _core = core - .forward("core", RouteInfo::default().with_hops(hops(&[7])).with_via(origin(7))) + .forward("core", RouteInfo::new().with_hops(hops(&[7])).with_via(origin(7))) .unwrap(); assert_eq!(everyone.expect_next_active("core").await.source(), Source::Peer(7)); toward_core.assert_next_wait(); let _mesh = peer - .forward("mesh", RouteInfo::default().with_hops(hops(&[8])).with_via(origin(8))) + .forward("mesh", RouteInfo::new().with_hops(hops(&[8])).with_via(origin(8))) .unwrap(); assert_eq!(toward_core.expect_next_active("mesh").await.source(), Source::Peer(8)); // A path both an upstream and a mesh peer reach: the upstream route is // cheaper, yet the upstream view selects the mesh peer's. let _cheap = core - .forward("both", RouteInfo::default().with_hops(hops(&[7])).with_via(origin(7))) + .forward("both", RouteInfo::new().with_hops(hops(&[7])).with_via(origin(7))) .unwrap(); let mesh = peer .forward( "both", - RouteInfo::default() + RouteInfo::new() .with_hops(hops(&[8])) .with_via(origin(8)) .with_cost(9), @@ -12039,7 +12112,7 @@ mod tests { async fn handler_rejection_is_final() { let producer = origin(1).produce(); let consumer = producer.consume(); - let server = producer.forward("room", RouteInfo::default()).unwrap(); + let server = producer.forward("room", RouteInfo::new()).unwrap(); let pending = consumer.request("room/alice", None); let request = queued(&server).await; @@ -12257,7 +12330,7 @@ mod tests { let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap(); claim - .update(RouteInfo::default().with_instance(crate::Instance::random(), 0)) + .update(RouteInfo::new().with_instance(crate::Instance::random(), 0)) .unwrap(); announced.assert_next_restarted("room"); assert!(matches!(prepared.announce(), Err(Error::Unroutable))); @@ -12538,9 +12611,9 @@ mod tests { async fn refusal_never_falls_through() { let producer = origin(1).produce(); let consumer = producer.consume(); - let catch_all = producer.forward("", RouteInfo::default()).unwrap(); - let winner = producer.forward("room", RouteInfo::default()).unwrap(); - let sibling = producer.forward("room", RouteInfo::default().with_cost(2)).unwrap(); + let catch_all = producer.forward("", RouteInfo::new()).unwrap(); + let winner = producer.forward("room", RouteInfo::new()).unwrap(); + let sibling = producer.forward("room", RouteInfo::new().with_cost(2)).unwrap(); let mut pending = Box::pin(consumer.request("room/alice", None)); assert!((&mut pending).now_or_never().is_none()); @@ -12566,7 +12639,7 @@ mod tests { async fn superseded_refusal_does_not_end_the_request() { let producer = origin(1).produce(); let consumer = producer.consume(); - let stale = producer.forward("room", RouteInfo::default()).unwrap(); + let stale = producer.forward("room", RouteInfo::new()).unwrap(); let mut pending = Box::pin(consumer.request("room/alice", None)); assert!((&mut pending).now_or_never().is_none()); @@ -12593,13 +12666,13 @@ mod tests { async fn refusal_from_a_beaten_route_asks_the_new_winner() { let producer = origin(1).produce(); let consumer = producer.consume(); - let stale = producer.forward("room", RouteInfo::default()).unwrap(); + let stale = producer.forward("room", RouteInfo::new()).unwrap(); let mut pending = Box::pin(consumer.request("room/alice", None)); assert!((&mut pending).now_or_never().is_none()); let request = queued(&stale).await; - let winner = producer.forward("room/alice", RouteInfo::default()).unwrap(); + let winner = producer.forward("room/alice", RouteInfo::new()).unwrap(); request.reject(Error::NotFound); let source = broadcast::Info::new().produce(); queued(&winner).await.serve(&source); @@ -12619,7 +12692,7 @@ mod tests { async fn follow_reports_teardown_as_closed() { let (producer, driver) = Producer::new(Config::from(origin(1))); let consumer = producer.consume(); - let _server = producer.forward("room", RouteInfo::default()).unwrap(); + let _server = producer.forward("room", RouteInfo::new()).unwrap(); // Park on the covering route, past the loop's closed check. let mut following = consumer.follow("room/alice", None).unwrap(); @@ -12663,7 +12736,7 @@ mod tests { async fn late_track_on_a_served_front_replays() { let producer = origin(1).produce(); let consumer = producer.consume(); - let server = producer.forward("room", RouteInfo::default()).unwrap(); + let server = producer.forward("room", RouteInfo::new()).unwrap(); let source = broadcast::Info::new().produce(); for name in ["a", "b"] { @@ -12704,10 +12777,10 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); - let broad_server = producer.forward("", RouteInfo::default()).unwrap(); + let broad_server = producer.forward("", RouteInfo::new()).unwrap(); // A narrow advertise-only claim: requests under it must NOT route to the // broad server; they fall through to the (absent) fallback handler. - let _narrow = producer.announce(".dash", RouteInfo::default()).unwrap(); + let _narrow = producer.announce(".dash", RouteInfo::new()).unwrap(); let err = consumer .request(".dash/pid", None) @@ -12729,7 +12802,7 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); let mut announced = consumer.routes(); - let dynamic = producer.forward("", RouteInfo::default()).unwrap(); + let dynamic = producer.forward("", RouteInfo::new()).unwrap(); // The root claim is advertised like any other prefix. announced.expect_next_active("").await; @@ -12763,7 +12836,7 @@ mod tests { #[cfg(feature = "async")] async fn out_of_scope_request_never_reaches_the_dynamic_handler() { let producer = origin(1).produce(); - let dynamic = producer.forward("", RouteInfo::default()).unwrap(); + let dynamic = producer.forward("", RouteInfo::new()).unwrap(); let scoped = producer.consume().scope("", &scopes(&["tenant-a"])).unwrap(); // `tenant-a-other` shares a character prefix but not a segment, so this @@ -12801,7 +12874,7 @@ mod tests { assert!((&mut fut).now_or_never().is_none()); // A covering prefix resolves the wait. - let _a = producer.announce("room", RouteInfo::default().with_cost(3)).unwrap(); + let _a = producer.announce("room", RouteInfo::new().with_cost(3)).unwrap(); let route = started(fut.now_or_never().expect("covered")); assert_eq!(route.cost, Cost::new(3)); @@ -12817,12 +12890,12 @@ mod tests { let consumer = producer.consume(); // A deeper route does not cover the shorter path. - let _deep = producer.announce("room/alice/cam", RouteInfo::default()).unwrap(); + let _deep = producer.announce("room/alice/cam", RouteInfo::new()).unwrap(); let mut routes = consumer.path_routes("room/alice").unwrap(); let mut fut = routes.next().boxed(); assert!((&mut fut).now_or_never().is_none()); - let _exact = producer.announce("room/alice", RouteInfo::default()).unwrap(); + let _exact = producer.announce("room/alice", RouteInfo::new()).unwrap(); started(fut.now_or_never().expect("covered")); } @@ -12844,7 +12917,7 @@ mod tests { assert!((&mut fut).now_or_never().is_none()); // A covering root still resolves: the lookup must not require `path/**`. - let _a = producer.announce("", RouteInfo::default()).unwrap(); + let _a = producer.announce("", RouteInfo::new()).unwrap(); started(fut.now_or_never().expect("covered")); } @@ -12853,11 +12926,11 @@ mod tests { async fn teardown_ends_everything() { let (producer, driver) = Producer::new(Config::from(origin(1))); let consumer = producer.consume(); - let _announcement = producer.announce("room", RouteInfo::default()).unwrap(); + let _announcement = producer.announce("room", RouteInfo::new()).unwrap(); let mut announced = consumer.routes(); announced.expect_next_active("room").await; - let _server = producer.forward("served", RouteInfo::default()).unwrap(); + let _server = producer.forward("served", RouteInfo::new()).unwrap(); let pending = consumer.request("served/path", None); drop(driver); @@ -12869,7 +12942,7 @@ mod tests { // Pending requests reject; new work refuses. assert!(matches!(pending.now_or_never().expect("rejected"), Err(Error::Closed))); assert!(matches!( - producer.announce("x", RouteInfo::default()), + producer.announce("x", RouteInfo::new()), Err(Error::Closed) )); assert!(matches!( @@ -12896,7 +12969,7 @@ mod tests { let (producer, driver) = Producer::new(Config::from(origin(1))); let snapshot = producer.snapshot("room"); let mut announced = producer.consume().routes(); - let _alice = producer.announce("room/alice", RouteInfo::default()).unwrap(); + let _alice = producer.announce("room/alice", RouteInfo::new()).unwrap(); drop(driver); assert!(!announced.is_synced(), "the queue is still owed"); @@ -12908,7 +12981,7 @@ mod tests { #[test] fn internal_route_requests_are_closed_on_teardown() { let (producer, mut driver) = Producer::new(Config::from(origin(1))); - let server = producer.forward("room", RouteInfo::default()).unwrap(); + let server = producer.forward("room", RouteInfo::new()).unwrap(); let _pending = producer.consume().request("room/alice", None); driver.poll(Instant::now(), &kio::Waiter::noop()).unwrap(); let Poll::Ready(Some(request)) = server.poll_requested(&kio::Waiter::noop()) else { @@ -12936,7 +13009,7 @@ mod tests { for teardown in [false, true] { let (producer, mut driver) = Producer::new(Config::from(origin(1))); - let server = producer.forward("room", RouteInfo::default()).unwrap(); + let server = producer.forward("room", RouteInfo::new()).unwrap(); let _pending = producer.consume().request("room/alice", None); driver.poll(Instant::ZERO, &kio::Waiter::noop()).unwrap(); let channel = server @@ -12986,14 +13059,14 @@ mod tests { /// Announce a served route with `first` as its first hop, materialize /// "room/alice" through it with a one-group "before" track, and subscribe. #[cfg(feature = "async")] - async fn new(first: &[u64]) -> (Self, Route, broadcast::Producer) { + async fn new(first: &[u64]) -> (Self, Claim, broadcast::Producer) { let producer = origin(1).produce(); let consumer = producer.consume(); let server = producer .forward( "room", - RouteInfo::default().with_instance(instance(), 0).with_hops(hops(first)), + RouteInfo::new().with_instance(instance(), 0).with_hops(hops(first)), ) .unwrap(); @@ -13035,11 +13108,11 @@ mod tests { /// Stand up a second served route with `first` as its first hop and hand /// back its handle, ready to answer the front's re-request. - fn standby(&self, first: &[u64]) -> Route { + fn standby(&self, first: &[u64]) -> Claim { self.producer .forward( "room", - RouteInfo::default().with_instance(instance(), 0).with_hops(hops(first)), + RouteInfo::new().with_instance(instance(), 0).with_hops(hops(first)), ) .unwrap() } @@ -13050,7 +13123,7 @@ mod tests { /// rig's subscription resumes onto it: the successor group is delivered on /// the same subscription, at the group boundary. #[cfg(feature = "async")] - async fn assert_resumes(rig: &mut ResumeRig, server: &Route) { + async fn assert_resumes(rig: &mut ResumeRig, server: &Claim) { let request = queued(server).await; let replacement = broadcast::Info::new().produce(); let track = replacement.create_track("video", crate::track::Info::timed()).unwrap(); @@ -13087,7 +13160,7 @@ mod tests { .producer .forward( "room", - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 1) .with_hops(hops(&[11])) .with_cost(9), @@ -13113,7 +13186,7 @@ mod tests { producer .forward( "pool", - RouteInfo::default() + RouteInfo::new() .with_instance(name.parse().unwrap(), 0) .with_hops(hops(&[hop])), ) @@ -13151,7 +13224,7 @@ mod tests { producer .forward( "pool", - RouteInfo::default() + RouteInfo::new() .with_instance(name.parse().unwrap(), 0) .with_hops(hops(&[hop])), ) @@ -13208,7 +13281,7 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); let first = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10])).with_cost(5)) + .forward("room", RouteInfo::new().with_hops(hops(&[10])).with_cost(5)) .unwrap(); let pending = consumer.request("room/alice", None); let source = broadcast::Info::new().produce(); @@ -13219,7 +13292,7 @@ mod tests { deliver(&track, &mut subscription, b"first").await; let second = producer - .forward("room", RouteInfo::default().with_hops(hops(&[11])).with_cost(1)) + .forward("room", RouteInfo::new().with_hops(hops(&[11])).with_cost(1)) .unwrap(); deliver(&track, &mut subscription, b"pinned").await; @@ -13349,7 +13422,7 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); let old = producer - .forward("room", RouteInfo::default().with_instance(crate::Instance::random(), 0)) + .forward("room", RouteInfo::new().with_instance(crate::Instance::random(), 0)) .unwrap(); let pending = consumer.request("room/alice", None); let request = queued(&old).await; @@ -13385,7 +13458,7 @@ mod tests { let consumer = producer.consume(); let old = crate::Instance::random(); let dynamic = producer - .forward("room", RouteInfo::default().with_instance(old.clone(), 0)) + .forward("room", RouteInfo::new().with_instance(old.clone(), 0)) .unwrap(); let pending = consumer.request("room/alice", None); let pinned = consumer.request("room/alice", old); @@ -13445,7 +13518,7 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); let dynamic = producer - .forward("room", RouteInfo::default().with_instance(crate::Instance::random(), 0)) + .forward("room", RouteInfo::new().with_instance(crate::Instance::random(), 0)) .unwrap(); let pending = consumer.request("room/alice", None); queued(&dynamic).await.reject(Error::NotFound); @@ -13472,7 +13545,7 @@ mod tests { let consumer = producer.consume(); let old = crate::Instance::random(); let dynamic = producer - .forward("room", RouteInfo::default().with_instance(old.clone(), 0)) + .forward("room", RouteInfo::new().with_instance(old.clone(), 0)) .unwrap(); let pending = consumer.request("room/alice", None); let request = queued(&dynamic).await; @@ -13665,7 +13738,7 @@ mod tests { for first in [&[][..], &[0][..], &[10][..]] { let (mut rig, server, _source) = ResumeRig::new(first).await; let standby = rig.standby(&[10, 20]); - server.update(RouteInfo::default().with_hops(hops(&[11]))).unwrap(); + server.update(RouteInfo::new().with_hops(hops(&[11]))).unwrap(); let mut group = rig.incumbent_track.append_group().unwrap(); group.write_frame(crate::Timestamp::ZERO, b"after".as_ref()).unwrap(); @@ -13701,14 +13774,14 @@ mod tests { let incumbent = producer .forward( "room", - RouteInfo::default().with_instance(instance(), 0).with_hops(hops(&[10])), + RouteInfo::new().with_instance(instance(), 0).with_hops(hops(&[10])), ) .unwrap(); // The same publisher, reached through the requesting peer. let echo = producer .forward( "room", - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(&[10, 7])), ) @@ -13774,7 +13847,7 @@ mod tests { // Session A: an assigned anonymous hop serving the path. let server_a = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); // Session C: a third anonymous session, excluding the hop the server @@ -13830,7 +13903,7 @@ mod tests { // Session B attaches at the same path. Its front is served immediately. let server_b = producer - .forward("room", RouteInfo::default().with_hops(hops(&[20]))) + .forward("room", RouteInfo::new().with_hops(hops(&[20]))) .unwrap(); let pending = consumer.request("room/alice", None); let request = queued(&server_b).await; @@ -13872,7 +13945,7 @@ mod tests { // A metadata-only reprice of the only route: nothing re-requests and the // subscription keeps flowing from the same source. incumbent - .update(RouteInfo::default().with_hops(hops(&[10])).with_cost(9)) + .update(RouteInfo::new().with_hops(hops(&[10])).with_cost(9)) .unwrap(); let track = source.create_track("audio", crate::track::Info::timed()).unwrap(); @@ -13907,7 +13980,7 @@ mod tests { // the death. incumbent .update( - RouteInfo::default() + RouteInfo::new() .with_instance(instance(), 0) .with_hops(hops(&[10])) .with_cost(Cost::DRAIN), @@ -13956,7 +14029,7 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); let server = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); // The front selected the covering route and waits on its answer. @@ -13978,14 +14051,14 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); let covering = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let pending = consumer.request("room/alice", None); let _beaten = queued(&covering).await; // The exact path wins, and the front asks it in turn. let exact = producer - .forward("room/alice", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room/alice", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let request = queued(&exact).await; let again = consumer.request("room/alice", None); @@ -14059,7 +14132,7 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); let server = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let pending = consumer.request("room/alice", None); @@ -14107,7 +14180,7 @@ mod tests { async fn a_closed_source_is_not_requested_again_from_its_standing_route() { let producer = origin(1).produce(); let server = producer - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let pending = producer.consume().request("room/alice", None); let source = broadcast::Info::new().produce(); @@ -14199,7 +14272,7 @@ mod tests { async fn a_held_group_continues_after_its_track_goes_unread() { let producer = origin(1).produce(); let server = producer - .forward("live", RouteInfo::default().with_hops(hops(&[10]))) + .forward("live", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let pending = producer.consume().request("live", None); let source = broadcast::Info::new().produce(); @@ -14291,7 +14364,7 @@ mod tests { let mid = origin(2).produce(); let mid_server = mid - .forward("room", RouteInfo::default().with_hops(hops(&[10]))) + .forward("room", RouteInfo::new().with_hops(hops(&[10]))) .unwrap(); let mid_pending = mid.consume().request("room/alice", None); queued(&mid_server).await.serve(&leaf_front); @@ -14299,7 +14372,7 @@ mod tests { let edge = origin(3).produce(); let edge_server = edge - .forward("room", RouteInfo::default().with_hops(hops(&[20]))) + .forward("room", RouteInfo::new().with_hops(hops(&[20]))) .unwrap(); let edge_pending = edge.consume().request("room/alice", None); queued(&edge_server).await.serve(&mid_resolved); @@ -14426,12 +14499,12 @@ mod tests { /// A remote front serving "room/alice" with one read track, "video", whose first /// group was delivered. Returns the producer, the incumbent's track, and the reader. #[cfg(feature = "async")] - async fn remote_front() -> (Producer, Route, broadcast::Producer, track::Producer, track::Subscriber) { + async fn remote_front() -> (Producer, Claim, broadcast::Producer, track::Producer, track::Subscriber) { let producer = origin(1).produce(); let server = producer .forward( "room", - RouteInfo::default().with_instance(instance(), 0).with_hops(hops(&[10])), + RouteInfo::new().with_instance(instance(), 0).with_hops(hops(&[10])), ) .unwrap(); let pending = producer.consume().request("room/alice", None); @@ -14680,7 +14753,7 @@ mod tests { let server = producer .forward( "room", - RouteInfo::default().with_instance(instance(), 0).with_hops(hops(&[10])), + RouteInfo::new().with_instance(instance(), 0).with_hops(hops(&[10])), ) .unwrap(); let pending = producer.consume().request("room/alice", None); @@ -15030,7 +15103,7 @@ mod tests { #[kio::test] async fn multiple_scopes_present_one_broad_prefix() { let producer = origin(1).produce(); - let _a = producer.announce("", RouteInfo::default()).unwrap(); + let _a = producer.announce("", RouteInfo::new()).unwrap(); let consumer = producer .consume() @@ -15089,7 +15162,7 @@ mod tests { .scope("", &scopes(&["room/a", "other/deep/head"])) .unwrap() .routes(); - let route = producer.announce("room/a/b/c", RouteInfo::default()).unwrap(); + let route = producer.announce("room/a/b/c", RouteInfo::new()).unwrap(); { let table = producer.shared.lock(); assert!( @@ -15141,7 +15214,7 @@ mod tests { let (producer, driver) = Producer::new(Config::from(origin(1))); let run = kio::clock::sim::spawn(crate::time::run(driver)); let consumer = producer.consume(); - let server = producer.forward("room", RouteInfo::default()).unwrap(); + let server = producer.forward("room", RouteInfo::new()).unwrap(); drop(producer); let pending = consumer.request("room/alice", None); @@ -15255,7 +15328,7 @@ mod tests { async fn source_selection_leases_survive_reprices_but_never_revive_pending_work() { let producer = origin(1).produce(); let broad = producer - .forward("room", RouteInfo::default().with_via(origin(2))) + .forward("room", RouteInfo::new().with_via(origin(2))) .unwrap(); let selected = broad.request_validity(&Path::from_static("room/a")).unwrap(); let pending = selected.current(); @@ -15264,11 +15337,11 @@ mod tests { assert!(!pending.is_closed()); // Another peer's winning route cannot change what a request on peer 2 names. let other = producer - .forward("room/a", RouteInfo::default().with_via(origin(3))) + .forward("room/a", RouteInfo::new().with_via(origin(3))) .unwrap(); assert!(!pending.is_closed()); let replacement = producer - .forward("room/a", RouteInfo::default().with_via(origin(2))) + .forward("room/a", RouteInfo::new().with_via(origin(2))) .unwrap(); assert!(pending.is_closed()); assert!(selected.current().is_closed()); @@ -15290,7 +15363,7 @@ mod tests { let producer = origin(1).produce(); let path = Path::from_static("room/a"); let first = producer - .forward("room", RouteInfo::default().with_via(origin(2))) + .forward("room", RouteInfo::new().with_via(origin(2))) .unwrap(); let selected = first.request_validity(&path).unwrap(); let answering = selected.answering(); @@ -15298,14 +15371,14 @@ mod tests { let worse = producer .forward( "room", - RouteInfo::default().with_via(origin(2)).with_cost(Cost::from(7)), + RouteInfo::new().with_via(origin(2)).with_cost(Cost::from(7)), ) .unwrap(); assert!(!answering.is_closed()); drop(worse); let replacement = producer - .forward("room/a", RouteInfo::default().with_via(origin(2))) + .forward("room/a", RouteInfo::new().with_via(origin(2))) .unwrap(); assert!(answering.is_closed()); // Winning again opens a new lease, which a withdrawal leaves open. @@ -15318,7 +15391,7 @@ mod tests { // Announced again, the path has a new instance: a replacement. let _again = producer - .forward("room", RouteInfo::default().with_via(origin(2))) + .forward("room", RouteInfo::new().with_via(origin(2))) .unwrap(); assert!(answering.is_closed()); } @@ -15327,7 +15400,7 @@ mod tests { async fn source_selection_unregisters_without_retaining_the_source() { let producer = origin(1).produce(); let route = producer - .forward("room", RouteInfo::default().with_via(origin(2))) + .forward("room", RouteInfo::new().with_via(origin(2))) .unwrap(); let path = Path::from_static("room/a"); let selected = route.request_validity(&path).unwrap(); @@ -15349,12 +15422,12 @@ mod tests { let seen = watch.seen(); // A route beside the path or beneath it covers nothing at the path. - let _other = producer.announce("other", RouteInfo::default()).unwrap(); - let _below = producer.announce("room/a/b", RouteInfo::default()).unwrap(); + let _other = producer.announce("other", RouteInfo::new()).unwrap(); + let _below = producer.announce("room/a/b", RouteInfo::new()).unwrap(); assert!(watch.poll_changed(&waiter, seen).is_pending()); // A route above it does, and so does its retraction. - let above = producer.announce("room", RouteInfo::default()).unwrap(); + let above = producer.announce("room", RouteInfo::new()).unwrap(); assert!(watch.poll_changed(&waiter, seen).is_ready()); let seen = watch.seen(); drop(above); @@ -15383,7 +15456,7 @@ mod tests { async fn a_discarded_front_task_unregisters_its_watch() { let (producer, _driver) = Producer::new(Config::from(origin(1))); let consumer = producer.consume(); - let _served = producer.forward("room", RouteInfo::default()).unwrap(); + let _served = producer.forward("room", RouteInfo::new()).unwrap(); // A consumer outlives its producer by design, so the task set can refuse // submissions while the origin is still open. The front's task is then // dropped on the spot, taking its `Watch` with it: the request must not @@ -15398,7 +15471,7 @@ mod tests { for path in ["room/./cam", "room/../cam", ".", ".."] { assert!(producer.route(path, RouteOptions::hidden()).is_err(), "created {path}"); assert!( - producer.announce(path, RouteInfo::default()).is_err(), + producer.announce(path, RouteInfo::new()).is_err(), "announced {path}" ); } @@ -15423,7 +15496,7 @@ mod tests { Err(Error::InvalidPath(_)) )); assert!(matches!( - producer.announce("room/**", RouteInfo::default()), + producer.announce("room/**", RouteInfo::new()), Err(Error::InvalidPath(_)) )); } @@ -15518,7 +15591,7 @@ mod tests { audio.announce().unwrap(); announced.assert_next_wait(); - let broad = producer.announce("room", RouteInfo::default()).unwrap(); + let broad = producer.announce("room", RouteInfo::new()).unwrap(); let Some(RouteEvent::Start(update)) = announced.try_next() else { panic!("expected the overlapping broad route"); }; @@ -15539,11 +15612,11 @@ mod tests { .map(|p| p.parse::().unwrap()) .collect(); let consumer = producer.consume().scope("project", &patterns).unwrap(); - let cam = producer.announce("project/cam.hang", RouteInfo::default()).unwrap(); + let cam = producer.announce("project/cam.hang", RouteInfo::new()).unwrap(); let overlap = producer - .announce("project/room/mic.hang", RouteInfo::default()) + .announce("project/room/mic.hang", RouteInfo::new()) .unwrap(); - let chat = producer.announce("project/lobby.chat", RouteInfo::default()).unwrap(); + let chat = producer.announce("project/lobby.chat", RouteInfo::new()).unwrap(); let mut routing = consumer.clone().covering().routes(); routing.expect_next_active("cam.hang").await; routing.expect_next_active("lobby.chat").await; @@ -15554,10 +15627,10 @@ mod tests { selected.assert_next_wait(); let nested = producer - .announce("project/room/lobby.chat", RouteInfo::default()) + .announce("project/room/lobby.chat", RouteInfo::new()) .unwrap(); selected.expect_next_active("room/lobby.chat").await; - overlap.update(RouteInfo::default().with_cost(2)).unwrap(); + overlap.update(RouteInfo::new().with_cost(2)).unwrap(); drop(overlap); selected.assert_next_wait(); drop(nested); @@ -15573,7 +15646,7 @@ mod tests { .consume() .scope("room/alice", &Patterns::from(Pattern::all())) .unwrap(); - let broad = producer.announce("room", RouteInfo::default()).unwrap(); + let broad = producer.announce("room", RouteInfo::new()).unwrap(); let mut selected = consumer.routes(); selected.assert_next_wait(); @@ -15581,24 +15654,24 @@ mod tests { let exact = producer .announce( "room/alice", - RouteInfo::default().with_instance(first_instance.clone(), 0), + RouteInfo::new().with_instance(first_instance.clone(), 0), ) .unwrap(); assert!( matches!(selected.expect_next().await, RouteEvent::Start(a) if a.prefix.is_empty() && a.captures.is_some()) ); exact - .update(RouteInfo::default().with_instance(first_instance, 0).with_cost(2)) + .update(RouteInfo::new().with_instance(first_instance, 0).with_cost(2)) .unwrap(); assert!(matches!(selected.expect_next().await, RouteEvent::Update(a) if a.route.cost == Cost::new(2))); exact - .update(RouteInfo::default().with_instance(crate::Instance::random(), 0)) + .update(RouteInfo::new().with_instance(crate::Instance::random(), 0)) .unwrap(); assert!(matches!(selected.expect_next().await, RouteEvent::Restart(_))); drop(exact); selected.expect_next_ended("").await; selected.assert_next_wait(); - let _again = producer.announce("room/alice", RouteInfo::default()).unwrap(); + let _again = producer.announce("room/alice", RouteInfo::new()).unwrap(); assert!(matches!(selected.expect_next().await, RouteEvent::Start(_))); drop(broad); selected.assert_next_wait(); @@ -15611,13 +15684,13 @@ mod tests { #[kio::test] async fn announced_matches_mounted_names_and_keeps_exclusions() { let producer = origin(1).produce(); - let _broad = producer.announce(".svc", RouteInfo::default()).unwrap(); - let _overlap = producer.announce(".svc/p1/mic.hang", RouteInfo::default()).unwrap(); + let _broad = producer.announce(".svc", RouteInfo::new()).unwrap(); + let _overlap = producer.announce(".svc/p1/mic.hang", RouteInfo::new()).unwrap(); let _hidden = producer - .announce(".svc/p1/.private/lobby.chat", RouteInfo::default()) + .announce(".svc/p1/.private/lobby.chat", RouteInfo::new()) .unwrap(); let _excluded = producer - .announce(".svc/p1/private/lobby.chat", RouteInfo::default()) + .announce(".svc/p1/private/lobby.chat", RouteInfo::new()) .unwrap(); let project = mounted(&producer, "p1", &["**/*.chat"]) .with_hidden(true) @@ -15629,7 +15702,7 @@ mod tests { let mut inside = project.scope(".svc", &Patterns::from(Pattern::all())).unwrap().routes(); inside.expect_next_active(".private/lobby.chat").await; inside.assert_next_wait(); - let live = producer.announce(".svc/p1/lobby.chat", RouteInfo::default()).unwrap(); + let live = producer.announce(".svc/p1/lobby.chat", RouteInfo::new()).unwrap(); selected.expect_next_active(".svc/lobby.chat").await; inside.expect_next_active("lobby.chat").await; drop(live); @@ -15643,7 +15716,7 @@ mod tests { let registry = stats::Registry::new(stats::Config::new()); let producer = origin(1).produce(); let local = producer.route("project/cam.chat", RouteOptions::default()).unwrap(); - let overlap = producer.announce("project/room", RouteInfo::default()).unwrap(); + let overlap = producer.announce("project/room", RouteInfo::new()).unwrap(); let consumer = producer .consume() .scope("project", &Patterns::from("**/*.chat".parse::().unwrap())) @@ -15705,7 +15778,7 @@ mod tests { async fn local_broadcast_wins_announcement_ties() { let producer = origin(1).produce(); let remote = producer - .announce("room/alice", RouteInfo::default().with_cost(9)) + .announce("room/alice", RouteInfo::new().with_cost(9)) .unwrap(); let local = producer.route("room/alice", RouteOptions::hidden()).unwrap(); local.announce().unwrap(); diff --git a/rs/moq-net/src/model/resume_model.rs b/rs/moq-net/src/model/resume_model.rs index e9feba9c4c0..834f87966b9 100644 --- a/rs/moq-net/src/model/resume_model.rs +++ b/rs/moq-net/src/model/resume_model.rs @@ -448,7 +448,7 @@ impl Model { let mut hops = Hops::new(); hops.push(Hop::new(10 * (instance as u64 + 1) + slot as u64).unwrap()) .unwrap(); - let route = RouteInfo::default() + let route = RouteInfo::new() .with_instance(self::instance(instance), 0) .with_hops(hops) // The second instance's routes all undercut the first's. diff --git a/rs/moq-net/src/server.rs b/rs/moq-net/src/server.rs index a7b6d79a365..da847b12489 100644 --- a/rs/moq-net/src/server.rs +++ b/rs/moq-net/src/server.rs @@ -2318,7 +2318,7 @@ mod tests { let _echoed = origin .announce( "echoed-route", - crate::origin::RouteInfo::default() + crate::origin::RouteInfo::new() .with_hops(echoed_hops) .with_via(assigned), ) @@ -2327,7 +2327,7 @@ mod tests { let mut local_hops = crate::Hops::new(); local_hops.push(other).unwrap(); let _local = origin - .announce("local-route", crate::origin::RouteInfo::default().with_hops(local_hops)) + .announce("local-route", crate::origin::RouteInfo::new().with_hops(local_hops)) .unwrap(); let (session, driver) = request.ok().await.unwrap(); diff --git a/rs/moq-net/tests/integration/claim_continues.rs b/rs/moq-net/tests/integration/claim_continues.rs index d479dc5740d..95dfc568fe2 100644 --- a/rs/moq-net/tests/integration/claim_continues.rs +++ b/rs/moq-net/tests/integration/claim_continues.rs @@ -47,7 +47,7 @@ async fn settle() { /// A worker claiming `claim`, answering each request with an output whose `video` track /// carries the worker's name and how many outputs it made before. struct Worker { - claim: Rc, + claim: Rc, outputs: Rc>>, origin: origin::Producer, } diff --git a/rs/moq-net/tests/integration/drained_claim.rs b/rs/moq-net/tests/integration/drained_claim.rs index a7ddf9d7efa..e0ebe12e46f 100644 --- a/rs/moq-net/tests/integration/drained_claim.rs +++ b/rs/moq-net/tests/integration/drained_claim.rs @@ -46,7 +46,7 @@ async fn settle() { /// A worker claiming `pool`, answering each request with an output whose `video` /// track carries the worker's name. struct Worker { - _claim: Rc, + _claim: Rc, /// Each output with its track, which would end once its route drops. outputs: Rc>>, origin: origin::Producer, diff --git a/rs/moq-stats/Cargo.toml b/rs/moq-stats/Cargo.toml index 86e55e19e03..9c4c50bacf9 100644 --- a/rs/moq-stats/Cargo.toml +++ b/rs/moq-stats/Cargo.toml @@ -41,7 +41,7 @@ criterion = { package = "bench-harness", path = "../bench-harness" } futures = { workspace = true } # Compile the generated wrappers used by the tests and benches. moq-json = { path = "../moq-json", features = ["async"] } -moq-net = { path = "../moq-net", features = ["async"] } +moq-net = { path = "../moq-net", features = ["async", "fuzz"] } moq-stats = { path = ".", features = ["async"] } tokio = { workspace = true, features = ["macros", "rt", "test-util", "time"] } workspace-hack = { path = "../workspace-hack" } diff --git a/rs/moq-stats/src/aggregate.rs b/rs/moq-stats/src/aggregate.rs index 6fe28026925..5d7e2e8e588 100644 --- a/rs/moq-stats/src/aggregate.rs +++ b/rs/moq-stats/src/aggregate.rs @@ -2025,7 +2025,7 @@ mod tests { &moq_net::announce::Announce { prefix: path.clone(), captures: None, - route: Default::default(), + route: moq_net::fuzz::route_info([], 0, None), }, instance.clone(), true, @@ -2047,7 +2047,7 @@ mod tests { &moq_net::announce::Announce { prefix: path.clone(), captures: None, - route: Default::default(), + route: moq_net::fuzz::route_info([], 0, None), }, "b".parse().unwrap(), true, From 613642018de04499e34699c3b246aeb3ae3980ca Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 11:34:39 -0800 Subject: [PATCH 03/12] chore: fmt, retarget drill mutation at Claim Co-Authored-By: Claude Opus 5.5 --- rs/moq-c/src/origin.rs | 6 +- .../tests/integration/ietf_conformance.rs | 7 +- rs/moq-net/src/ietf/publisher.rs | 109 +++++------------- rs/moq-net/src/ietf/session.rs | 8 +- rs/moq-net/src/ietf/subscriber.rs | 5 +- rs/moq-net/src/lite/publisher.rs | 16 +-- rs/moq-net/src/model/origin.rs | 106 ++++------------- .../relay-withdraws-lost-publisher.patch | 4 +- 8 files changed, 66 insertions(+), 195 deletions(-) diff --git a/rs/moq-c/src/origin.rs b/rs/moq-c/src/origin.rs index 63fd6e534a2..bf65671d026 100644 --- a/rs/moq-c/src/origin.rs +++ b/rs/moq-c/src/origin.rs @@ -550,11 +550,7 @@ impl Origin { } /// Run `f` against the route, then check its origin is still healthy. - pub fn route_with( - &self, - route: Id, - f: impl FnOnce(Held<'_>) -> Result, - ) -> Result { + pub fn route_with(&self, route: Id, f: impl FnOnce(Held<'_>) -> Result) -> Result { let entry = self.route_entry(route)?; let result = f(entry.held()); entry.driver.check()?; diff --git a/rs/moq-net-tests/tests/integration/ietf_conformance.rs b/rs/moq-net-tests/tests/integration/ietf_conformance.rs index 8881c19c3b1..ebce58fedaf 100644 --- a/rs/moq-net-tests/tests/integration/ietf_conformance.rs +++ b/rs/moq-net-tests/tests/integration/ietf_conformance.rs @@ -23,7 +23,12 @@ async fn routing(version: &str, cluster: bool) { let relay = origin(2); let reader = origin(4); let prefix = Arc::new( - moq_net::fuzz::requests_route(&publisher, moq_net::Path::new(PREFIX).unwrap(), moq_net::fuzz::route_info([], 0, None)).unwrap(), + moq_net::fuzz::requests_route( + &publisher, + moq_net::Path::new(PREFIX).unwrap(), + moq_net::fuzz::route_info([], 0, None), + ) + .unwrap(), ); let broadcast = broadcast::Info::new().produce(); let track = broadcast.create_track("test", moq_net::track::Info::default()).unwrap(); diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 8180ff9b384..efb81341f9b 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -10878,10 +10878,7 @@ mod serve_tests { session.push(&update_with_tokens(&[TOKEN])); let request = taken_token(&mut running, &mut requests).await; - let other = h - ._origin - .announce("other", crate::origin::RouteInfo::new()) - .unwrap(); + let other = h._origin.announce("other", crate::origin::RouteInfo::new()).unwrap(); settle().await; assert!(futures::poll!(running.as_mut()).is_pending()); drop(other); @@ -11053,10 +11050,7 @@ mod serve_tests { let request = taken_token(&mut running, &mut requests).await; session.log.fail_writes(); - let _other = h - ._origin - .announce("other", crate::origin::RouteInfo::new()) - .unwrap(); + let _other = h._origin.announce("other", crate::origin::RouteInfo::new()).unwrap(); for _ in 0..10 { assert!( futures::poll!(running.as_mut()).is_pending(), @@ -18314,10 +18308,7 @@ mod tests { let mut clean_hops = crate::Hops::new(); clean_hops.push(clean_publisher).unwrap(); let clean = origin - .announce( - "route-flip-cam", - crate::origin::RouteInfo::new().with_hops(clean_hops), - ) + .announce("route-flip-cam", crate::origin::RouteInfo::new().with_hops(clean_hops)) .unwrap(); settle().await; assert!(futures::poll!(run.as_mut()).is_pending()); @@ -18372,9 +18363,7 @@ mod tests { const VERSION: Version = Version::Draft18; let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let _cam = origin - .announce("lonely-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let _cam = origin.announce("lonely-cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; // Every stream is answered with the same refusal, so a retry would show up as a @@ -18446,9 +18435,7 @@ mod tests { const VERSION: Version = Version::Draft18; let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let _local = origin - .announce("local-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let _local = origin.announce("local-cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; // The only stream is the PUBLISH_NAMESPACE request we open ourselves. @@ -18492,9 +18479,7 @@ mod tests { async fn publish_namespace_withdraws_by_reset() { for version in [Version::Draft18, Version::Draft20, Version::Draft22] { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let local = origin - .announce("local-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let local = origin.announce("local-cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; let session = @@ -18558,9 +18543,7 @@ mod tests { const VERSION: Version = Version::Draft18; let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let _local = origin - .announce("local-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let _local = origin.announce("local-cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; let ok = crate::lite::test_transport::Log::default(); @@ -18652,9 +18635,7 @@ mod tests { } = case; let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); let _cam = origin.announce("cam", crate::origin::RouteInfo::new()).unwrap(); - let _stats = origin - .announce(".stats/node", crate::origin::RouteInfo::new()) - .unwrap(); + let _stats = origin.announce(".stats/node", crate::origin::RouteInfo::new()).unwrap(); settle().await; // Stream 1 is the peer's SUBSCRIBE_NAMESPACE; stream 2, if opened at all, is our @@ -18800,9 +18781,7 @@ mod tests { async fn a_non_solicit_subscribe_namespace_carries_namespace() { for version in [Version::Draft18] { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let early = origin - .announce("early-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let early = origin.announce("early-cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![Vec::new()]); @@ -18846,9 +18825,7 @@ mod tests { "{version:?}: existing match", ); - let _late = origin - .announce("late-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let _late = origin.announce("late-cam", crate::origin::RouteInfo::new()).unwrap(); for _ in 0..100 { assert!(futures::poll!(run.as_mut()).is_pending()); if occurrences(&log, b"late-cam") >= 1 { @@ -18895,9 +18872,7 @@ mod tests { const VERSION: Version = Version::Draft18; let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let first = origin - .announce("first-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let first = origin.announce("first-cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; // The first advertisement has send capacity, and the peer answers it. @@ -18932,9 +18907,7 @@ mod tests { // Send capacity runs out before the second advertisement can send its header. set_gate(&gate, false); - let _second = origin - .announce("second-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let _second = origin.announce("second-cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; // Retiring the first needs no new stream, so the loop has to reach @@ -19063,9 +19036,7 @@ mod tests { let _standby = origin .announce( "solo-cam", - crate::origin::RouteInfo::new() - .with_instance(instance, 0) - .with_cost(0), + crate::origin::RouteInfo::new().with_instance(instance, 0).with_cost(0), ) .unwrap(); @@ -19170,9 +19141,7 @@ mod tests { let _warm = origin .announce( "cam", - crate::origin::RouteInfo::new() - .with_instance(instance, 0) - .with_cost(0), + crate::origin::RouteInfo::new().with_instance(instance, 0).with_cost(0), ) .unwrap(); @@ -19266,9 +19235,7 @@ mod tests { let _warm = origin .announce( "cam", - crate::origin::RouteInfo::new() - .with_instance(instance, 0) - .with_cost(0), + crate::origin::RouteInfo::new().with_instance(instance, 0).with_cost(0), ) .unwrap(); @@ -19464,8 +19431,7 @@ mod tests { "{version}: PUBLISH_NAMESPACE carries the auth" ); - cam.update(crate::origin::RouteInfo::new().with_auth(second)) - .unwrap(); + cam.update(crate::origin::RouteInfo::new().with_auth(second)).unwrap(); let expected = request_update( version, &ietf::PublishNamespaceUpdate { @@ -19543,8 +19509,7 @@ mod tests { poll_until(&mut run, &log, b"cam", 1).await; assert_eq!(occurrences(&log, b"late-secret"), 0, "named before it had an auth"); - cam.update(crate::origin::RouteInfo::new().with_auth(token)) - .unwrap(); + cam.update(crate::origin::RouteInfo::new().with_auth(token)).unwrap(); poll_until(&mut run, &log, b"cam", 2).await; assert_eq!(occurrences(&log, b"cam"), 2, "the request was not made again"); @@ -19562,16 +19527,10 @@ mod tests { let auth = crate::auth::Link::ietf(false); let present = |token: &'static [u8]| auth.present(bytes::Bytes::from_static(token), false).unwrap(); let a = origin - .announce( - "cam-a", - crate::origin::RouteInfo::new().with_auth(present(b"a-first")), - ) + .announce("cam-a", crate::origin::RouteInfo::new().with_auth(present(b"a-first"))) .unwrap(); let b = origin - .announce( - "cam-b", - crate::origin::RouteInfo::new().with_auth(present(b"b-first")), - ) + .announce("cam-b", crate::origin::RouteInfo::new().with_auth(present(b"b-first"))) .unwrap(); settle().await; @@ -19682,12 +19641,7 @@ mod tests { let origin = unheld_origin(); let mut cams: HashMap<&str, _> = ["a-cam", "b-cam"] .into_iter() - .map(|name| { - ( - name, - origin.announce(name, crate::origin::RouteInfo::new()).unwrap(), - ) - }) + .map(|name| (name, origin.announce(name, crate::origin::RouteInfo::new()).unwrap())) .collect(); settle().await; @@ -20008,9 +19962,7 @@ mod tests { let _warm = origin .announce( "cam", - crate::origin::RouteInfo::new() - .with_instance(instance, 0) - .with_cost(0), + crate::origin::RouteInfo::new().with_instance(instance, 0).with_cost(0), ) .unwrap(); @@ -20043,12 +19995,8 @@ mod tests { const VERSION: Version = Version::Draft18; let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let _first = origin - .announce("first-cam", crate::origin::RouteInfo::new()) - .unwrap(); - let _second = origin - .announce("second-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let _first = origin.announce("first-cam", crate::origin::RouteInfo::new()).unwrap(); + let _second = origin.announce("second-cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; // Every stream opens and then goes silent: an exhausted script parks rather than @@ -20153,8 +20101,7 @@ mod tests { assert!(futures::poll!(run.as_mut()).is_pending()); if matches!(stage, Stage::UpdateWrite) { let second = auth.present(bytes::Bytes::from_static(b"second"), false).unwrap(); - cam.update(crate::origin::RouteInfo::new().with_auth(second)) - .unwrap(); + cam.update(crate::origin::RouteInfo::new().with_auth(second)).unwrap(); settle().await; assert!(futures::poll!(run.as_mut()).is_pending()); assert!( @@ -20246,9 +20193,7 @@ mod tests { async fn an_advertisement_without_credit_is_retried_and_spends_no_id() { for version in [Version::Draft18] { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let _cam = origin - .announce("lonely-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let _cam = origin.announce("lonely-cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; let session = crate::lite::test_transport::ScriptedSession::new(publish_namespace_ok(version).await).without_credit(); @@ -20298,9 +20243,7 @@ mod tests { const VERSION: Version = Version::Draft18; let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let _cam = origin - .announce("lonely-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let _cam = origin.announce("lonely-cam", crate::origin::RouteInfo::new()).unwrap(); settle().await; // No send capacity from the start: an admitted header cannot finish. diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index 65cd449cc71..edea87f3409 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -2642,9 +2642,7 @@ mod tests { /// enough: the question is only whether the bytes went out unasked. async fn announce_occurrences(peer_declared: Option) -> usize { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let _cam = origin - .announce("solo-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let _cam = origin.announce("solo-cam", crate::origin::RouteInfo::new()).unwrap(); // An open gate: an unsolicited PUBLISH_NAMESPACE can reach the wire. let gate = kio::Producer::new(true); @@ -2749,9 +2747,7 @@ mod tests { fn auth_session(auth: bool) -> AuthSession { let origin = crate::origin::Config::new(std::num::NonZeroU64::new(1).unwrap()).produce(); - let cam = origin - .announce("solo-cam", crate::origin::RouteInfo::new()) - .unwrap(); + let cam = origin.announce("solo-cam", crate::origin::RouteInfo::new()).unwrap(); let gate = kio::Producer::new(true); let session = crate::lite::test_transport::SinkSession::gated_bi(gate.consume()); diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index a7516e9ce5b..ecfb3279d54 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -10720,10 +10720,7 @@ mod tests { // What we are publishing to the peer: a real upstream route. let upstream = crate::Hops::try_from(vec![crate::Hop::new(7).unwrap()]).unwrap(); let _source = origin - .announce( - "room/host", - crate::origin::RouteInfo::new().with_hops(upstream.clone()), - ) + .announce("room/host", crate::origin::RouteInfo::new().with_hops(upstream.clone())) .unwrap(); announced.expect_next_active("room/host").await; let _advertised = publishing.expect_next_active("room/host").await; diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 45a268df05f..bfedfa1f1ea 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -3633,9 +3633,7 @@ mod announce_test { fn a_lite07_prefix_past_the_root_announces_nothing() { let origin = Hop::new(1).unwrap().produce(); let root = "r".repeat(100); - let _route = origin - .announce(format!("{root}/x"), origin::RouteInfo::new()) - .unwrap(); + let _route = origin.announce(format!("{root}/x"), origin::RouteInfo::new()).unwrap(); let consumer = origin .consume() .scope(root.as_str(), &crate::Patterns::from(crate::Pattern::all())) @@ -3757,11 +3755,7 @@ mod announce_test { drop(removed); let mut churn = Vec::new(); for limit in 1..=4 { - churn.push( - origin - .announce(format!("a/{limit}"), origin::RouteInfo::new()) - .unwrap(), - ); + churn.push(origin.announce(format!("a/{limit}"), origin::RouteInfo::new()).unwrap()); *budget.write().ok().unwrap() = limit; assert!(run.poll(&mut stream, &consumer, &mut announced, &waiter).is_pending()); } @@ -4317,11 +4311,7 @@ mod announce_test { #[kio::test] async fn clamped_cost_change_is_quiet() { let mut h = harness().await; - let route = |cost| { - crate::origin::RouteInfo::new() - .with_hops(pub_hops()) - .with_cost(cost) - }; + let route = |cost| crate::origin::RouteInfo::new().with_hops(pub_hops()).with_cost(cost); h.announcement.update(route(u64::MAX)).unwrap(); kio::clock::sleep(crate::origin::Config::default().update_hold).await; settle().await; diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 8b1ab53ce54..f93b232458b 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -9792,8 +9792,7 @@ mod tests { assert_eq!(announced.expect_next_active("room").await.cost, Cost::new(5)); let _sticky = hold(&consumer, "room/job", &a).await; - b.update(RouteInfo::new().with_hops(hops(&[11])).with_cost(3)) - .unwrap(); + b.update(RouteInfo::new().with_hops(hops(&[11])).with_cost(3)).unwrap(); assert_eq!(announced.expect_next_restarted("room").await.cost, Cost::new(3)); quiet(&mut announced).await; } @@ -10003,9 +10002,7 @@ mod tests { // Broad and cheap; narrow and expensive. Both present relative to a cursor // rooted below them, and the narrow one is what a request there resolves. let _broad = producer.announce("room", RouteInfo::new().with_cost(1)).unwrap(); - let _narrow = producer - .announce("room/alice", RouteInfo::new().with_cost(9)) - .unwrap(); + let _narrow = producer.announce("room/alice", RouteInfo::new().with_cost(9)).unwrap(); let consumer = producer .consume() @@ -10849,9 +10846,7 @@ mod tests { let echo = producer .forward( "room", - RouteInfo::new() - .with_instance(instance(), 0) - .with_hops(hops(&[10, 7])), + RouteInfo::new().with_instance(instance(), 0).with_hops(hops(&[10, 7])), ) .unwrap(); drop(incumbent); @@ -11336,9 +11331,7 @@ mod tests { .unwrap() }; let _chat = scoped("*/chat").forward("", RouteInfo::new().with_cost(1)).unwrap(); - let _video = scoped("*/video") - .forward("", RouteInfo::new().with_cost(5)) - .unwrap(); + let _video = scoped("*/video").forward("", RouteInfo::new().with_cost(5)).unwrap(); let mut video = producer .consume() @@ -11406,9 +11399,7 @@ mod tests { async fn root_cursor_keeps_the_more_specific_covering_route() { let producer = origin(1).produce(); let broad = producer.forward("room", RouteInfo::new().with_cost(1)).unwrap(); - let narrow = producer - .forward("room/live", RouteInfo::new().with_cost(9)) - .unwrap(); + let narrow = producer.forward("room/live", RouteInfo::new().with_cost(9)).unwrap(); let mut announced = producer .consume() .scope("room/live/video", &Patterns::from(Pattern::all())) @@ -11435,9 +11426,7 @@ mod tests { .join("/"); let mut announced = producer.consume().routes(); - let dynamic = producer - .forward(&path, RouteInfo::new()) - .expect("max depth is allowed"); + let dynamic = producer.forward(&path, RouteInfo::new()).expect("max depth is allowed"); announced.expect_next_active(&path).await; let _pending = producer.consume().request(&path, None); @@ -11894,10 +11883,7 @@ mod tests { let direct = || RouteInfo::new().with_hops(hops(&[9, 2])).with_via(origin(2)); let first = peer.forward("room", direct()).unwrap(); let relayed = peer - .forward( - "room", - RouteInfo::new().with_hops(hops(&[9, 2, 3])).with_via(origin(3)), - ) + .forward("room", RouteInfo::new().with_hops(hops(&[9, 2, 3])).with_via(origin(3))) .unwrap(); announced.expect_next_active("room").await; announced.assert_next_wait(); @@ -11927,9 +11913,7 @@ mod tests { let producer = origin(1).produce(); let peer = producer.clone().with_link(Link::Peer); let mut announced = producer.consume().routes(); - let route = RouteInfo::new() - .with_instance(instance(), 0) - .with_hops(hops(&[9, 2])); + let route = RouteInfo::new().with_instance(instance(), 0).with_hops(hops(&[9, 2])); let first = peer.forward("room", route.clone()).unwrap(); let second = peer.forward("room", route.clone()).unwrap(); announced.expect_next_active("room").await; @@ -11953,9 +11937,7 @@ mod tests { async fn withdrawn_route_no_longer_covers_requests() { let producer = origin(1).produce(); let peer = producer.clone().with_link(Link::Peer); - let direct = peer - .forward("room", RouteInfo::new().with_hops(hops(&[9, 2]))) - .unwrap(); + let direct = peer.forward("room", RouteInfo::new().with_hops(hops(&[9, 2]))).unwrap(); let _relayed = peer .forward("room", RouteInfo::new().with_hops(hops(&[9, 2, 3]))) .unwrap(); @@ -12021,10 +12003,7 @@ mod tests { let ingest = producer .forward( "both", - RouteInfo::new() - .with_hops(hops(&[5])) - .with_via(origin(5)) - .with_cost(9), + RouteInfo::new().with_hops(hops(&[5])).with_via(origin(5)).with_cost(9), ) .unwrap(); assert_eq!(local.expect_next_active("both").await.source(), Source::Local); @@ -12081,10 +12060,7 @@ mod tests { let mesh = peer .forward( "both", - RouteInfo::new() - .with_hops(hops(&[8])) - .with_via(origin(8)) - .with_cost(9), + RouteInfo::new().with_hops(hops(&[8])).with_via(origin(8)).with_cost(9), ) .unwrap(); assert_eq!(toward_core.expect_next_active("both").await.source(), Source::Peer(8)); @@ -12941,10 +12917,7 @@ mod tests { // Pending requests reject; new work refuses. assert!(matches!(pending.now_or_never().expect("rejected"), Err(Error::Closed))); - assert!(matches!( - producer.announce("x", RouteInfo::new()), - Err(Error::Closed) - )); + assert!(matches!(producer.announce("x", RouteInfo::new()), Err(Error::Closed))); assert!(matches!( producer.route("x", RouteOptions::hidden()), Err(Error::Closed) @@ -13781,9 +13754,7 @@ mod tests { let echo = producer .forward( "room", - RouteInfo::new() - .with_instance(instance(), 0) - .with_hops(hops(&[10, 7])), + RouteInfo::new().with_instance(instance(), 0).with_hops(hops(&[10, 7])), ) .unwrap(); @@ -14363,17 +14334,13 @@ mod tests { let leaf_front = leaf_consumer.request("room/alice", None).await.expect("resolves"); let mid = origin(2).produce(); - let mid_server = mid - .forward("room", RouteInfo::new().with_hops(hops(&[10]))) - .unwrap(); + let mid_server = mid.forward("room", RouteInfo::new().with_hops(hops(&[10]))).unwrap(); let mid_pending = mid.consume().request("room/alice", None); queued(&mid_server).await.serve(&leaf_front); let mid_resolved = mid_pending.await.expect("mid resolves"); let edge = origin(3).produce(); - let edge_server = edge - .forward("room", RouteInfo::new().with_hops(hops(&[20]))) - .unwrap(); + let edge_server = edge.forward("room", RouteInfo::new().with_hops(hops(&[20]))).unwrap(); let edge_pending = edge.consume().request("room/alice", None); queued(&edge_server).await.serve(&mid_resolved); let edge_resolved = edge_pending.await.expect("edge resolves"); @@ -15327,9 +15294,7 @@ mod tests { #[kio::test] async fn source_selection_leases_survive_reprices_but_never_revive_pending_work() { let producer = origin(1).produce(); - let broad = producer - .forward("room", RouteInfo::new().with_via(origin(2))) - .unwrap(); + let broad = producer.forward("room", RouteInfo::new().with_via(origin(2))).unwrap(); let selected = broad.request_validity(&Path::from_static("room/a")).unwrap(); let pending = selected.current(); assert!(!pending.is_closed()); @@ -15362,17 +15327,12 @@ mod tests { async fn source_selection_answering_ends_only_on_a_replacement() { let producer = origin(1).produce(); let path = Path::from_static("room/a"); - let first = producer - .forward("room", RouteInfo::new().with_via(origin(2))) - .unwrap(); + let first = producer.forward("room", RouteInfo::new().with_via(origin(2))).unwrap(); let selected = first.request_validity(&path).unwrap(); let answering = selected.answering(); // A route that loses to the selected one replaces nothing. let worse = producer - .forward( - "room", - RouteInfo::new().with_via(origin(2)).with_cost(Cost::from(7)), - ) + .forward("room", RouteInfo::new().with_via(origin(2)).with_cost(Cost::from(7))) .unwrap(); assert!(!answering.is_closed()); drop(worse); @@ -15390,18 +15350,14 @@ mod tests { assert!(!answering.is_closed()); // Announced again, the path has a new instance: a replacement. - let _again = producer - .forward("room", RouteInfo::new().with_via(origin(2))) - .unwrap(); + let _again = producer.forward("room", RouteInfo::new().with_via(origin(2))).unwrap(); assert!(answering.is_closed()); } #[kio::test] async fn source_selection_unregisters_without_retaining_the_source() { let producer = origin(1).produce(); - let route = producer - .forward("room", RouteInfo::new().with_via(origin(2))) - .unwrap(); + let route = producer.forward("room", RouteInfo::new().with_via(origin(2))).unwrap(); let path = Path::from_static("room/a"); let selected = route.request_validity(&path).unwrap(); let lease = selected.current(); @@ -15470,10 +15426,7 @@ mod tests { let producer = origin(1).produce(); for path in ["room/./cam", "room/../cam", ".", ".."] { assert!(producer.route(path, RouteOptions::hidden()).is_err(), "created {path}"); - assert!( - producer.announce(path, RouteInfo::new()).is_err(), - "announced {path}" - ); + assert!(producer.announce(path, RouteInfo::new()).is_err(), "announced {path}"); } let scoped = producer .scope("room/..", &Patterns::from_iter([Pattern::all()])) @@ -15613,9 +15566,7 @@ mod tests { .collect(); let consumer = producer.consume().scope("project", &patterns).unwrap(); let cam = producer.announce("project/cam.hang", RouteInfo::new()).unwrap(); - let overlap = producer - .announce("project/room/mic.hang", RouteInfo::new()) - .unwrap(); + let overlap = producer.announce("project/room/mic.hang", RouteInfo::new()).unwrap(); let chat = producer.announce("project/lobby.chat", RouteInfo::new()).unwrap(); let mut routing = consumer.clone().covering().routes(); routing.expect_next_active("cam.hang").await; @@ -15626,9 +15577,7 @@ mod tests { selected.expect_next_active("lobby.chat").await; selected.assert_next_wait(); - let nested = producer - .announce("project/room/lobby.chat", RouteInfo::new()) - .unwrap(); + let nested = producer.announce("project/room/lobby.chat", RouteInfo::new()).unwrap(); selected.expect_next_active("room/lobby.chat").await; overlap.update(RouteInfo::new().with_cost(2)).unwrap(); drop(overlap); @@ -15652,10 +15601,7 @@ mod tests { let first_instance = crate::Instance::random(); let exact = producer - .announce( - "room/alice", - RouteInfo::new().with_instance(first_instance.clone(), 0), - ) + .announce("room/alice", RouteInfo::new().with_instance(first_instance.clone(), 0)) .unwrap(); assert!( matches!(selected.expect_next().await, RouteEvent::Start(a) if a.prefix.is_empty() && a.captures.is_some()) @@ -15777,9 +15723,7 @@ mod tests { #[kio::test] async fn local_broadcast_wins_announcement_ties() { let producer = origin(1).produce(); - let remote = producer - .announce("room/alice", RouteInfo::new().with_cost(9)) - .unwrap(); + let remote = producer.announce("room/alice", RouteInfo::new().with_cost(9)).unwrap(); let local = producer.route("room/alice", RouteOptions::hidden()).unwrap(); local.announce().unwrap(); diff --git a/test/drill/mutations/relay-withdraws-lost-publisher.patch b/test/drill/mutations/relay-withdraws-lost-publisher.patch index 66e1b0ba07d..972493a56ca 100644 --- a/test/drill/mutations/relay-withdraws-lost-publisher.patch +++ b/test/drill/mutations/relay-withdraws-lost-publisher.patch @@ -31,9 +31,9 @@ diff --git a/rs/moq-net/src/lite/subscriber.rs b/rs/moq-net/src/lite/subscriber. /// without recomputing the chain. route: crate::origin::RouteInfo, /// Dropping it retracts the route and rejects its queued requests. -- dynamic: crate::origin::Route, +- dynamic: crate::origin::Claim, + // MUTATION: never dropped, so a route outlives the session that announced it. -+ dynamic: std::mem::ManuallyDrop, ++ dynamic: std::mem::ManuallyDrop, /// Closes as the route goes, which closes every source it minted. live: kio::Producer<()>, /// Whether the GOAWAY drain already re-priced this route. From 0103e4392f42d1defad05962a4121a2aa4b6e3a6 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 11:53:09 -0800 Subject: [PATCH 04/12] docs(moq-net): link Claim::poll_requested Co-Authored-By: Claude Opus 5.5 --- rs/moq-net/src/model/origin.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index f93b232458b..5ca478fbb31 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -2956,7 +2956,7 @@ pub struct Route { /// A prefix route on an origin: a claim that every path beneath a prefix can be served, /// answering each request as it arrives. /// -/// Created by [`Producer::route_prefix`]. Requests arrive on [`Self::requested`]; answer +/// Created by [`Producer::route_prefix`]. Requests arrive on [`Self::poll_requested`]; answer /// each by serving a broadcast already held or by creating the path's own [`Route`]. /// /// Clones share one claim. Dropping the last clone retracts it and refuses the requests From ded7d762b33289c9c01b8503e56467037e3d35b1 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 12:04:44 -0800 Subject: [PATCH 05/12] test(moq-cli): play test takes a Claim Co-Authored-By: Claude Opus 5.5 --- rs/moq-cli/src/play/media.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rs/moq-cli/src/play/media.rs b/rs/moq-cli/src/play/media.rs index 402a8bd2eca..760a2a4295a 100644 --- a/rs/moq-cli/src/play/media.rs +++ b/rs/moq-cli/src/play/media.rs @@ -1827,7 +1827,7 @@ mod tests { /// Answer the next request through `claim` with one `audio` rendition, under a fresh instance. async fn answer( - claim: &moq_net::origin::Route, + claim: &moq_net::origin::Claim, ) -> ( moq_net::origin::Route, catalog::Producer, From e6ba62584f950d37c7058ba614d15ee6e7da9990 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 12:12:44 -0800 Subject: [PATCH 06/12] quest(route-roles): record the split prototype and the pending pick Co-Authored-By: Claude Opus 5.5 --- quest/m2/route-roles.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/quest/m2/route-roles.md b/quest/m2/route-roles.md index a8c67fa0e86..ee27cc11666 100644 --- a/quest/m2/route-roles.md +++ b/quest/m2/route-roles.md @@ -37,3 +37,16 @@ put the comparison in the PR under `## Waiting` with a recommendation. After the maintainer picks, land the winner in JS, moq-ffi, moq-c, and the wrappers in the same PR. The route instance accessor's five spellings across bindings stay with [the exporter](/quest/m3/ffi-exporter.md). + +Status (2026-11-08, [moq-dev/moq#8292](https://github.com/moq-dev/moq/pull/8292)): +the split is built in Rust (moq-net returns a `Claim` from `route_prefix`; moq-ffi +and moq-c wrap both kinds in a private enum, so their API is unchanged so far). The single +prefix Route is sketched in the PR with caller diffs, not built: building it means +redesigning the origin table (exact routes become serving entries, sibling broadcasts +share one instance, job routes answer requests differently). + +## Waiting + +- Maintainer: pick split or single prefix on moq-dev/moq#8292, and whether the split + renames `route_prefix` to `claim`; recommended: split, renamed. Done when the PR has a + reply naming the shape. From 77ba97251d457f6f39d18ffcff65d3657fb7b916 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 21:36:12 -0800 Subject: [PATCH 07/12] feat(moq-ffi,moq-c,wrappers)!: claim splits from route in every binding `route_prefix` becomes `claim`, returning a Claim with requested(); Route keeps an infallible broadcast(). moq-ffi gains MoqClaim, the C ABI gains moq_origin_claim and moq_claim_*, and every wrapper follows. Co-Authored-By: Claude Opus 5.5 --- c/moq/test/probe.c | 6 +- cpp/moq/bench/main.cpp | 2 +- cpp/moq/test/probe.cpp | 4 +- cpp/obs/src/moq-output.cpp | 6 +- cpp/obs/test/moq-audio-encoder-test.cpp | 2 +- cpp/obs/test/moq-source-test.cpp | 2 +- dart/moq/lib/src/aliases.dart | 7 +- dart/moq/test/moq_test.dart | 5 +- dart/moq_ffi/lib/src/moq.dart | 328 ++++++++++++++---- dart/moq_ffi/lib/src/uniffi_runtime.dart | 2 + doc/concept/identity.md | 12 +- doc/lib/c/index.md | 11 +- doc/lib/cpp/index.md | 2 +- doc/lib/dart/index.md | 2 +- doc/lib/go/index.md | 4 +- doc/lib/layers.md | 2 +- doc/lib/rs/index.md | 4 +- doc/lib/rs/moq-net.md | 4 +- doc/lib/swift/index.md | 2 +- go/wrapper/README.md | 2 +- go/wrapper/example_test.go | 5 +- go/wrapper/moq_test.go | 28 +- go/wrapper/origin.go | 126 ++++--- go/wrapper/origin_internal_test.go | 9 +- go/wrapper/reconnect_test.go | 5 +- go/wrapper/runtime_bench_test.go | 5 +- .../kotlin/dev/moq/Aliases.kt | 17 +- .../jvmAndAndroidMain/kotlin/dev/moq/Flows.kt | 7 +- .../kotlin/dev/moq/SmokeTest.kt | 5 +- py/moq-rs/README.md | 15 +- py/moq-rs/docs/index.md | 1 + py/moq-rs/moq/__init__.py | 2 + py/moq-rs/moq/origin.py | 122 ++++--- py/moq-rs/tests/test_local.py | 16 +- rs/moq-c/README.md | 11 +- rs/moq-c/src/api.rs | 137 ++++++-- rs/moq-c/src/origin.rs | 174 +++++----- rs/moq-c/src/test.rs | 43 ++- rs/moq-cli/src/archive.rs | 2 +- rs/moq-cli/src/play/media.rs | 6 +- rs/moq-cli/src/report.rs | 2 +- rs/moq-cli/tests/integration/instances.rs | 2 +- rs/moq-ffi/src/bench.rs | 2 +- rs/moq-ffi/src/origin.rs | 273 ++++++++------- rs/moq-ffi/src/test.rs | 64 ++-- rs/moq-ffi/uniffi.toml | 1 + rs/moq-gst/src/source/imp.rs | 4 +- rs/moq-hls/src/export/rendition.rs | 2 +- rs/moq-hls/src/server/include_tests.rs | 6 +- rs/moq-mux/src/catalog/hang/consumer.rs | 2 +- rs/moq-mux/src/container/ts/export_test.rs | 4 +- rs/moq-mux/src/source.rs | 2 +- rs/moq-net-tests/tests/integration/restart.rs | 2 +- rs/moq-net-tests/tests/integration/serve.rs | 2 +- rs/moq-net/benches/origin.rs | 10 +- rs/moq-net/benches/retirement.rs | 4 +- rs/moq-net/benches/viewers.rs | 2 +- rs/moq-net/src/model/follow.rs | 14 +- rs/moq-net/src/model/origin.rs | 56 +-- .../integration/announce_covering_route.rs | 2 +- .../tests/integration/claim_continues.rs | 2 +- rs/moq-net/tests/integration/drained_claim.rs | 2 +- rs/moq-net/tests/integration/wide_hop.rs | 2 +- rs/moq-relay/src/cluster.rs | 4 +- rs/moq-room/src/room.rs | 2 +- rs/moq-webrtc/src/egress.rs | 2 +- swift/Sources/Moq/Origin.swift | 117 ++++--- swift/Tests/MoqTests/FfiBench.swift | 2 +- swift/Tests/MoqTests/SmokeTests.swift | 19 +- test/interop/clients/cpp/main.cpp | 4 +- test/interop/clients/go/main.go | 10 +- 71 files changed, 1056 insertions(+), 711 deletions(-) diff --git a/c/moq/test/probe.c b/c/moq/test/probe.c index 6ca21f6ee1f..3229ae984f7 100644 --- a/c/moq/test/probe.c +++ b/c/moq/test/probe.c @@ -293,8 +293,7 @@ int main(void) route_options.hidden = true; moq_route *route = NULL; ok(moq_origin_producer_route(origin, "probe", &route_options, &route), "route"); - moq_broadcast_producer *broadcast = NULL; - ok(moq_route_broadcast(route, &broadcast), "route broadcast"); + moq_broadcast_producer *broadcast = moq_route_broadcast(route); char *instance = moq_route_instance_id(route); CHECK(instance && instance[0] != '\0'); moq_string_free(instance); @@ -464,8 +463,7 @@ int main(void) late_options.hidden = true; moq_route *late_route = NULL; ok(moq_origin_producer_route(late_origin, "late", &late_options, &late_route), "late route"); - moq_broadcast_producer *late_broadcast = NULL; - ok(moq_route_broadcast(late_route, &late_broadcast), "late broadcast"); + moq_broadcast_producer *late_broadcast = moq_route_broadcast(late_route); moq_route_free(late_route); moq_track_producer *late_track = NULL; ok(moq_broadcast_producer_publish_track(late_broadcast, "data", &info, &late_track), "late track"); diff --git a/cpp/moq/bench/main.cpp b/cpp/moq/bench/main.cpp index dde2857309f..f129c126b64 100644 --- a/cpp/moq/bench/main.cpp +++ b/cpp/moq/bench/main.cpp @@ -101,7 +101,7 @@ void throughput(Case c, double budget, std::vector &results) moq::RouteOptions hidden; hidden.hidden = true; auto route = ok(origin->route("bench", hidden)); - auto broadcast = ok(route->broadcast()); + auto broadcast = route->broadcast(); std::vector> tracks; std::vector> consumers; moq::TrackInfo info; diff --git a/cpp/moq/test/probe.cpp b/cpp/moq/test/probe.cpp index e4f325ebade..6e8f626606f 100644 --- a/cpp/moq/test/probe.cpp +++ b/cpp/moq/test/probe.cpp @@ -300,7 +300,7 @@ int main() hidden.hidden = true; auto route = ok(origin->route("probe", hidden), "route"); CHECK(!route->instance_id().empty()); - auto broadcast = ok(route->broadcast(), "route broadcast"); + auto broadcast = route->broadcast(); moq::TrackInfo info; info.timescale = 1000000; auto track = ok(broadcast->publish_track("data", info), "publish_track"); @@ -308,7 +308,7 @@ int main() // A route whose broadcast closed can no longer announce. auto stale = ok(origin->route("stale", {}), "route"); - ok(ok(stale->broadcast(), "stale broadcast")->close(), "close stale broadcast"); + ok(stale->broadcast()->close(), "close stale broadcast"); auto reannounced = stale->announce(); CHECK(!reannounced); CHECK(std::holds_alternative(reannounced.error().get_variant())); diff --git a/cpp/obs/src/moq-output.cpp b/cpp/obs/src/moq-output.cpp index df628cfda75..0716c62b0dd 100644 --- a/cpp/obs/src/moq-output.cpp +++ b/cpp/obs/src/moq-output.cpp @@ -178,10 +178,6 @@ bool MoQOutput::Start() return false; } auto next_broadcast = (*next_route)->broadcast(); - if (!next_broadcast) { - LOG_ERROR("Failed to create broadcast: %s", next_broadcast.error().to_string().c_str()); - return false; - } // Advanced settings live on the service alongside the URL and path. With the group // switched off the client keeps the library defaults. @@ -235,7 +231,7 @@ bool MoQOutput::Start() std::lock_guard lock(media_mutex); origin = next_origin; route = *next_route; - broadcast = *next_broadcast; + broadcast = next_broadcast; } // NOTE: You could publish the same broadcasts to multiple sessions if you want (redundant ingest). diff --git a/cpp/obs/test/moq-audio-encoder-test.cpp b/cpp/obs/test/moq-audio-encoder-test.cpp index 682658d1ebb..a8109e9839f 100644 --- a/cpp/obs/test/moq-audio-encoder-test.cpp +++ b/cpp/obs/test/moq-audio-encoder-test.cpp @@ -204,7 +204,7 @@ void CheckSubscriberDecodes(const char *preset, size_t channels) auto origin = moq::OriginProducer::init(moq::OriginConfig{}); auto route = TestOk(origin->route("room", {}), "route"); - auto broadcast = TestOk(route->broadcast(), "route broadcast"); + auto broadcast = route->broadcast(); moq::AudioInit init{}; init.format = moq::AudioFormat::kOpus; diff --git a/cpp/obs/test/moq-source-test.cpp b/cpp/obs/test/moq-source-test.cpp index 2beac639daf..00680f21af5 100644 --- a/cpp/obs/test/moq-source-test.cpp +++ b/cpp/obs/test/moq-source-test.cpp @@ -588,7 +588,7 @@ class Publisher { moq::RouteOptions hidden; hidden.hidden = true; route = TestOk(relay.origin->route(path, hidden), "route"); - broadcast = TestOk(route->broadcast(), "route broadcast"); + broadcast = route->broadcast(); if (video) { moq::VideoInit init{}; init.format = moq::VideoFormat::kAvc3; diff --git a/dart/moq/lib/src/aliases.dart b/dart/moq/lib/src/aliases.dart index 89efa52ca2b..1b4c908796c 100644 --- a/dart/moq/lib/src/aliases.dart +++ b/dart/moq/lib/src/aliases.dart @@ -38,9 +38,14 @@ typedef CongestionControl = MoqCongestionControl; /// Certificate trust and the mTLS identity for `ConnectOptions.tls`. typedef ClientTls = MoqClientTls; -/// The publish side of an origin: create routes so subscribers can discover their broadcasts. +/// The publish side of an origin: create routes and claims so subscribers can discover their broadcasts. typedef OriginProducer = MoqOriginProducer; +/// A prefix route from `OriginProducer.claim`: a claim that every path beneath a prefix can be +/// served, yielding each request from `requested()`. Cancelling or disposing it retracts it and +/// rejects the requests still waiting. +typedef Claim = MoqClaim; + /// Config for creating an origin, such as its total cache budget. typedef OriginConfig = MoqOriginConfig; diff --git a/dart/moq/test/moq_test.dart b/dart/moq/test/moq_test.dart index 5623422e6a5..3560a543784 100644 --- a/dart/moq/test/moq_test.dart +++ b/dart/moq/test/moq_test.dart @@ -687,12 +687,12 @@ void main() { test('dynamic serves a request under a prefix', () async { final origin = MoqOriginProducer(config: MoqOriginConfig()); - final dynamic = origin.routePrefix(prefix: 'live', options: RouteOptions()); + final dynamic = origin.claim(prefix: 'live', options: RouteOptions()); final pending = origin.consume().request(path: 'live/cam'); final request = (await dynamic.requested().timeout(timeout))!; expect(request.path(), 'live/cam'); // A hidden job route answers nobody until it announces, under the instance its - // prefix route lends. + // claim lends. final served = request.route(options: RouteOptions(hidden: true)); expect(served.instanceId(), dynamic.instanceId()); served.announce(); @@ -700,7 +700,6 @@ void main() { // Closing the job's broadcast ends its route. served.broadcast().close(); expect(() => served.announce(), throwsA(isA())); - expect(() => dynamic.broadcast(), throwsA(isA())); dynamic.cancel(); await expectLater( dynamic.requested(), diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index d52e3abe28e..49db2a4e1b4 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -13331,6 +13331,128 @@ class FfiConverterMoqBroadcastRequest { } } +abstract class MoqClaimInterface { + void announce(); + void cancel(); + String instanceId(); + UniffiRustFuture requested(); + void setCost({required int cost}); + void withdraw(); +} + +final _MoqClaimFinalizer = Finalizer>((ptr) { + rustCall((status) => uniffi_moq_ffi_fn_free_moqclaim(ptr, status)); +}); + +class MoqClaim implements MoqClaimInterface { + late final Pointer _ptr; + bool _isDisposed = false; + MoqClaim._(this._ptr) { + _MoqClaimFinalizer.attach(this, _ptr, detach: this); + } + factory MoqClaim.lift(Pointer ptr) { + return MoqClaim._(ptr); + } + Pointer uniffiClonePointer() { + if (_isDisposed) { + throw StateError("Object has already been disposed"); + } + return rustCall((status) => uniffi_moq_ffi_fn_clone_moqclaim(_ptr, status)); + } + + void dispose() { + if (_isDisposed) { + return; + } + final status = calloc(); + _isDisposed = true; + _MoqClaimFinalizer.detach(this); + try { + uniffi_moq_ffi_fn_free_moqclaim(_ptr, status); + checkCallStatus(NullRustCallStatusErrorHandler(), status); + } finally { + calloc.free(status); + } + } + + void announce() { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqclaim_announce(uniffiClonePointer(), status); + }, moqExceptionErrorHandler); + } + + void cancel() { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqclaim_cancel(uniffiClonePointer(), status); + }, null); + } + + String instanceId() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqclaim_instance_id( + uniffiClonePointer(), + status, + ), + FfiConverterString.lift, + null, + ); + } + + UniffiRustFuture requested() { + return uniffiRustCallAsync( + () => uniffi_moq_ffi_fn_method_moqclaim_requested(uniffiClonePointer()), + ffi_moq_ffi_rust_future_poll_rust_buffer, + ffi_moq_ffi_rust_future_complete_rust_buffer, + ffi_moq_ffi_rust_future_cancel_rust_buffer, + ffi_moq_ffi_rust_future_free_rust_buffer, + FfiConverterOptionalMoqBroadcastRequest.lift, + moqExceptionErrorHandler, + ); + } + + void setCost({required int cost}) { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqclaim_set_cost( + uniffiClonePointer(), + FfiConverterUInt64.lower(cost), + status, + ); + }, moqExceptionErrorHandler); + } + + void withdraw() { + return rustCall((status) { + uniffi_moq_ffi_fn_method_moqclaim_withdraw(uniffiClonePointer(), status); + }, moqExceptionErrorHandler); + } +} + +class FfiConverterMoqClaim { + static MoqClaim lift(Pointer ptr) { + return MoqClaim.lift(ptr); + } + + static Pointer lower(MoqClaim value) { + return value.uniffiClonePointer(); + } + + static int allocationSize(MoqClaim value) { + return 8; + } + + static LiftRetVal read(Uint8List buf) { + final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); + final pointer = Pointer.fromAddress(handle); + return LiftRetVal(MoqClaim.lift(pointer), 8); + } + + static int write(MoqClaim value, Uint8List buf) { + final handle = lower(value); + buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); + return 8; + } +} + abstract class MoqFollowingInterface { UniffiRustFuture available(); void cancel(); @@ -13541,12 +13663,9 @@ class FfiConverterMoqOriginConsumer { } abstract class MoqOriginProducerInterface { + MoqClaim claim({required String prefix, required MoqRouteOptions options}); MoqOriginConsumer consume(); MoqRoute route({required String path, required MoqRouteOptions options}); - MoqRoute routePrefix({ - required String prefix, - required MoqRouteOptions options, - }); } final _MoqOriginProducerFinalizer = Finalizer>((ptr) { @@ -13596,38 +13715,35 @@ class MoqOriginProducer implements MoqOriginProducerInterface { } } - MoqOriginConsumer consume() { + MoqClaim claim({required String prefix, required MoqRouteOptions options}) { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqoriginproducer_consume( + (status) => uniffi_moq_ffi_fn_method_moqoriginproducer_claim( uniffiClonePointer(), + FfiConverterString.lower(prefix), + FfiConverterMoqRouteOptions.lower(options), status, ), - FfiConverterMoqOriginConsumer.lift, - null, + FfiConverterMoqClaim.lift, + moqExceptionErrorHandler, ); } - MoqRoute route({required String path, required MoqRouteOptions options}) { + MoqOriginConsumer consume() { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqoriginproducer_route( + (status) => uniffi_moq_ffi_fn_method_moqoriginproducer_consume( uniffiClonePointer(), - FfiConverterString.lower(path), - FfiConverterMoqRouteOptions.lower(options), status, ), - FfiConverterMoqRoute.lift, - moqExceptionErrorHandler, + FfiConverterMoqOriginConsumer.lift, + null, ); } - MoqRoute routePrefix({ - required String prefix, - required MoqRouteOptions options, - }) { + MoqRoute route({required String path, required MoqRouteOptions options}) { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqoriginproducer_route_prefix( + (status) => uniffi_moq_ffi_fn_method_moqoriginproducer_route( uniffiClonePointer(), - FfiConverterString.lower(prefix), + FfiConverterString.lower(path), FfiConverterMoqRouteOptions.lower(options), status, ), @@ -13668,7 +13784,6 @@ abstract class MoqRouteInterface { MoqBroadcastProducer broadcast(); void cancel(); String instanceId(); - UniffiRustFuture requested(); void setCost({required int cost}); void withdraw(); } @@ -13721,7 +13836,7 @@ class MoqRoute implements MoqRouteInterface { status, ), FfiConverterMoqBroadcastProducer.lift, - moqExceptionErrorHandler, + null, ); } @@ -13742,18 +13857,6 @@ class MoqRoute implements MoqRouteInterface { ); } - UniffiRustFuture requested() { - return uniffiRustCallAsync( - () => uniffi_moq_ffi_fn_method_moqroute_requested(uniffiClonePointer()), - ffi_moq_ffi_rust_future_poll_rust_buffer, - ffi_moq_ffi_rust_future_complete_rust_buffer, - ffi_moq_ffi_rust_future_cancel_rust_buffer, - ffi_moq_ffi_rust_future_free_rust_buffer, - FfiConverterOptionalMoqBroadcastRequest.lift, - moqExceptionErrorHandler, - ); - } - void setCost({required int cost}) { return rustCall((status) { uniffi_moq_ffi_fn_method_moqroute_set_cost( @@ -21378,6 +21481,68 @@ external void uniffi_moq_ffi_fn_method_moqbroadcastrequest_serve( Pointer uniffiStatus, ); +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_clone_moqclaim( + Pointer handle, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_free_moqclaim( + Pointer handle, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqclaim_announce( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqclaim_cancel( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external RustBuffer uniffi_moq_ffi_fn_method_moqclaim_instance_id( + Pointer ptr, + Pointer uniffiStatus, +); + +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqclaim_requested( + Pointer ptr, +); + +@Native, Uint64, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqclaim_set_cost( + Pointer ptr, + int cost, + Pointer uniffiStatus, +); + +@Native, Pointer)>( + assetId: _uniffiAssetId, +) +external void uniffi_moq_ffi_fn_method_moqclaim_withdraw( + Pointer ptr, + Pointer uniffiStatus, +); + @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -21480,14 +21645,6 @@ external Pointer uniffi_moq_ffi_fn_constructor_moqoriginproducer_new( Pointer uniffiStatus, ); -@Native Function(Pointer, Pointer)>( - assetId: _uniffiAssetId, -) -external Pointer uniffi_moq_ffi_fn_method_moqoriginproducer_consume( - Pointer ptr, - Pointer uniffiStatus, -); - @Native< Pointer Function( Pointer, @@ -21496,13 +21653,21 @@ external Pointer uniffi_moq_ffi_fn_method_moqoriginproducer_consume( Pointer, ) >(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqoriginproducer_route( +external Pointer uniffi_moq_ffi_fn_method_moqoriginproducer_claim( Pointer ptr, - RustBuffer path, + RustBuffer prefix, RustBuffer options, Pointer uniffiStatus, ); +@Native Function(Pointer, Pointer)>( + assetId: _uniffiAssetId, +) +external Pointer uniffi_moq_ffi_fn_method_moqoriginproducer_consume( + Pointer ptr, + Pointer uniffiStatus, +); + @Native< Pointer Function( Pointer, @@ -21511,9 +21676,9 @@ external Pointer uniffi_moq_ffi_fn_method_moqoriginproducer_route( Pointer, ) >(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqoriginproducer_route_prefix( +external Pointer uniffi_moq_ffi_fn_method_moqoriginproducer_route( Pointer ptr, - RustBuffer prefix, + RustBuffer path, RustBuffer options, Pointer uniffiStatus, ); @@ -21566,11 +21731,6 @@ external RustBuffer uniffi_moq_ffi_fn_method_moqroute_instance_id( Pointer uniffiStatus, ); -@Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqroute_requested( - Pointer ptr, -); - @Native, Uint64, Pointer)>( assetId: _uniffiAssetId, ) @@ -23629,6 +23789,24 @@ external int uniffi_moq_ffi_checksum_method_moqbroadcastrequest_route(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqbroadcastrequest_serve(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqclaim_announce(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqclaim_cancel(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqclaim_instance_id(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqclaim_requested(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqclaim_set_cost(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqclaim_withdraw(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqfollowing_available(); @@ -23645,13 +23823,13 @@ external int uniffi_moq_ffi_checksum_method_moqoriginconsumer_follow(); external int uniffi_moq_ffi_checksum_method_moqoriginconsumer_request(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqoriginproducer_consume(); +external int uniffi_moq_ffi_checksum_method_moqoriginproducer_claim(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqoriginproducer_route(); +external int uniffi_moq_ffi_checksum_method_moqoriginproducer_consume(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqoriginproducer_route_prefix(); +external int uniffi_moq_ffi_checksum_method_moqoriginproducer_route(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqroute_announce(); @@ -23665,9 +23843,6 @@ external int uniffi_moq_ffi_checksum_method_moqroute_cancel(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqroute_instance_id(); -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqroute_requested(); - @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqroute_set_cost(); @@ -24509,10 +24684,28 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqbroadcastrequest_reject() != 9727) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqbroadcastrequest_route() != 8265) { + if (uniffi_moq_ffi_checksum_method_moqbroadcastrequest_route() != 50556) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqbroadcastrequest_serve() != 51851) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqbroadcastrequest_serve() != 10832) { + if (uniffi_moq_ffi_checksum_method_moqclaim_announce() != 5128) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqclaim_cancel() != 17885) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqclaim_instance_id() != 12635) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqclaim_requested() != 13700) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqclaim_set_cost() != 15591) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqclaim_withdraw() != 10658) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqfollowing_available() != 26337) { @@ -24530,28 +24723,25 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqoriginconsumer_request() != 40910) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqoriginproducer_consume() != 52357) { + if (uniffi_moq_ffi_checksum_method_moqoriginproducer_claim() != 5226) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqoriginproducer_route() != 27041) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } - if (uniffi_moq_ffi_checksum_method_moqoriginproducer_route_prefix() != 3472) { + if (uniffi_moq_ffi_checksum_method_moqoriginproducer_consume() != 52357) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqroute_announce() != 46977) { + if (uniffi_moq_ffi_checksum_method_moqoriginproducer_route() != 27041) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqroute_broadcast() != 31588) { + if (uniffi_moq_ffi_checksum_method_moqroute_announce() != 30839) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqroute_cancel() != 41411) { + if (uniffi_moq_ffi_checksum_method_moqroute_broadcast() != 51116) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqroute_instance_id() != 57871) { + if (uniffi_moq_ffi_checksum_method_moqroute_cancel() != 12780) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqroute_requested() != 49558) { + if (uniffi_moq_ffi_checksum_method_moqroute_instance_id() != 37303) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqroute_set_cost() != 30911) { diff --git a/dart/moq_ffi/lib/src/uniffi_runtime.dart b/dart/moq_ffi/lib/src/uniffi_runtime.dart index 3b7dd9cf392..66b9e185973 100644 --- a/dart/moq_ffi/lib/src/uniffi_runtime.dart +++ b/dart/moq_ffi/lib/src/uniffi_runtime.dart @@ -8,6 +8,7 @@ import "dart:ffi"; import "dart:io" show Platform, File, Directory; import "dart:isolate"; import "dart:typed_data"; + import "package:ffi/ffi.dart"; class UniffiInternalError implements Exception { @@ -252,6 +253,7 @@ mixin FfiConverterPrimitive on FfiConverter { @override T lower(T value) => value; } + Uint8List createUint8ListFromInt(int value) { int length = value.bitLength ~/ 8 + 1; if (length != 4 && length != 8) { diff --git a/doc/concept/identity.md b/doc/concept/identity.md index 49df5551284..0d79ba5f360 100644 --- a/doc/concept/identity.md +++ b/doc/concept/identity.md @@ -32,7 +32,7 @@ no credential, and auth decides who may publish the path. keeps its instance on every route, which is what lets a subscription move between them. - **A stable instance is a promise.** A publisher may name its own instance - (`Route::with_instance(instance, epoch)` in Rust, `announce({ instance, epoch })` + (`Route::with_instance(instance, epoch)` in Rust, `origin.route(path, { instance, epoch })` in JavaScript) only if it continues the sequence space across restarts and announces a higher **epoch** each time, for example a counter persisted on disk. Breaking the promise splices unrelated groups into every reader's @@ -169,10 +169,10 @@ demand, whose instance changes each time its job restarts. A worker can advertise a prefix it serves on demand and answer with a broadcast it already holds. This announces no exact route: the answer belongs -to the prefix route's instance at that path. Every answer there must continue +to the claim's instance at that path. Every answer there must continue one sequence space with the same bytes. To serve different content at a path -already served, start a new prefix route. Its first subscription stays on -the prefix route without a restart. +already served, start a new claim. Its first subscription stays on +the claim without a restart. A job that may restart independently, such as a transcoder claiming `transcode`, instead creates each requested path's own exact route. A claim @@ -180,7 +180,7 @@ promises capability, not content. Each requested path is a separate job, announced at its exact path. ```rust -let claim = origin.route_prefix("transcode", RouteOptions::default())?; +let claim = origin.claim("transcode", RouteOptions::default())?; while let Some(request) = claim.requested().await { // Takes the claim's instance, so readers resolved through the claim continue. // Hidden until its tracks exist. @@ -200,7 +200,7 @@ earlier when its instance is first read, as a signer built from it does. Read first, the job announces under it or not at all: if another job under the claim ends in between, moving the claim to a fresh instance, `announce` fails with `Unroutable` and the request reaches the worker again. Ending a job's route withdraws its path, and the -prefix route keeps answering later requests. +claim keeps answering later requests. A lazy job's lifecycle, as a viewer of `transcode/alice` sees it through a relay: diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index 20ab8552bb4..f9175f39911 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -90,12 +90,13 @@ reports each instance as `MOQ_FOLLOW_EVENT_ONLINE` with its handle, `MOQ_FOLLOW_EVENT_OFFLINE` when the path goes offline, and one `MOQ_FOLLOW_EVENT_END`. Set `instance` only for a publisher that continues its group sequences across restarts, and raise `epoch` on each: readers stitch every route of one instance together, so restarting the sequences under an old instance splices unrelated groups into -their tracks. To serve paths on demand, `moq_origin_route_prefix()` delivers each request to +their tracks. To serve paths on demand, `moq_origin_claim()` returns a claim handle and delivers each request to answer with `moq_broadcast_request_serve()`, `moq_broadcast_request_route()`, or -`moq_broadcast_request_reject()`. Unless one is named, a prefix route moves to a fresh -instance each time a job holding its current one ends, and a job from -`moq_broadcast_request_route()` takes the prefix route's, so on moq-lite 07 a reader resolved through the -prefix route does not restart; older wires mint another instance for the job's route, restarting it. The string `moq_route_instance()` writes is borrowed until the +`moq_broadcast_request_reject()`; `moq_claim_announce()`, `moq_claim_withdraw()`, +`moq_claim_set_cost()`, and `moq_claim_free()` control the claim. Unless one is named, a claim moves to a fresh +instance (`moq_claim_instance()`) each time a job holding its current one ends, and a job from +`moq_broadcast_request_route()` takes the claim's, so on moq-lite 07 a reader resolved through the +claim does not restart; older wires mint another instance for the job's route, restarting it. The string `moq_route_instance()` writes is borrowed until the next `moq_route_instance()` on that route or `moq_route_free()`. Raw video encoders take an exact numerator/denominator frame rate, such as 30000/1001. Publication track names stay separate from codec settings. For simulcast, give each rendition the next one down as the `lower` handle in its `moq_video_encode_options`: it stops encoding, advertised as disabled, while its bandwidth grant cannot fund it, and resumes once the grant recovers. A rung only disables while the session probes for bandwidth, which on native transports takes moq-quic with BBR3. For pre-encoded video, publish from the lowest rendition up and set `moq_video_init.lower` to the next lower media handle. Reserve each track with `moq_allocator_reserve_media`, then bind its reservation with `moq_rate_control_create` and call `moq_rate_control_update` on every frame. Apply changed targets to your encoder and `moq_publish_media_set_enabled`, resuming video on a keyframe; close the control and reservation separately when done. diff --git a/doc/lib/cpp/index.md b/doc/lib/cpp/index.md index f8fad94854b..301d524c8d1 100644 --- a/doc/lib/cpp/index.md +++ b/doc/lib/cpp/index.md @@ -140,7 +140,7 @@ A raw `moq::Frame` with `std::nullopt` is untimed. moq::RouteOptions options; options.hidden = true; // fill tracks before anyone finds it; hold the route to stay announced auto route = ok(session->publish()->route("my-stream.hang", options)); -auto broadcast = ok(route->broadcast()); +auto broadcast = route->broadcast(); auto audio = ok(moq::MediaTrackProducer::audio(broadcast, moq::MediaTarget::kNamed{}, {moq::AudioFormat::kOpus, opus_init})); ok(audio->write_frame({packet, moq::Timestamp{960, 48'000}})); // 20 ms diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index 9a122a3a087..bc52cdcd38f 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -149,7 +149,7 @@ one to one; the API reference has the names, and [Layers](/lib/layers) shows which module holds each. - **Names.** Types drop the `Moq` prefix (`Session`, `BroadcastProducer`, `RouteOptions`) as aliases, so the generated names still work. `MoqContainer`, `MoqRoute`, and the exceptions keep it, since Flutter owns those names. -- **Routes.** `route(path)` publishes a broadcast and `routePrefix(prefix)` answers requests beneath a prefix, each returning a `MoqRoute`. Hold it: cancelling or disposing it retracts the route, while a broadcast handle alone does not keep it announced. A `route(path)` keeps its instance across `withdraw()` and `announce()`, so a new run is a new route. Unless one is named, a request's own route (`request.route(options: ...)`) takes its prefix route's instance (on moq-lite 07; older wires mint another, restarting readers resolved through the prefix route), and the prefix route moves to a fresh one each time such a route holding its current one ends. +- **Routes.** `route(path)` publishes a broadcast, returning a `MoqRoute` whose `broadcast()` you fill, and `claim(prefix)` answers requests beneath a prefix, returning a `Claim` whose `requested()` yields each one. Hold either: cancelling or disposing it retracts it, while a broadcast handle alone does not keep a route announced. A `route(path)` keeps its instance across `withdraw()` and `announce()`, so a new run is a new route. Unless one is named, a request's own route (`request.route(options: ...)`) takes its claim's instance (on moq-lite 07; older wires mint another, restarting readers resolved through the claim), and the claim moves to a fresh one each time such a route holding its current one ends. - **Audio needs cuts.** Video groups at its keyframes, but audio forms a group only where you call `cut()`: after every frame, or less often to batch frames into fewer groups. - **Timeline breaks.** On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Media reads.** `media.TrackConsumer`, `audio.Consumer`, and `video.Consumer` return a `Read` in order: a `ReadFrame`, a `ReadGap` where media was lost, or a `ReadEnd` where the publisher stopped its encoder. A gap breaks continuity. An encoder end is not stream EOF: following frames before its endpoint are the old encoder's drain; the first at or past it starts fresh. A decoder reads everything the track still holds unless a live player sets `start: media.DecodeStart.latest` in its decoder output, which joins at the newest group and skips the cached backlog. diff --git a/doc/lib/go/index.md b/doc/lib/go/index.md index daaaeb292e1..717201e3f5f 100644 --- a/doc/lib/go/index.md +++ b/doc/lib/go/index.md @@ -96,7 +96,7 @@ import ( // opusInit, packet, pts (90 kHz ticks), and rgba come from your encoder or capture source. // Hidden until the catalog is filled; keep the route reachable while publishing. route, _ := client.Route("my-stream.hang", moq.RouteOptions{Hidden: true}) -broadcast, _ := route.Broadcast() +broadcast := route.Broadcast() audio, _ := moqmedia.NewAudioTrackProducer(broadcast, moqmedia.Named{}, moqmedia.AudioInit{Format: moqmedia.AudioFormatOpus, Data: opusInit}) timestamp := moq.Timestamp{Value: 960, Scale: 48_000} // 20 ms on the Opus sample clock _ = audio.WriteFrame(moq.Frame{Payload: packet, Timestamp: ×tamp}) @@ -125,7 +125,7 @@ one to one; the API reference has the names, and [Layers](/lib/layers) shows which module holds each. - **Context cancellation.** Every call that can block takes a `context.Context` first, and cancelling it tears down the native work, not just your wait. A one-shot call (`Request`, `FetchGroup`, `Server.Accept`) aborts alone; a stream read (`Next`, `ReadFrame`, and the iterators over them) cancels the stream it reads. -- **Keep owners reachable.** An origin from `moq.NewOriginProducer` has no `Close`. It ends when the garbage collector reaches its last owner (each producer and `Route`), and its consumers then fail with `moq.ErrClosed`. A `Route` the collector reclaims is retracted, so keep it reachable while it should stay announced, or end it with `Cancel()`. +- **Keep owners reachable.** An origin from `moq.NewOriginProducer` has no `Close`. It ends when the garbage collector reaches its last owner (each producer, `Route`, and `Claim`), and its consumers then fail with `moq.ErrClosed`. A `Route` or `Claim` the collector reclaims is retracted, so keep it reachable while it should stay announced, or end it with `Cancel()`. - **Bandwidth ownership.** An encoder you manage can reserve a share of the session's bandwidth. Reuse its reservation when the ceiling changes; before abandoning or replacing it, call `Update(0)` to return its share and automatic probe ceiling without waiting for garbage collection. The track can stay subscribed and the reservation can be reused. - **Audio needs cuts.** Video groups at its keyframes, but audio forms a group only where you call `Cut()`: after every frame, or less often to batch frames into fewer groups. - **Timeline breaks.** On a seek or pause, call `Discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. diff --git a/doc/lib/layers.md b/doc/lib/layers.md index a9ec70893c3..13b8d573c04 100644 --- a/doc/lib/layers.md +++ b/doc/lib/layers.md @@ -43,7 +43,7 @@ Sessions, origins, broadcasts, tracks, and groups: `Client`, `Server`, | C | `moq_session_*`, `moq_origin_*`, `moq_publish_track_*`, `moq_consume_track_*` | `moq_publish_track` | On-demand broadcast requests in every binding can answer with held content -without announcing an exact route. The answer uses the prefix route's +without announcing an exact route. The answer uses the claim's continuous sequence space at that path. Use a fresh publication for a job that may restart independently; see [work on demand](/concept/identity#work-on-demand) and the [Go](/lib/go/) and [C](/lib/c/) binding references. diff --git a/doc/lib/rs/index.md b/doc/lib/rs/index.md index 86c2c9c425e..b282027af0d 100644 --- a/doc/lib/rs/index.md +++ b/doc/lib/rs/index.md @@ -85,8 +85,8 @@ let route = origin.route("my-stream.hang", RouteOptions::default())?; // moq-mux (from a container) or moq-video / moq-audio (from a device) fill // `route.broadcast()`. Keep the route: dropping it, or closing its broadcast, // retracts it, and `withdraw()`/`announce()` hide and show the same stream. To -// serve a whole subtree on demand instead, `origin.route_prefix("room", ..)?` -// yields each requested path: answer with `request.route(..)`, `serve` a held +// serve a whole subtree on demand instead, `origin.claim("room", ..)?` returns +// a `Claim` that yields each requested path: answer with `request.route(..)`, `serve` a held // broadcast, or `reject`. ``` diff --git a/doc/lib/rs/moq-net.md b/doc/lib/rs/moq-net.md index 2af4f414756..71108634ccd 100644 --- a/doc/lib/rs/moq-net.md +++ b/doc/lib/rs/moq-net.md @@ -15,9 +15,9 @@ moq-transport at setup and presents one API either way. Media is a layer above What you use it for, beyond what the concept page already describes: -- **An origin outlives the session.** `origin.route(path, options)` returns a `Route` that owns the broadcast to fill (`route.broadcast()`) and controls its announcement: `announce()`, `withdraw()`, `set_cost()`, and dropping the last clone retracts it. `origin.route_prefix(prefix, options)` serves requests beneath a prefix instead, each answered with `request.serve(held)`, `request.route(options)` (the path's own exact route) or `reject`. A standalone broadcast cannot announce; publish one only through a prefix route's `serve`. A reconnect announces existing routes again, and closing the session does not delete them. +- **An origin outlives the session.** `origin.route(path, options)` returns a `Route` that owns the broadcast to fill (`route.broadcast()`) and controls its announcement: `announce()`, `withdraw()`, `set_cost()`, and dropping the last clone retracts it. `origin.claim(prefix, options)` returns a `Claim` that serves requests beneath a prefix instead: `claim.requested()` yields each one, answered with `request.serve(held)`, `request.route(options)` (the path's own exact route) or `reject`. A `Claim` has the same announcement controls and no broadcast. A standalone broadcast cannot announce; publish one only through a claim's `serve`. A reconnect announces existing routes again, and closing the session does not delete them. - **Routes report what the mesh filled in.** An announcement's `route` gives its `instance()`, `cost()`, the hop ids it crossed (`hops()`, oldest first, 0 for an anonymous hop) and `is_anonymous()`; an application sets only `RouteOptions`. An origin's own hop id is `origin::Config::hop`, random unless a relay names one. -- **Requests can pin an instance.** `consumer.request(path, Some(instance))` resolves only through a route announcing that [publisher instance](/concept/moq-lite#publisher-instances); `None` takes whichever route wins. The resolved consumer names its instance in `info().instance`, pinned or not. `origin.route(path, options)` serves a random instance minted when it is created and kept across `withdraw()` and `announce()`. Unless one is named, a prefix route moves to a fresh instance each time a job holding its current one ends, and a job takes the prefix route's. Set one with `RouteOptions::with_instance(instance, epoch)` only for a publisher that continues its group sequences across restarts and raises the epoch each time. `route.instance()` names it. +- **Requests can pin an instance.** `consumer.request(path, Some(instance))` resolves only through a route announcing that [publisher instance](/concept/moq-lite#publisher-instances); `None` takes whichever route wins. The resolved consumer names its instance in `info().instance`, pinned or not. `origin.route(path, options)` serves a random instance minted when it is created and kept across `withdraw()` and `announce()`. Unless one is named, a claim moves to a fresh instance each time a job holding its current one ends, and a job takes the claim's. Set one with `RouteOptions::with_instance(instance, epoch)` only for a publisher that continues its group sequences across restarts and raises the epoch each time. `route.instance()` names it. - **Rank several CDNs.** Dial each with its own subscribe handle, `origin.clone().with_preference(origin::Preference::new(rank))` (higher wins; 0 is neutral and a negative rank demotes), all on one origin. Requests use the preferred link that has a route and fail over to the next; see [multiple CDNs](/concept/moq-lite#multiple-cdns). - **Request one instance, or follow them all.** `consumer.request(path, None)` resolves the instance serving a path now, and fails `Unroutable` only once discovery has synced with no route for it. `consumer.follow(path, None)` hands out each publisher instance serving a path from `available()`: the first once announced, then each one that takes over, `None` once the path goes offline, and whatever serves it next, like JS `follow(path)`. `consumer.announced()` lists paths only as present or absent. A broadcast already resolved stays on the old instance until dropped or its route goes. See [identity and recovery](/concept/identity) to choose between following and holding one instance. - **Discovery follows what you watch.** A client session asks the relay for announcements only under the prefixes its subscribe origin's readers watch, with `announced()`, `request`, or `follow`, stops asking about a prefix 2s after nothing at or beneath it is watched, and asks again on reconnect. A broadcast resolved through a discovered route keeps its path watched until dropped. `request` owns discovery of its path, so no separate watch is needed. A server session, or a client fed into an origin handle marked `with_link(origin::Link::Peer)` or `Link::Upstream`, asks for everything it may, so a relay discovers everything. An HTTP gateway (the moq-hls `Server`, the moq-webrtc WHEP router) watches its whole scope while it lives, so the paths its callers name never open a request each. moq-lite-03/04 sessions, whose announcements mark no initial set, still ask for everything. diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index 7889493d3f4..a9a3c8717d2 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -72,7 +72,7 @@ for try await event in try session.consume.announced(prefix: "live/", filter: "* // opusInit, packet, pts, and rgba come from your encoder or capture source. // Hidden until the catalog is filled; hold the route while it should stay announced. let route = try session.publish.route(path: "my-stream.hang", hidden: true) -let broadcast = try route.broadcast +let broadcast = route.broadcast let audio = try Media.TrackProducer.audio(broadcast: broadcast, initData: Media.AudioInit(format: .opus, data: opusInit)) try audio.writeFrame(packet, timestamp: Timestamp(value: 20, scale: 1_000)) try audio.cut() // audio has no keyframes, so this is what gives it groups diff --git a/go/wrapper/README.md b/go/wrapper/README.md index 16f98f5e61b..2a6a457afe9 100644 --- a/go/wrapper/README.md +++ b/go/wrapper/README.md @@ -139,7 +139,7 @@ import ( ) route, _ := client.Route("room", moq.RouteOptions{Hidden: true}) -broadcast, _ := route.Broadcast() +broadcast := route.Broadcast() // Every JSON write is stamped, so the track is timed. JSON is small and repetitive, so // compress it on the wire. scale := uint64(1_000) diff --git a/go/wrapper/example_test.go b/go/wrapper/example_test.go index dbc2243939e..607e04aad72 100644 --- a/go/wrapper/example_test.go +++ b/go/wrapper/example_test.go @@ -91,10 +91,7 @@ func ExampleClient_Route() { log.Fatal(err) } defer route.Cancel() - broadcast, err := route.Broadcast() - if err != nil { - log.Fatal(err) - } + broadcast := route.Broadcast() media, err := moqmedia.NewAudioTrackProducer(broadcast, moqmedia.Named{}, moqmedia.AudioInit{Format: moqmedia.AudioFormatOpus, Data: opusHead()}) if err != nil { diff --git a/go/wrapper/moq_test.go b/go/wrapper/moq_test.go index 6bbe426013c..65e18b57f47 100644 --- a/go/wrapper/moq_test.go +++ b/go/wrapper/moq_test.go @@ -39,10 +39,7 @@ func newRoute(t *testing.T, origin *moq.OriginProducer, path string, options moq t.Fatal(err) } t.Cleanup(func() { runtime.KeepAlive(route) }) - broadcast, err := route.Broadcast() - if err != nil { - t.Fatal(err) - } + broadcast := route.Broadcast() return route, broadcast } @@ -62,14 +59,11 @@ func TestDynamicBroadcastRequest(t *testing.T) { defer cancel() origin := newOrigin(t) - dynamic, err := origin.RoutePrefix("", moq.RouteOptions{}) + dynamic, err := origin.Claim("", moq.RouteOptions{}) if err != nil { t.Fatal(err) } defer dynamic.Cancel() - if _, err := dynamic.Broadcast(); err == nil { - t.Fatal("a prefix route owns no broadcast") - } type result struct { broadcast *moq.BroadcastConsumer @@ -99,12 +93,9 @@ func TestDynamicBroadcastRequest(t *testing.T) { } defer runtime.KeepAlive(served) if served.Instance() != dynamic.Instance() { - t.Fatal("a job's route continues the instance its prefix route lends") - } - broadcast, err := served.Broadcast() - if err != nil { - t.Fatal(err) + t.Fatal("a job's route continues the instance its claim lends") } + broadcast := served.Broadcast() track, err := broadcast.PublishTrack("status", timedInfo()) if err != nil { t.Fatal(err) @@ -149,10 +140,7 @@ func TestDynamicBroadcastRequest(t *testing.T) { t.Fatal(err) } // The route hands out one broadcast, so closing it ends the route too. - again, err := served.Broadcast() - if err != nil { - t.Fatal(err) - } + again := served.Broadcast() if _, err := again.PublishTrack("late", nil); !errors.Is(err, moq.ErrClosed) { t.Fatalf("PublishTrack after close = %v, want ErrClosed", err) } @@ -1322,7 +1310,7 @@ func TestConsumerCancelConcurrent(t *testing.T) { // that one request rather than the consumer it was made on. func TestRequestCancelKeepsTheOrigin(t *testing.T) { origin := newOrigin(t) - dynamic, err := origin.RoutePrefix("", moq.RouteOptions{}) + dynamic, err := origin.Claim("", moq.RouteOptions{}) if err != nil { t.Fatal(err) } @@ -1848,7 +1836,7 @@ func TestDynamicServesARequestUnderAPrefix(t *testing.T) { defer cancel() origin := newOrigin(t) - dynamic, err := origin.RoutePrefix("live", moq.RouteOptions{}) + dynamic, err := origin.Claim("live", moq.RouteOptions{}) if err != nil { t.Fatal(err) } @@ -1884,7 +1872,7 @@ func TestCancellingAHiddenAnswerRefusesTheRequest(t *testing.T) { defer cancel() origin := newOrigin(t) - dynamic, err := origin.RoutePrefix("live", moq.RouteOptions{}) + dynamic, err := origin.Claim("live", moq.RouteOptions{}) if err != nil { t.Fatal(err) } diff --git a/go/wrapper/origin.go b/go/wrapper/origin.go index 55021fc10a0..70e5985d7f7 100644 --- a/go/wrapper/origin.go +++ b/go/wrapper/origin.go @@ -13,7 +13,7 @@ import ( // consume sink for a full-duplex peer. // // There is no Close: the origin ends once the collector reaches every owner -// (each producer and [Route]), and its consumers +// (each producer, [Route], and [Claim]), and its consumers // then fail with [ErrClosed]. Keep an owner reachable for as long as the origin // should live. type OriginProducer struct { @@ -51,56 +51,44 @@ func (o *OriginProducer) Route(path string, options RouteOptions) (*Route, error return newRoute(inner), nil } -// RoutePrefix creates a route over prefix that serves the requests beneath it. +// Claim claims prefix and serves the requests beneath it. // -// A route claims prefix and every path beneath it ("" claims every path). A +// A claim covers prefix and every path beneath it ("" claims every path). A // service that only serves some of them rejects the rest as they are requested. -// Answer each [Route.Requested] request, and keep the route reachable while it +// Answer each [Claim.Requested] request, and keep the claim reachable while it // should stay advertised. -func (o *OriginProducer) RoutePrefix(prefix string, options RouteOptions) (*Route, error) { - inner, err := o.inner.RoutePrefix(prefix, options) +func (o *OriginProducer) Claim(prefix string, options RouteOptions) (*Claim, error) { + inner, err := o.inner.Claim(prefix, options) if err != nil { return nil, err } - return newRoute(inner), nil + return &Claim{inner: inner}, nil } -// Route is a route on an origin: an exact route owning one broadcast, or a -// prefix route yielding the requests beneath it. +// Route is an exact route on an origin, owning one broadcast. // // [Route.Cancel], or the collector reclaiming it, retracts the route, as does -// closing an exact route's broadcast; a [BroadcastProducer] alone does not keep -// it announced. +// closing its broadcast; a [BroadcastProducer] alone does not keep it +// announced. type Route struct { inner *ffi.MoqRoute broadcast *BroadcastProducer } func newRoute(inner *ffi.MoqRoute) *Route { - route := &Route{inner: inner} - // A prefix route owns no broadcast. - if broadcast, err := inner.Broadcast(); err == nil { - route.broadcast = &BroadcastProducer{inner: broadcast} - } - return route + return &Route{inner: inner, broadcast: &BroadcastProducer{inner: inner.Broadcast()}} } -// Broadcast returns the broadcast an exact route owns, the same one on every -// call, or an error on a prefix route, which owns none. -func (r *Route) Broadcast() (*BroadcastProducer, error) { - if r.broadcast == nil { - _, err := r.inner.Broadcast() - return nil, err - } - return r.broadcast, nil +// Broadcast returns the broadcast the route owns, the same one on every call. +func (r *Route) Broadcast() *BroadcastProducer { + return r.broadcast } // Instance returns the stream this route serves now. A named instance never -// changes. Unnamed, a prefix route moves to a fresh one each time a job holding -// its current one ends. A job's route takes its prefix route's current one when -// it first announces or when this first reads it. Read first, the job announces -// under it, and [Route.Announce] fails with Unroutable once the prefix route has -// moved past it, so a signer built from it stays valid. +// changes. A job's route takes its claim's current one when it first announces +// or when this first reads it. Read first, the job announces under it, and +// [Route.Announce] fails with Unroutable once the claim has moved past it, so a +// signer built from it stays valid. func (r *Route) Instance() string { return r.inner.InstanceId() } @@ -125,12 +113,53 @@ func (r *Route) SetCost(cost uint64) error { return r.inner.SetCost(cost) } -// Requested blocks until a consumer requests a path beneath this prefix route, -// returning (nil, nil) once the origin closes, and at once on an exact route. +// Cancel retracts the route now, rather than when the collector reclaims it. +// Later calls fail with ErrCancelled. Its broadcast lives on until +// [BroadcastProducer.Close]. +func (r *Route) Cancel() { + r.inner.Cancel() +} + +// Claim is a prefix route on an origin: a claim that every path beneath a +// prefix can be served, yielding each request as it arrives. // -// Cancelling ctx abandons only this wait: the route stays advertised. -func (r *Route) Requested(ctx context.Context) (*BroadcastRequest, error) { - inner, err := bridge.CallRelease(ctx, nil, r.inner.Requested, func(request **ffi.MoqBroadcastRequest) { +// [Claim.Cancel], or the collector reclaiming it, retracts the claim and +// rejects the requests still waiting. +type Claim struct { + inner *ffi.MoqClaim +} + +// Instance returns the stream this claim serves now. A named instance never +// changes. Unnamed, the claim moves to a fresh one each time a job holding its +// current one ends. +func (c *Claim) Instance() string { + return c.inner.InstanceId() +} + +// Announce makes the claim visible, or keeps it so. +func (c *Claim) Announce() error { + return c.inner.Announce() +} + +// Withdraw hides the claim from local consumers and peers alike, keeping its +// instance: Announce brings it back. Requests beneath it are rejected +// meanwhile. +func (c *Claim) Withdraw() error { + return c.inner.Withdraw() +} + +// SetCost re-prices the claim in place: lower wins among routes covering the +// same prefix. A hidden claim keeps the price for when it next announces. +func (c *Claim) SetCost(cost uint64) error { + return c.inner.SetCost(cost) +} + +// Requested blocks until a consumer requests a path beneath this claim, +// returning (nil, nil) once the claim is retracted or the origin closes. +// +// Cancelling ctx abandons only this wait: the claim stays advertised. +func (c *Claim) Requested(ctx context.Context) (*BroadcastRequest, error) { + inner, err := bridge.CallRelease(ctx, nil, c.inner.Requested, func(request **ffi.MoqBroadcastRequest) { if request != nil { (*request).Destroy() } @@ -141,17 +170,16 @@ func (r *Route) Requested(ctx context.Context) (*BroadcastRequest, error) { return &BroadcastRequest{inner: *inner}, nil } -// All ranges over requested broadcasts until the route ends, a call errors, or +// All ranges over requested broadcasts until the claim ends, a call errors, or // the loop breaks. -func (r *Route) All(ctx context.Context) iter.Seq2[*BroadcastRequest, error] { - return bridge.Seq(ctx, r.Requested) +func (c *Claim) All(ctx context.Context) iter.Seq2[*BroadcastRequest, error] { + return bridge.Seq(ctx, c.Requested) } -// Cancel retracts the route now, rather than when the collector reclaims it. -// Pending requests are rejected and later calls fail with ErrCancelled. An exact -// route's broadcast lives on until [BroadcastProducer.Close]. -func (r *Route) Cancel() { - r.inner.Cancel() +// Cancel retracts the claim now, rather than when the collector reclaims it. +// Pending requests are rejected and later calls fail with ErrCancelled. +func (c *Claim) Cancel() { + c.inner.Cancel() } // BroadcastRequest is a requested broadcast that has not been answered yet. @@ -166,11 +194,11 @@ func (r *BroadcastRequest) Path() (string, error) { // Route answers with the path's own exact route, owning a new broadcast. // -// Unless options names an instance, it takes the one its prefix route lends -// when it first announces or [Route.Instance] first reads it, so readers that resolved the path through the prefix -// route continue on it; its end then moves the prefix route to a fresh instance, -// so a restarted job is a new stream. A prefix route that names its instance -// lends none, and the route mints its own. Created visible, it announces now and answers +// Unless options names an instance, it takes the one its claim lends when it +// first announces or [Route.Instance] first reads it, so readers that resolved +// the path through the claim continue on it; its end then moves the claim to a +// fresh instance, so a restarted job is a new stream. A claim that names its +// instance lends none, and the route mints its own. Created visible, it announces now and answers // the waiting requesters; created hidden, they wait // until [Route.Announce], so the job can fill its catalog first. func (r *BroadcastRequest) Route(options RouteOptions) (*Route, error) { @@ -181,7 +209,7 @@ func (r *BroadcastRequest) Route(options RouteOptions) (*Route, error) { return newRoute(inner), nil } -// Serve answers with held content under the prefix route's continuous sequence space, +// Serve answers with held content under the claim's continuous sequence space, // without announcing an exact route. The broadcast remains the caller's to release. func (r *BroadcastRequest) Serve(broadcast *BroadcastConsumer) error { return r.inner.Serve(broadcast.inner) diff --git a/go/wrapper/origin_internal_test.go b/go/wrapper/origin_internal_test.go index e3f2de5544b..e4010f23968 100644 --- a/go/wrapper/origin_internal_test.go +++ b/go/wrapper/origin_internal_test.go @@ -43,7 +43,7 @@ func TestRouteKeepsTheOrigin(t *testing.T) { defer cancel() origin := NewOriginProducer() - dynamic, err := origin.RoutePrefix("", RouteOptions{}) + dynamic, err := origin.Claim("", RouteOptions{}) if err != nil { t.Fatal(err) } @@ -95,11 +95,8 @@ func TestReleasingARouteRetractsIt(t *testing.T) { if err != nil { t.Fatal(err) } - broadcast, err := route.Broadcast() - if err != nil { - t.Fatal(err) - } - if again, _ := route.Broadcast(); again != broadcast { + broadcast := route.Broadcast() + if route.Broadcast() != broadcast { t.Fatal("Broadcast must return the same producer on every call") } if _, err := consumer.Request(ctx, "live", nil); err != nil { diff --git a/go/wrapper/reconnect_test.go b/go/wrapper/reconnect_test.go index da8edb5bb8e..84e08fb1531 100644 --- a/go/wrapper/reconnect_test.go +++ b/go/wrapper/reconnect_test.go @@ -188,10 +188,7 @@ func TestReconnectAcrossRelayRestart(t *testing.T) { t.Fatal(err) } defer route.Cancel() - broadcast, err := route.Broadcast() - if err != nil { - t.Fatal(err) - } + broadcast := route.Broadcast() defer broadcast.Close() track, err := broadcast.PublishTrack("data", timedInfo()) diff --git a/go/wrapper/runtime_bench_test.go b/go/wrapper/runtime_bench_test.go index 0d01fb69477..09f59eae517 100644 --- a/go/wrapper/runtime_bench_test.go +++ b/go/wrapper/runtime_bench_test.go @@ -155,10 +155,7 @@ func benchThroughput(b *testing.B, c benchCase) { b.Fatal(err) } b.Cleanup(func() { runtime.KeepAlive(route) }) - broadcast, err := route.Broadcast() - if err != nil { - b.Fatal(err) - } + broadcast := route.Broadcast() b.Cleanup(func() { _ = broadcast.Close() }) tracks := make([]*moq.TrackProducer, c.publishers) consumers := make([]*moq.TrackConsumer, 0, c.publishers*c.subscribers) diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index 54149942435..9551342a051 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -49,17 +49,24 @@ typealias Request = uniffi.moq.MoqRequest typealias Transport = uniffi.moq.MoqTransport // Origin (broadcast discovery / announcement). -/** The publish side of an origin: create routes so subscribers can discover them. */ +/** The publish side of an origin: create routes and claims so subscribers can discover them. */ typealias OriginProducer = uniffi.moq.MoqOriginProducer /** - * A route on an origin: an exact route owning one broadcast (`broadcast()` to fill it), or a prefix - * route yielding the requests beneath it (`requested()`). `announce`, `withdraw`, and `setCost` - * advertise it. Closing or cancelling it retracts it, as does ending its broadcast; a broadcast - * handle alone does not keep it announced. + * An exact route on an origin, owning one broadcast (`broadcast()` to fill it). `announce`, + * `withdraw`, and `setCost` advertise it. Closing or cancelling it retracts it, as does ending its + * broadcast; a broadcast handle alone does not keep it announced. */ typealias Route = uniffi.moq.MoqRoute +/** + * A prefix route on an origin, from `OriginProducer.claim`: a claim that every path beneath a + * prefix can be served, yielding each request (`requested()`). `announce`, `withdraw`, and + * `setCost` advertise it. Closing or cancelling it retracts it and rejects the requests still + * waiting. + */ +typealias Claim = uniffi.moq.MoqClaim + /** Config for creating an origin, such as its total cache budget. */ typealias OriginConfig = uniffi.moq.MoqOriginConfig diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt index bf2fc6a62bc..611a3a82498 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Flows.kt @@ -48,10 +48,11 @@ fun BroadcastRequests.requestedTracks(): Flow = fun TrackRequests.requestedFills(): Flow = pull({ cancel() }) { requestedFill() } /** - * Stream of broadcasts requested beneath a prefix route, ending once the origin closes. Ending the - * collection leaves the route advertised; close or cancel the route to retract it. + * Stream of broadcasts requested beneath a claim, ending once the claim is retracted or the origin + * closes. Ending the collection leaves the claim advertised; close or cancel the claim to retract + * it. */ -fun Route.requestedBroadcasts(): Flow = pull { requested() } +fun Claim.requestedBroadcasts(): Flow = pull { requested() } /** Stream of timestamped raw frames within a group. */ fun GroupConsumer.frames(): Flow = pull({ cancel() }) { readFrame() } diff --git a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt index e4a7597e87e..82afb4259b0 100644 --- a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt +++ b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt @@ -210,7 +210,7 @@ class SmokeTest { fun `origin alias constructs and consumes`() = runTest { OriginProducer(OriginConfig()).use { origin -> origin.consume().use { /* lifecycle smoke */ } - origin.routePrefix("", RouteOptions()).use { /* prefix route smoke */ } + origin.claim("", RouteOptions()).use { /* claim smoke */ } } } @@ -912,8 +912,7 @@ class SmokeTest { @Test fun `dynamic serves a request under a prefix`() = runTest { OriginProducer(OriginConfig()).use { origin -> - origin.routePrefix("live", RouteOptions()).use { dynamic -> - assertFailsWith { dynamic.broadcast() } + origin.claim("live", RouteOptions()).use { dynamic -> val pending = async { origin.consume().request("live/cam") } diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index 79a5a88735f..b17a0574edf 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -248,7 +248,7 @@ same either way. Opaque bytes go on a plain `TrackProducer`. - **`GroupConsumer`**. Async iterator of raw `Frame`s. - `.read_frame() -> Frame | None` returns a raw frame with optional capture time. -Every handle whose cleanup is `cancel()` is an async context manager, so exiting `async with` releases it: the consumers (`media.CatalogConsumer`, `media.TrackConsumer`, `media.GroupConsumer`, `TrackConsumer`, `audio.Consumer`, `video.Consumer`, `GroupConsumer`, `json.SnapshotConsumer`, `json.StreamConsumer`, `json.WindowConsumer`, `AnnounceConsumer`, `Following`) and the dynamic sources (`Route`, `BroadcastRequests`, `TrackRequests`). +Every handle whose cleanup is `cancel()` is an async context manager, so exiting `async with` releases it: the consumers (`media.CatalogConsumer`, `media.TrackConsumer`, `media.GroupConsumer`, `TrackConsumer`, `audio.Consumer`, `video.Consumer`, `GroupConsumer`, `json.SnapshotConsumer`, `json.StreamConsumer`, `json.WindowConsumer`, `AnnounceConsumer`, `Following`) and the dynamic sources (`Route`, `Claim`, `BroadcastRequests`, `TrackRequests`). ### Sockets @@ -285,12 +285,15 @@ moq-transport on every relay hop; this API does not add pre-07 capability detect - **`OriginProducer(*, cache_capacity_bytes=None)`**. Manage broadcast announcements. Set `cache_capacity_bytes` to bound cached groups under this origin. - `.consume() → OriginConsumer` - `.route(path, *, hidden=False, cost=0, instance=None, epoch=0) → Route`. An exact route owning a new broadcast, visible at once unless `hidden`, under a fresh instance unless `instance` names one. - - `.route_prefix(prefix, *, hidden=False, cost=0, instance=None, epoch=0) → Route`. A prefix route that yields the requests beneath it. -- **`Route`**. A route on an origin. Hold it: dropping or cancelling it retracts it, and so does closing its broadcast. - - `.broadcast → BroadcastProducer`. The broadcast an exact route owns; raises `Internal` on a prefix route. - - `.instance`. The stream it serves now, kept across `withdraw()` and `announce()`. Unless one is named, a prefix route moves to a fresh one each time a job holding it ends, and a job takes its prefix route's when it first announces or when `.instance` first reads it. Read first, the job announces under it, and `announce()` fails with `Unroutable` once the prefix route has moved past it. + - `.claim(prefix, *, hidden=False, cost=0, instance=None, epoch=0) → Claim`. Claim `prefix` and every path beneath it, yielding the requests there. +- **`Route`**. An exact route on an origin, owning one broadcast. Hold it: dropping or cancelling it retracts it, and so does closing its broadcast. + - `.broadcast → BroadcastProducer`. The broadcast the route owns. + - `.instance`. The stream it serves now, kept across `withdraw()` and `announce()`. Unless one is named, a job's route takes its claim's when it first announces or when `.instance` first reads it. Read first, the job announces under it, and `announce()` fails with `Unroutable` once the claim has moved past it. - `.announce()`, `.withdraw()`, `.set_cost(cost)`. Show, hide, or re-price it in place; `announce` and `set_cost` raise `Closed` once the broadcast closed. - - `await .requested() → BroadcastRequest | None`, or async iteration over a prefix route. Call `.serve(consumer)` to answer with held content under the prefix route's continuous sequence space, `.route(hidden=..., ...)` for the path's own route, which continues the prefix route's instance until the job ends and then moves the prefix route to a fresh one (unless either names an instance: a named prefix route lends none, and a named job keeps its own), or `.reject(code)` to fail the requester. +- **`Claim`**. A prefix route on an origin. Hold it: dropping or cancelling it retracts it and rejects the requests still waiting. + - `.instance`. The stream it serves now, kept across `withdraw()` and `announce()`. Unless one is named, it moves to a fresh one each time a job holding it ends. + - `.announce()`, `.withdraw()`, `.set_cost(cost)`. Show, hide, or re-price it in place. + - `await .requested() → BroadcastRequest | None`, or async iteration. Call `.serve(consumer)` to answer with held content under the claim's continuous sequence space, `.route(hidden=..., ...)` for the path's own route, which continues the claim's instance until the job ends and then moves the claim to a fresh one (unless either names an instance: a named claim lends none, and a named job keeps its own), or `.reject(code)` to fail the requester. - **`OriginConsumer`**. Discover broadcasts. - `.announced(prefix, filter=None) → AnnounceConsumer` (async iterator of `AnnounceEvent`: `AnnounceEventPresent` or `AnnounceEventAbsent`, each carrying an `Announce` whose `.route.instance` names the stream; another instance taking a path over keeps it present, so `follow` the path to see that); `filter` is a pattern relative to the literal prefix, while each `Announce.prefix` stays origin-relative and `.captures` is a required list of wildcard matches, empty without wildcards - `.follow(path, instance=None) → Following` (awaitable, waits until something serves the path, then returns each stream that takes over, or `None` once the path goes offline; an `instance` follows only that stream) diff --git a/py/moq-rs/docs/index.md b/py/moq-rs/docs/index.md index d51a05244f5..5bae389fab3 100644 --- a/py/moq-rs/docs/index.md +++ b/py/moq-rs/docs/index.md @@ -195,6 +195,7 @@ broadcast, and producers advertise it in the catalog. OriginProducer OriginConsumer Route + Claim AnnounceConsumer Following Announce diff --git a/py/moq-rs/moq/__init__.py b/py/moq-rs/moq/__init__.py index 76c391c65e4..b5d7284fe48 100644 --- a/py/moq-rs/moq/__init__.py +++ b/py/moq-rs/moq/__init__.py @@ -22,6 +22,7 @@ AnnounceEventAbsent, AnnounceEventPresent, BroadcastRequest, + Claim, Following, OriginConsumer, OriginProducer, @@ -108,6 +109,7 @@ "BroadcastRequests", "BroadcastProducer", "BroadcastRequest", + "Claim", "Client", "ClientTls", "CongestionControl", diff --git a/py/moq-rs/moq/origin.py b/py/moq-rs/moq/origin.py index 1128922623f..5cdb90182ff 100644 --- a/py/moq-rs/moq/origin.py +++ b/py/moq-rs/moq/origin.py @@ -8,6 +8,7 @@ MoqAnnounceConsumer, MoqAnnounceEvent, MoqBroadcastRequest, + MoqClaim, MoqFollowing, MoqOriginConfig, MoqOriginConsumer, @@ -119,19 +120,19 @@ def path(self) -> str: def route(self, *, hidden: bool = False, cost: int = 0, instance: str | None = None, epoch: int = 0) -> Route: """Answer with the path's own exact :class:`Route`, owning a new broadcast. - Unless ``instance`` names one, the route takes the instance its prefix route lends when - it first announces or :attr:`Route.instance` first reads it, so readers that resolved - the path through the prefix route continue on it; its end then moves the prefix route to - a fresh instance, so a job that restarts is a new stream. A prefix route that names its - instance lends none, and the route mints its own. Created visible, it announces now and - answers the waiting requesters; created ``hidden``, they wait until - :meth:`Route.announce`, so the job can fill its catalog first, and cancelling the route - before then refuses them. Ending the route withdraws only this path. + Unless ``instance`` names one, the route takes the instance its claim lends when it + first announces or :attr:`Route.instance` first reads it, so readers that resolved the + path through the claim continue on it; its end then moves the claim to a fresh + instance, so a job that restarts is a new stream. A claim that names its instance lends + none, and the route mints its own. Created visible, it announces now and answers the + waiting requesters; created ``hidden``, they wait until :meth:`Route.announce`, so the + job can fill its catalog first, and cancelling the route before then refuses them. + Ending the route withdraws only this path. """ return Route(self._inner.route(_options(hidden=hidden, cost=cost, instance=instance, epoch=epoch))) def serve(self, broadcast: BroadcastConsumer) -> None: - """Serve held content under the prefix route's continuous sequence space, without an exact route.""" + """Serve held content under the claim's continuous sequence space, without an exact route.""" self._inner.serve(broadcast._inner) def reject(self, error_code: int) -> None: @@ -139,40 +140,37 @@ def reject(self, error_code: int) -> None: self._inner.reject(error_code) -class Route(_Stream[BroadcastRequest]): - """A route on an origin: an exact route owning one broadcast, or a prefix route - yielding the requests beneath it. +class Route: + """An exact route on an origin, owning one broadcast. Hold it for as long as the route should stay advertised: dropping or cancelling it - retracts it, as does closing an exact route's broadcast. A broadcast handle alone does - not keep it announced. Iterate a prefix route with ``async for`` for its - :class:`BroadcastRequest` values; usable as an async context manager that cancels the - route on exit. + retracts it, as does closing its broadcast. A broadcast handle alone does not keep it + announced. Usable as an async context manager that cancels the route on exit. """ def __init__(self, inner: MoqRoute) -> None: self._inner = inner - self._broadcast: BroadcastProducer | None = None + self._broadcast = BroadcastProducer._from_inner(inner.broadcast()) + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc) -> None: + self.cancel() @property def broadcast(self) -> BroadcastProducer: - """The broadcast this exact route owns, to fill with tracks. - - Raises ``moq.Error.Internal`` on a prefix route, which owns none: answer its requests instead. - """ - if self._broadcast is None: - self._broadcast = BroadcastProducer._from_inner(self._inner.broadcast()) + """The broadcast this route owns, to fill with tracks.""" return self._broadcast @property def instance(self) -> str: """The stream this route serves now. - A named instance never changes. Unnamed, a prefix route moves to a fresh one each time - a job holding its current one ends. A job's route takes its prefix route's current one - when it first announces or when this first reads it. Read first, the job announces - under it, and :meth:`announce` fails with ``Unroutable`` once the prefix route has moved - past it, so a signer built from it stays valid. Withdrawing and announcing keep it.""" + A named instance never changes. A job's route takes its claim's current one when it + first announces or when this first reads it. Read first, the job announces under it, + and :meth:`announce` fails with ``Unroutable`` once the claim has moved past it, so a + signer built from it stays valid. Withdrawing and announcing keep it.""" return self._inner.instance_id() def announce(self) -> None: @@ -198,21 +196,65 @@ def set_cost(self, cost: int) -> None: """ self._inner.set_cost(cost) + def cancel(self) -> None: + """Retract the route and release it now. Its broadcast lives on until + :meth:`BroadcastProducer.close`.""" + self._inner.cancel() + + +class Claim(_Stream[BroadcastRequest]): + """A prefix route on an origin: a claim that every path beneath a prefix can be served, + yielding each request as it arrives. + + Hold it for as long as the claim should stay advertised: dropping or cancelling it + retracts it and rejects the requests still waiting. Iterate it with ``async for`` for its + :class:`BroadcastRequest` values; usable as an async context manager that cancels the + claim on exit. + """ + + def __init__(self, inner: MoqClaim) -> None: + self._inner = inner + + @property + def instance(self) -> str: + """The stream this claim serves now. + + A named instance never changes. Unnamed, the claim moves to a fresh one each time a + job holding its current one ends. Withdrawing and announcing keep it.""" + return self._inner.instance_id() + + def announce(self) -> None: + """Make the claim visible, or keep it so.""" + self._inner.announce() + + def withdraw(self) -> None: + """Hide the claim from everyone, keeping its instance: :meth:`announce` brings it back. + + Requests beneath it are rejected meanwhile. + """ + self._inner.withdraw() + + def set_cost(self, cost: int) -> None: + """Re-price the claim in place: lower wins among routes covering the same prefix. + + A hidden claim keeps the price for when it next announces. + """ + self._inner.set_cost(cost) + async def _next(self) -> BroadcastRequest | None: return await self.requested() async def requested(self) -> BroadcastRequest | None: - """Await the next broadcast a consumer requests beneath this prefix route. + """Await the next broadcast a consumer requests beneath this claim. Serve, route, or reject it; the requester stays pending until then. Returns - ``None`` once the origin closes, and at once on an exact route. + ``None`` once the claim is retracted or the origin closes. """ request = await self._inner.requested() return None if request is None else BroadcastRequest(request) def cancel(self) -> None: - """Retract the route and release it now. An exact route's broadcast lives on until - :meth:`BroadcastProducer.close`.""" + """Retract the claim and release it now, rejecting the requests still waiting.""" self._inner.cancel() @@ -260,7 +302,7 @@ async def request(self, path: str, *, instance: str | None = None) -> BroadcastC class OriginProducer: """The publishing side of an origin: route broadcasts for consumers to discover. - Call :meth:`route` to publish a broadcast at a path, :meth:`route_prefix` to + Call :meth:`route` to publish a broadcast at a path, :meth:`claim` to serve on-demand requests beneath a prefix, or :meth:`consume` for a matching :class:`OriginConsumer`. """ @@ -293,15 +335,13 @@ def route( """ return Route(self._inner.route(path, _options(hidden=hidden, cost=cost, instance=instance, epoch=epoch))) - def route_prefix( + def claim( self, prefix: str, *, hidden: bool = False, cost: int = 0, instance: str | None = None, epoch: int = 0 - ) -> Route: - """Create a :class:`Route` over ``prefix`` that yields the requests beneath it. + ) -> Claim: + """Claim ``prefix`` and yield the requests beneath it as a :class:`Claim`. - A route claims ``prefix`` and every path beneath it (``""`` claims every + A claim covers ``prefix`` and every path beneath it (``""`` claims every path). A service that only serves some of them rejects the rest as they - are requested. Hold the route while it should stay advertised. + are requested. Hold the claim while it should stay advertised. """ - return Route( - self._inner.route_prefix(prefix, _options(hidden=hidden, cost=cost, instance=instance, epoch=epoch)) - ) + return Claim(self._inner.claim(prefix, _options(hidden=hidden, cost=cost, instance=instance, epoch=epoch))) diff --git a/py/moq-rs/tests/test_local.py b/py/moq-rs/tests/test_local.py index 4d94a03a30c..5bbef20a8c2 100644 --- a/py/moq-rs/tests/test_local.py +++ b/py/moq-rs/tests/test_local.py @@ -830,7 +830,7 @@ async def test_dynamic_track_request_can_publish_media(): async def test_dynamic_broadcast_request(): origin = moq.OriginProducer(cache_capacity_bytes=4096) - dynamic = origin.route_prefix("") + dynamic = origin.claim("") consumer = origin.consume() requesting = asyncio.create_task(consumer.request("dynamic/broadcast")) @@ -839,7 +839,7 @@ async def test_dynamic_broadcast_request(): assert request is not None assert request.path == "dynamic/broadcast" - # A hidden job route answers once it announces, under the instance its prefix route lends. + # A hidden job route answers once it announces, under the instance its claim lends. served = request.route(hidden=True) assert served.instance == dynamic.instance track = served.broadcast.publish_track("status", moq.TrackInfo(timescale=1_000_000)) @@ -862,7 +862,7 @@ async def test_dynamic_broadcast_request(): async def test_dynamic_serves_held_content_without_an_exact_route(): origin = moq.OriginProducer() - dynamic = origin.route_prefix("live") + dynamic = origin.claim("live") held = moq.BroadcastProducer() track = held.publish_track("status", moq.TrackInfo(timescale=1_000_000)) source = held.consume() @@ -884,7 +884,7 @@ async def test_dynamic_serves_held_content_without_an_exact_route(): async def test_dynamic_broadcast_request_can_reject(): origin = moq.OriginProducer() - dynamic = origin.route_prefix("") + dynamic = origin.claim("") consumer = origin.consume() requesting = asyncio.create_task(consumer.request("missing")) @@ -1816,7 +1816,7 @@ async def test_announced_pattern_captures(): announced = consumer.announced("room", filter="*/chat") # A claim at "room" could serve a match, but its own name is none, so it is not listed. - dynamic = origin.route_prefix("room") + dynamic = origin.claim("room") audio = origin.route("room/alice/audio") chat = origin.route("room/alice/chat") @@ -1833,10 +1833,8 @@ async def test_announced_pattern_captures(): async def test_dynamic_serves_a_request_under_a_prefix(): origin = moq.OriginProducer() - dynamic = origin.route_prefix("live") + dynamic = origin.claim("live") consumer = origin.consume() - with pytest.raises(moq.Error.Internal): - _ = dynamic.broadcast pending = asyncio.create_task(consumer.request("live/cam")) request = await asyncio.wait_for(anext(dynamic), timeout=5.0) @@ -1856,7 +1854,7 @@ async def assert_cancelled(awaitable) -> None: assert moq.is_shutdown(excinfo.value) origin = moq.OriginProducer() - async with origin.route_prefix("live") as origin_dynamic: + async with origin.claim("live") as origin_dynamic: pass await assert_cancelled(origin_dynamic.requested()) diff --git a/rs/moq-c/README.md b/rs/moq-c/README.md index 873d3374084..9b05bae6c02 100644 --- a/rs/moq-c/README.md +++ b/rs/moq-c/README.md @@ -81,14 +81,21 @@ int32_t moq_origin_announced_cancel(uint32_t announced); // Publishing: Routes (freeing one retracts it; moq_publish_close on its broadcast ends both) int32_t moq_origin_route(uint32_t origin, const char *path, uintptr_t path_len, const moq_route_options *options); -int32_t moq_origin_route_prefix(uint32_t origin, const char *prefix, uintptr_t prefix_len, const moq_route_options *options, moq_status_callback on_request, void *user_data); -// options (NULL for the default): hidden until moq_route_announce, a cost, and an optional stable instance with its epoch. Hops are the origin's to add. +// options (NULL for the default): hidden until announced, a cost, and an optional stable instance with its epoch. Hops are the origin's to add. int32_t moq_route_broadcast(uint32_t route); int32_t moq_route_instance(uint32_t route, moq_string *dst); int32_t moq_route_announce(uint32_t route); int32_t moq_route_withdraw(uint32_t route); int32_t moq_route_set_cost(uint32_t route, uint64_t cost); int32_t moq_route_free(uint32_t route); + +// Publishing: Claims (a prefix answered on demand; freeing one retracts it) +int32_t moq_origin_claim(uint32_t origin, const char *prefix, uintptr_t prefix_len, const moq_route_options *options, moq_status_callback on_request, void *user_data); +int32_t moq_claim_instance(uint32_t claim, moq_string *dst); +int32_t moq_claim_announce(uint32_t claim); +int32_t moq_claim_withdraw(uint32_t claim); +int32_t moq_claim_set_cost(uint32_t claim, uint64_t cost); +int32_t moq_claim_free(uint32_t claim); int32_t moq_broadcast_request_path(uint32_t request, moq_string *dst); int32_t moq_broadcast_request_serve(uint32_t request, uint32_t broadcast); int32_t moq_broadcast_request_route(uint32_t request, const moq_route_options *options); diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index 78b8ad0719c..fbd4846b87c 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -970,7 +970,7 @@ pub struct moq_section { /// How a route advertises itself: its visibility at creation, a static cost and, optionally, /// a stable instance. /// -/// Pass one to [moq_origin_route], [moq_origin_route_prefix], or [moq_broadcast_request_route]. +/// Pass one to [moq_origin_route], [moq_origin_claim], or [moq_broadcast_request_route]. /// The hop chain is the origin's to build, so a local publisher cannot claim relay hops it /// never took. Zeroed (or NULL) is the default: visible at once, cost 0, under a fresh /// instance. `instance` is borrowed for the duration of the call. @@ -995,8 +995,8 @@ pub struct moq_route_options { /// Which run of a stable `instance` this is: only its highest epoch is eligible, cheaper /// or not. Ignored without one. pub epoch: u64, - /// Create the route hidden: it exists for nobody until [moq_route_announce]. For a - /// publisher that fills its catalog first. + /// Create the route or claim hidden: it exists for nobody until [moq_route_announce] or + /// [moq_claim_announce]. For a publisher that fills its catalog first. pub hidden: bool, } @@ -2167,29 +2167,29 @@ pub unsafe extern "C" fn moq_origin_route( }) } -/// Create a route over `prefix` that serves the requests beneath it. +/// Claim `prefix` on an origin, serving the requests beneath it. /// -/// A route claims `prefix` and every path beneath it (the empty prefix claims +/// A claim covers `prefix` and every path beneath it (the empty prefix claims /// every path). A service that only serves some of them advertises the /// covering prefix and rejects the rest as they are requested. NULL `options` is the /// default. /// -/// `on_request` is required: a NULL callback is refused before the route is advertised. +/// `on_request` is required: a NULL callback is refused before the claim is advertised. /// It is invoked with a positive request handle for each pending broadcast (answer it with /// [moq_broadcast_request_serve], [moq_broadcast_request_route], or /// [moq_broadcast_request_reject]), then exactly once more with a terminal code: `0` -/// (stopped cleanly, after [moq_route_free] or the origin closing) or a negative error. +/// (stopped cleanly, after [moq_claim_free] or the origin closing) or a negative error. /// After the terminal (`<= 0`) callback, `user_data` is never touched again. /// -/// Returns a positive route handle on success, or a negative code on failure. +/// Returns a positive claim handle on success, or a negative code on failure. /// /// # Safety /// - The caller must ensure that prefix is a valid pointer to prefix_len bytes of data. /// - `options` may be NULL, or must point at a readable [moq_route_options]. -/// - `on_request` must be non-NULL; a missing callback is refused before the route is advertised. +/// - `on_request` must be non-NULL; a missing callback is refused before the claim is advertised. /// - The caller must keep `user_data` valid until the terminal (`<= 0`) `on_request` callback. #[unsafe(no_mangle)] -pub unsafe extern "C" fn moq_origin_route_prefix( +pub unsafe extern "C" fn moq_origin_claim( origin: u32, prefix: *const c_char, prefix_len: usize, @@ -2202,15 +2202,14 @@ pub unsafe extern "C" fn moq_origin_route_prefix( let prefix = unsafe { ffi::parse_str(prefix, prefix_len)? }; let options = unsafe { parse_route_options(options)? }; let on_request = unsafe { ffi::OnStatus::new(user_data, on_request)? }; - State::lock().origin.route_prefix(origin, prefix, options, on_request) + State::lock().origin.claim(origin, prefix, options, on_request) }) } -/// The broadcast an exact route owns, to fill with the `moq_publish_*` functions. +/// The broadcast a route owns, to fill with the `moq_publish_*` functions. /// -/// Returns the same positive broadcast handle on every call, or a negative code: a prefix -/// route owns none (`MOQ_ERROR_BROADCAST_NOT_FOUND`), and neither does a route whose -/// broadcast [moq_publish_close] ended. +/// Returns the same positive broadcast handle on every call, or a negative code: +/// `MOQ_ERROR_BROADCAST_NOT_FOUND` once [moq_publish_close] ended the broadcast. #[unsafe(no_mangle)] pub extern "C" fn moq_route_broadcast(route: u32) -> i32 { ffi::enter(move || { @@ -2226,11 +2225,10 @@ pub extern "C" fn moq_route_broadcast(route: u32) -> i32 { /// The stream a route serves now. /// -/// Named options keep one instance. Unnamed, a prefix route moves to a fresh one each time a -/// job holding its current one ends. A route from [moq_broadcast_request_route] takes its -/// prefix route's current one when it first announces or when this first reads it. Read first, +/// Named options keep one instance. A route from [moq_broadcast_request_route] takes its +/// claim's current one when it first announces or when this first reads it. Read first, /// the job announces under it, and [moq_route_announce] fails with an unroutable error once the -/// prefix route has moved past it, so a signer built from it stays valid. +/// claim has moved past it, so a signer built from it stays valid. /// Withdrawing and announcing again keep it. The destination borrows the route's storage /// until the next [moq_route_instance] on the route or [moq_route_free]. /// @@ -2251,7 +2249,7 @@ pub unsafe extern "C" fn moq_route_instance(route: u32, dst: *mut moq_string) -> /// /// A route from [moq_broadcast_request_route] also answers the requesters waiting on its /// path. Fails once its broadcast closed, and when a request's route can never announce -/// because the request was released or its prefix route retracted meanwhile. +/// because the request was released or its claim retracted meanwhile. /// /// Returns zero on success, or a negative code on failure. #[unsafe(no_mangle)] @@ -2292,10 +2290,7 @@ pub extern "C" fn moq_route_set_cost(route: u32, cost: u64) -> i32 { /// Release a route handle, retracting the route. /// -/// An exact route's broadcast handle stays the caller's until [moq_publish_close]. A prefix -/// route stops serving: requests not yet delivered are rejected, and its `on_request` -/// callback fires once more with a terminal `0`, which is where `user_data` should be -/// released. +/// The broadcast handle stays the caller's until [moq_publish_close]. /// /// Returns zero on success, or a negative code if the handle is unknown. #[unsafe(no_mangle)] @@ -2309,7 +2304,81 @@ pub extern "C" fn moq_route_free(route: u32) -> i32 { }) } -/// The path of a broadcast request delivered to a [moq_origin_route_prefix] callback. +/// The stream a claim serves now. +/// +/// Named options keep one instance. Unnamed, the claim moves to a fresh one each time a job +/// holding its current one ends. The destination borrows the claim's storage until the next +/// [moq_claim_instance] on the claim or [moq_claim_free]. +/// +/// Returns zero on success, or a negative code on failure. +/// +/// # Safety +/// - `dst` must point at a writable [moq_string]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_claim_instance(claim: u32, dst: *mut moq_string) -> i32 { + ffi::enter(move || { + let claim = ffi::parse_id(claim)?; + let dst = unsafe { dst.as_mut() }.ok_or(Error::InvalidPointer)?; + State::lock().origin.claim_instance(claim, dst) + }) +} + +/// Make a claim visible, or keep it so. +/// +/// Returns zero on success, or a negative code on failure. +#[unsafe(no_mangle)] +pub extern "C" fn moq_claim_announce(claim: u32) -> i32 { + ffi::enter(move || { + let claim = ffi::parse_id(claim)?; + State::lock().origin.claim_with(claim, |claim| claim.announce()) + }) +} + +/// Hide a claim from everyone, keeping its instance. +/// +/// Requests beneath it are rejected meanwhile, and [moq_claim_announce] brings it back. +/// Returns zero on success, or a negative code on failure. +#[unsafe(no_mangle)] +pub extern "C" fn moq_claim_withdraw(claim: u32) -> i32 { + ffi::enter(move || { + let claim = ffi::parse_id(claim)?; + State::lock().origin.claim_with(claim, |claim| { + claim.withdraw(); + Ok(()) + }) + }) +} + +/// Re-price a claim in place: lower wins among routes covering the same prefix. +/// +/// A hidden claim keeps the price for when it next announces. Returns zero on success, or +/// a negative code on failure. +#[unsafe(no_mangle)] +pub extern "C" fn moq_claim_set_cost(claim: u32, cost: u64) -> i32 { + ffi::enter(move || { + let claim = ffi::parse_id(claim)?; + State::lock().origin.claim_with(claim, |claim| claim.set_cost(cost)) + }) +} + +/// Release a claim handle, retracting the claim. +/// +/// Requests not yet delivered are rejected, and its `on_request` callback fires once more +/// with a terminal `0`, which is where `user_data` should be released. +/// +/// Returns zero on success, or a negative code if the handle is unknown. +#[unsafe(no_mangle)] +pub extern "C" fn moq_claim_free(claim: u32) -> i32 { + ffi::enter(move || { + let claim = ffi::parse_id(claim)?; + // Dropped outside the lock: retracting refuses the requests still waiting. + let claim = State::lock().origin.claim_take(claim)?; + drop(claim); + Ok(()) + }) +} + +/// The path of a broadcast request delivered to a [moq_origin_claim] callback. /// /// The destination borrows the request's storage: copy it out before /// [moq_broadcast_request_serve], [moq_broadcast_request_route], @@ -2328,11 +2397,11 @@ pub unsafe extern "C" fn moq_broadcast_request_path(request: u32, dst: *mut moq_ }) } -/// Serve a held consumer under the prefix route's instance without announcing an exact route. +/// Serve a held consumer under the claim's instance without announcing an exact route. /// /// Every answer at this path must continue the same sequences and bytes. Start a new -/// prefix route for different content, or route a job, whose end moves the prefix route to -/// another instance. +/// claim for different content, or route a job, whose end moves the claim to another +/// instance. /// Consumes the request handle; the consumer remains owned by the caller. /// Returns zero on success, or a negative error. #[unsafe(no_mangle)] @@ -2353,11 +2422,11 @@ pub extern "C" fn moq_broadcast_request_serve(request: u32, broadcast: u32) -> i /// Answer a broadcast request with the path's own exact route, owning a new broadcast. /// /// Consumes the request handle and returns a positive route handle, or a negative error. -/// Unless `options` names an instance, the route takes the one its prefix route lends when -/// it first announces or [moq_route_instance] first reads it, so readers that resolved the path through the prefix route continue -/// on it; its end then moves the prefix route to a fresh instance, so a job that restarts is -/// a new stream. A prefix route that names its instance lends none, and the route mints its -/// own. Created visible, it announces now and answers the waiting requesters; +/// Unless `options` names an instance, the route takes the one its claim lends when it first +/// announces or [moq_route_instance] first reads it, so readers that resolved the path through +/// the claim continue on it; its end then moves the claim to a fresh instance, so a job that +/// restarts is a new stream. A claim that names its instance lends none, and the route mints +/// its own. Created visible, it announces now and answers the waiting requesters; /// created hidden, they wait until [moq_route_announce], so the job can fill its catalog /// first, and freeing the route before then refuses them. Ending the route withdraws only /// this path. Unreadable `options` fail without consuming the request. @@ -2588,7 +2657,7 @@ pub extern "C" fn moq_origin_follow_cancel(task: u32) -> i32 { /// Owns discovery of the path and retries route churn while resolving one publisher instance. /// It fails as unroutable once discovery has synced without a covering route, including a /// hidden route not announced yet. No separate announcement stream is needed. -/// Serve on-demand paths with [moq_origin_route_prefix]. +/// Serve on-demand paths with [moq_origin_claim]. /// /// `instance` is the only stream to accept, or NULL (or empty) for any. A request pinned to an /// instance that does not serve the path is unroutable. diff --git a/rs/moq-c/src/origin.rs b/rs/moq-c/src/origin.rs index bf65671d026..216a90d27c3 100644 --- a/rs/moq-c/src/origin.rs +++ b/rs/moq-c/src/origin.rs @@ -25,17 +25,20 @@ pub struct Origin { /// Pending requests. Close signals shutdown; the task delivers a final callback, then removes itself. consume_task: NonZeroSlab, - /// Routes created on an origin, retracted when freed. + /// Exact routes created on an origin, retracted when freed. routes: NonZeroSlab, + /// Claims created on an origin, retracted when freed. + claims: NonZeroSlab, + /// Follows. Close signals shutdown; the task delivers its end event, then removes itself. follow_task: NonZeroSlab>, - /// Request deliveries of prefix routes. Freeing the route signals shutdown; the task - /// delivers a final callback, then removes itself. - route_requests: NonZeroSlab, + /// Request deliveries of claims. Freeing the claim signals shutdown; the task delivers a + /// final callback, then removes itself. + claim_requests: NonZeroSlab, - /// Broadcast requests delivered to a prefix route's callback, freed after serve/route/reject. + /// Broadcast requests delivered to a claim's callback, freed after serve/route/reject. broadcast_request: NonZeroSlab<(moq_net::origin::Request, crate::ffi::Background)>, } @@ -148,68 +151,21 @@ impl State { } struct RouteEntry { + inner: moq_net::origin::Route, driver: crate::ffi::Background, /// The instance last read, borrowed by [Origin::route_instance]. instance: String, - /// An exact route with its broadcast fill handle, or a prefix claim with its request - /// delivery task. - kind: RouteKind, -} - -enum RouteKind { - Exact { - route: moq_net::origin::Route, - broadcast: Id, - }, - Prefix { - claim: moq_net::origin::Claim, - requests: Id, - }, -} - -/// The native route behind a handle, as [Origin::route_with] lends it. -pub enum Held<'a> { - Route(&'a moq_net::origin::Route), - Claim(&'a moq_net::origin::Claim), + /// The fill handle of the route's broadcast. + broadcast: Id, } -impl Held<'_> { - pub fn instance(&self) -> moq_net::Instance { - match self { - Self::Route(route) => route.instance(), - Self::Claim(claim) => claim.instance(), - } - } - - pub fn announce(&self) -> Result<(), moq_net::Error> { - match self { - Self::Route(route) => route.announce(), - Self::Claim(claim) => claim.announce(), - } - } - - pub fn withdraw(&self) { - match self { - Self::Route(route) => route.withdraw(), - Self::Claim(claim) => claim.withdraw(), - } - } - - pub fn set_cost(&self, cost: u64) -> Result<(), moq_net::Error> { - match self { - Self::Route(route) => route.set_cost(cost), - Self::Claim(claim) => claim.set_cost(cost), - } - } -} - -impl RouteEntry { - fn held(&self) -> Held<'_> { - match &self.kind { - RouteKind::Exact { route, .. } => Held::Route(route), - RouteKind::Prefix { claim, .. } => Held::Claim(claim), - } - } +struct ClaimEntry { + inner: moq_net::origin::Claim, + driver: crate::ffi::Background, + /// The instance last read, borrowed by [Origin::claim_instance]. + instance: String, + /// The claim's request delivery task. + requests: Id, } impl Origin { @@ -462,15 +418,16 @@ impl Origin { ) -> Result { // Read only on request: reading a hidden job's instance binds it. self.routes.insert(RouteEntry { + inner: route, instance: String::new(), driver, - kind: RouteKind::Exact { route, broadcast }, + broadcast, }) } - /// Create a prefix route, delivering each request beneath it as a broadcast-request handle - /// via `on_request`. - pub fn route_prefix( + /// Claim a prefix, delivering each request beneath it as a broadcast-request handle via + /// `on_request`. + pub fn claim( &mut self, origin: Id, prefix: &str, @@ -479,30 +436,31 @@ impl Origin { ) -> Result { let origin = self.get(origin)?; let driver = origin.driver.clone(); - let result = origin.producer.route_prefix(prefix, options); + let result = origin.producer.claim(prefix, options); driver.check()?; let claim = result?; let instance = claim.instance().to_string(); - // The route first, so the delivery task finds it once it runs; it cannot lock the + // The claim first, so the delivery task finds it once it runs; it cannot lock the // state before this call returns. let (task, close) = Task::new(on_request); - let requests = self.route_requests.insert(task)?; - let id = match self.routes.insert(RouteEntry { + let requests = self.claim_requests.insert(task)?; + let id = match self.claims.insert(ClaimEntry { + inner: claim, driver: driver.clone(), instance, - kind: RouteKind::Prefix { claim, requests }, + requests, }) { Ok(id) => id, Err(err) => { - self.route_requests.remove(requests); + self.claim_requests.remove(requests); return Err(err); } }; tokio::spawn(async move { let res = crate::ffi::run(driver.watch(Self::run_requests(id, on_request, close, driver.clone()))).await; - let entry = State::lock().origin.route_requests.remove(requests); + let entry = State::lock().origin.claim_requests.remove(requests); if let Some(entry) = entry { entry.callback.call(res); } @@ -512,7 +470,7 @@ impl Origin { } async fn run_requests( - route: Id, + claim: Id, callback: OnStatus, mut close: oneshot::Receiver<()>, driver: crate::ffi::Background, @@ -523,9 +481,9 @@ impl Origin { _ = &mut close => return Ok(()), request = kio::wait(|waiter| { let state = State::lock(); - match state.origin.routes.get(route).map(|entry| &entry.kind) { - Some(RouteKind::Prefix { claim, .. }) => claim.poll_requested(waiter), - _ => std::task::Poll::Ready(None), + match state.origin.claims.get(claim) { + Some(entry) => entry.inner.poll_requested(waiter), + None => std::task::Poll::Ready(None), } }) => match request { Some(request) => request, @@ -550,25 +508,26 @@ impl Origin { } /// Run `f` against the route, then check its origin is still healthy. - pub fn route_with(&self, route: Id, f: impl FnOnce(Held<'_>) -> Result) -> Result { + pub fn route_with( + &self, + route: Id, + f: impl FnOnce(&moq_net::origin::Route) -> Result, + ) -> Result { let entry = self.route_entry(route)?; - let result = f(entry.held()); + let result = f(&entry.inner); entry.driver.check()?; Ok(result?) } - /// An exact route's broadcast fill handle, or [`Error::BroadcastNotFound`] on a prefix route. + /// The route's broadcast fill handle. pub fn route_broadcast(&self, route: Id) -> Result { - match self.route_entry(route)?.kind { - RouteKind::Exact { broadcast, .. } => Ok(broadcast), - RouteKind::Prefix { .. } => Err(Error::BroadcastNotFound), - } + Ok(self.route_entry(route)?.broadcast) } pub fn route_instance(&mut self, route: Id, dst: &mut moq_string) -> Result<(), Error> { let entry = self.routes.get_mut(route).ok_or(Error::NotFound)?; entry.driver.check()?; - entry.instance = entry.held().instance().to_string(); + entry.instance = entry.inner.instance().to_string(); *dst = moq_string { data: entry.instance.as_ptr().cast::(), len: entry.instance.len(), @@ -576,15 +535,42 @@ impl Origin { Ok(()) } - /// Release a route handle and stop a prefix route's request delivery, returning the route - /// for the caller to retract by dropping it. - pub fn route_take(&mut self, route: Id) -> Result, Error> { - let entry = self.routes.remove(route).ok_or(Error::NotFound)?; - if let RouteKind::Prefix { requests, .. } = entry.kind { - // Already gone once the origin closed and the task delivered its terminal callback. - let _ = self.route_requests.close(requests, Error::NotFound); - } - Ok(entry.kind) + /// Release a route handle, returning the route for the caller to retract by dropping it. + pub fn route_take(&mut self, route: Id) -> Result { + Ok(self.routes.remove(route).ok_or(Error::NotFound)?.inner) + } + + /// Run `f` against the claim, then check its origin is still healthy. + pub fn claim_with( + &self, + claim: Id, + f: impl FnOnce(&moq_net::origin::Claim) -> Result, + ) -> Result { + let entry = self.claims.get(claim).ok_or(Error::NotFound)?; + entry.driver.check()?; + let result = f(&entry.inner); + entry.driver.check()?; + Ok(result?) + } + + pub fn claim_instance(&mut self, claim: Id, dst: &mut moq_string) -> Result<(), Error> { + let entry = self.claims.get_mut(claim).ok_or(Error::NotFound)?; + entry.driver.check()?; + entry.instance = entry.inner.instance().to_string(); + *dst = moq_string { + data: entry.instance.as_ptr().cast::(), + len: entry.instance.len(), + }; + Ok(()) + } + + /// Release a claim handle and stop its request delivery, returning the claim for the + /// caller to retract by dropping it. + pub fn claim_take(&mut self, claim: Id) -> Result { + let entry = self.claims.remove(claim).ok_or(Error::NotFound)?; + // Already gone once the origin closed and the task delivered its terminal callback. + let _ = self.claim_requests.close(entry.requests, Error::NotFound); + Ok(entry.inner) } pub fn broadcast_request_path(&self, request: Id, dst: &mut crate::moq_string) -> Result<(), Error> { diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index ff4d8a68f52..4992beb2c5c 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -75,11 +75,19 @@ fn hidden() -> moq_route_options { /// The instance a route serves. fn instance_of(route: u32) -> String { + read_instance(|dst| unsafe { moq_route_instance(route, dst) }) +} + +fn claim_instance_of(claim: u32) -> String { + read_instance(|dst| unsafe { moq_claim_instance(claim, dst) }) +} + +fn read_instance(read: impl FnOnce(&mut moq_string) -> i32) -> String { let mut dst = moq_string { data: std::ptr::null(), len: 0, }; - assert_eq!(unsafe { moq_route_instance(route, &mut dst) }, 0); + assert_eq!(read(&mut dst), 0); unsafe { std::str::from_utf8(std::slice::from_raw_parts(dst.data.cast::(), dst.len)) } .unwrap() .to_string() @@ -4292,10 +4300,10 @@ fn a_new_route_at_a_path_restarts() { assert_eq!(moq_origin_close(origin), 0); } -/// Create a prefix route over `prefix` delivering its requests through `cb`. -fn route_prefix(origin: u32, prefix: &[u8], cb: &Callback) -> u32 { +/// Claim `prefix`, delivering its requests through `cb`. +fn claim(origin: u32, prefix: &[u8], cb: &Callback) -> u32 { id(unsafe { - moq_origin_route_prefix( + moq_origin_claim( origin, prefix.as_ptr() as *const c_char, prefix.len(), @@ -4310,8 +4318,7 @@ fn route_prefix(origin: u32, prefix: &[u8], cb: &Callback) -> u32 { fn dynamic_serves_a_request_under_a_prefix() { let origin = id(moq_origin_create()); let cb = Callback::new(); - let dynamic = route_prefix(origin, b"live", &cb); - assert!(moq_route_broadcast(dynamic) < 0, "a prefix route owns no broadcast"); + let dynamic = claim(origin, b"live", &cb); let path = b"live/cam"; let req_cb = Callback::new(); @@ -4348,26 +4355,26 @@ fn dynamic_serves_a_request_under_a_prefix() { crate::error::MOQ_ERROR_UTF8 ); - // A hidden job route answers nobody until it announces, under the instance its prefix - // route lends. + // A hidden job route answers nobody until it announces, under the instance its claim + // lends. let job = id(unsafe { moq_broadcast_request_route(request, &hidden()) }); assert!( unsafe { moq_broadcast_request_route(request, std::ptr::null()) } < 0, "request is consumed" ); - let lent = instance_of(dynamic); + let lent = claim_instance_of(dynamic); assert_eq!(instance_of(job), lent); let served = id(moq_route_broadcast(job)); assert_eq!(moq_route_announce(job), 0); assert!(req_cb.recv() > 0); req_cb.recv_terminal(); - // The answer's route is the job's to withdraw, which moves the prefix route on. + // The answer's route is the job's to withdraw, which moves the claim on. assert_eq!(moq_route_withdraw(job), 0); - assert_ne!(instance_of(dynamic), lent); + assert_ne!(claim_instance_of(dynamic), lent); assert_eq!(moq_route_free(job), 0); - assert_eq!(moq_route_free(dynamic), 0); - assert!(moq_route_free(dynamic) < 0, "double-free should fail"); + assert_eq!(moq_claim_free(dynamic), 0); + assert!(moq_claim_free(dynamic) < 0, "double-free should fail"); assert_eq!(cb.recv_terminal(), 0); assert_eq!(moq_publish_close(served), 0); assert_eq!(moq_origin_close(origin), 0); @@ -4379,7 +4386,7 @@ fn dynamic_serves_a_held_consumer_without_taking_its_handle() { let broadcast = publish_broadcast(origin, b"source"); let held = consume_local(broadcast); let cb = Callback::new(); - let dynamic = route_prefix(origin, b"live", &cb); + let dynamic = claim(origin, b"live", &cb); let result = Callback::new(); let _task = id(unsafe { moq_origin_request( @@ -4399,7 +4406,7 @@ fn dynamic_serves_a_held_consumer_without_taking_its_handle() { assert_eq!(moq_consume_close(held), 0, "source handle remains caller-owned"); result.recv_terminal(); assert_eq!(moq_consume_close(served), 0); - assert_eq!(moq_route_free(dynamic), 0); + assert_eq!(moq_claim_free(dynamic), 0); cb.recv_terminal(); assert_eq!(moq_publish_close(broadcast), 0); assert_eq!(moq_origin_close(origin), 0); @@ -4410,7 +4417,7 @@ fn dynamic_refuses_a_missing_callback() { let origin = id(moq_origin_create()); let prefix = b"live"; let code = unsafe { - moq_origin_route_prefix( + moq_origin_claim( origin, prefix.as_ptr() as *const c_char, prefix.len(), @@ -5700,7 +5707,7 @@ fn follow_delivers_a_takeover_once(dynamic_at: &str) { .origin .get(origin) .unwrap() - .route_prefix(dynamic_at, moq_net::origin::RouteOptions::default()) + .claim(dynamic_at, moq_net::origin::RouteOptions::default()) .unwrap() }; let cb = Callback::new(); @@ -5824,7 +5831,7 @@ fn serve_dynamic(origin: u32, prefix: &str) -> moq_net::origin::Claim { .origin .get(origin) .unwrap() - .route_prefix(prefix, moq_net::origin::RouteOptions::default()) + .claim(prefix, moq_net::origin::RouteOptions::default()) .unwrap() } diff --git a/rs/moq-cli/src/archive.rs b/rs/moq-cli/src/archive.rs index a728a8c0b77..f99cb0bdd92 100644 --- a/rs/moq-cli/src/archive.rs +++ b/rs/moq-cli/src/archive.rs @@ -463,7 +463,7 @@ mod tests { }; let origin = moq_tokio::origin::spawn(); let claim = origin - .route_prefix("live/a", moq_net::origin::RouteOptions::default()) + .claim("live/a", moq_net::origin::RouteOptions::default()) .unwrap(); let recording = tokio::spawn(export(origin.consume(), "live".into(), args)); diff --git a/rs/moq-cli/src/play/media.rs b/rs/moq-cli/src/play/media.rs index 760a2a4295a..b4c02fa339a 100644 --- a/rs/moq-cli/src/play/media.rs +++ b/rs/moq-cli/src/play/media.rs @@ -1914,7 +1914,7 @@ mod tests { async fn a_refused_broadcast_ends_the_player() { let origin = moq_tokio::origin::spawn(); let handler = origin - .route_prefix("", moq_net::origin::RouteOptions::default()) + .claim("", moq_net::origin::RouteOptions::default()) .unwrap(); let recorder = Recorder::default(); let player = tokio::spawn(media(&origin, Duration::from_millis(50), recorder.clone()).run()); @@ -2077,7 +2077,7 @@ mod tests { kio::clock::sleep(Duration::from_secs(60)).await; let pool = origin - .route_prefix("", moq_net::origin::RouteOptions::default()) + .claim("", moq_net::origin::RouteOptions::default()) .unwrap(); drop(exact); let (served, served_catalog, mut new) = answer(&pool).await; @@ -2113,7 +2113,7 @@ mod tests { exact.withdraw(); let pool = origin - .route_prefix("", moq_net::origin::RouteOptions::default()) + .claim("", moq_net::origin::RouteOptions::default()) .unwrap(); let (mirror, mirror_catalog, mut copy) = answer(&pool).await; for index in 50..60 { diff --git a/rs/moq-cli/src/report.rs b/rs/moq-cli/src/report.rs index 4617dc16ebd..4a9bd05814f 100644 --- a/rs/moq-cli/src/report.rs +++ b/rs/moq-cli/src/report.rs @@ -689,7 +689,7 @@ mod tests { tokio::spawn(write_echo(origin.consume(), String::new(), out)); let claim = origin - .route_prefix("viewer.echo", moq_net::origin::RouteOptions::default()) + .claim("viewer.echo", moq_net::origin::RouteOptions::default()) .unwrap(); kio::clock::timeout(Duration::from_secs(1), claim.requested()) .await diff --git a/rs/moq-cli/tests/integration/instances.rs b/rs/moq-cli/tests/integration/instances.rs index 9b955159da5..c73a8f7d582 100644 --- a/rs/moq-cli/tests/integration/instances.rs +++ b/rs/moq-cli/tests/integration/instances.rs @@ -301,7 +301,7 @@ struct Job { impl Worker { fn new(origin: &origin::Producer) -> Self { - let claim = origin.route_prefix("live", origin::RouteOptions::default()).unwrap(); + let claim = origin.claim("live", origin::RouteOptions::default()).unwrap(); let jobs = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); let (handler, answered) = (claim.clone(), jobs.clone()); tokio::spawn(async move { diff --git a/rs/moq-ffi/src/bench.rs b/rs/moq-ffi/src/bench.rs index 8e7ae89e77d..a76863573e9 100644 --- a/rs/moq-ffi/src/bench.rs +++ b/rs/moq-ffi/src/bench.rs @@ -253,7 +253,7 @@ async fn rust_ffi() { }, ) .unwrap(); - let broadcast = route.broadcast().unwrap(); + let broadcast = route.broadcast(); let timed = MoqTrackInfo { priority: 0, max_age: None, diff --git a/rs/moq-ffi/src/origin.rs b/rs/moq-ffi/src/origin.rs index c34d195d8ab..b6d400ec04c 100644 --- a/rs/moq-ffi/src/origin.rs +++ b/rs/moq-ffi/src/origin.rs @@ -38,7 +38,7 @@ pub struct MoqAnnounceConfig { /// claim relay hops it never took. #[derive(Clone, Debug, Default, PartialEq, Eq, uniffi::Record)] pub struct MoqRouteOptions { - /// Create the route hidden: it exists for nobody until [`MoqRoute::announce`]. For a + /// Create the route or claim hidden: it exists for nobody until it announces. For a /// publisher that fills its catalog first. #[uniffi(default = false)] pub hidden: bool, @@ -81,8 +81,8 @@ impl TryFrom for moq_net::origin::RouteOptions { /// /// Carried by `MoqAnnounceConsumer` events. A route claims capability, not /// inventory: by convention a publisher creates each broadcast's exact route, -/// so subscribers can enumerate broadcasts, while a service creates a prefix route -/// with `MoqOriginProducer::route_prefix` and answers whatever is requested beneath it. +/// so subscribers can enumerate broadcasts, while a service claims a prefix +/// with `MoqOriginProducer::claim` and answers whatever is requested beneath it. #[derive(Clone, Debug, PartialEq, Eq, uniffi::Record)] pub struct MoqRouteInfo { /// Hop ids of the relay hops the route traversed, oldest first. 0 is the @@ -140,25 +140,38 @@ pub struct MoqAnnounceConsumer { reads: Polled, } -/// A route on an origin: an exact route owning one broadcast, or a prefix route yielding -/// the requests beneath it. +/// An exact route on an origin, owning one broadcast. /// -/// Dropping or cancelling it retracts the route, as does closing an exact route's -/// broadcast; a broadcast handle alone does not keep it announced. It keeps its -/// origin running after every `MoqOriginProducer` is gone. +/// Dropping or cancelling it retracts the route, as does closing its broadcast; a broadcast +/// handle alone does not keep it announced. It keeps its origin running after every +/// `MoqOriginProducer` is gone. #[derive(uniffi::Object)] pub struct MoqRoute { /// The route itself, released on cancel. - reads: Polled, - /// An exact route's broadcast, wrapped once so every caller shares its catalog. - broadcast: Option>, + reads: Polled, + /// The route's broadcast, wrapped once so every caller shares its catalog. + broadcast: Arc, /// The instance last read, reported once the route is cancelled. instance: std::sync::Mutex, driver: Background, } +/// A prefix route on an origin: a claim that every path beneath a prefix can be served, +/// yielding each request as it arrives. +/// +/// Dropping or cancelling it retracts the claim and rejects the requests still waiting. It +/// keeps its origin running after every `MoqOriginProducer` is gone. +#[derive(uniffi::Object)] +pub struct MoqClaim { + /// The claim itself, released on cancel. + reads: Polled, + /// The instance last read, reported once the claim is cancelled. + instance: std::sync::Mutex, + driver: Background, +} + #[derive(uniffi::Object)] -/// A pending broadcast request on a prefix route, answered by serving, routing, or rejecting it. +/// A pending broadcast request on a claim, answered by serving, routing, or rejecting it. pub struct MoqBroadcastRequest { inner: std::sync::Mutex>, driver: Background, @@ -320,27 +333,27 @@ impl MoqOriginProducer { /// [`MoqBroadcastProducer::close`] ends both. pub fn route(&self, path: String, options: MoqRouteOptions) -> Result, MoqError> { let _guard = crate::ffi::enter(); - let (options, visible) = MoqRoute::exact_options(options)?; + let (options, visible) = MoqRoute::options(options)?; self.inner.driver.check()?; // Surfaces Error::Unauthorized (out of scope) via the MoqError::Protocol conversion. let result = self.inner.route(path.as_str(), options); self.inner.driver.check()?; - Ok(Arc::new(MoqRoute::exact(result?, self.inner.driver.clone(), visible)?)) + Ok(Arc::new(MoqRoute::new(result?, self.inner.driver.clone(), visible)?)) } - /// Create a route over `prefix` that yields the requests beneath it. + /// Claim `prefix` and yield the requests beneath it. /// - /// A route claims `prefix` and every path beneath it (the empty prefix + /// A claim covers `prefix` and every path beneath it (the empty prefix /// claims every path). A service that only serves some of them advertises /// the covering prefix and rejects the rest as they are requested. Answer each - /// [`MoqRoute::requested`] request; hold the route while it should stay advertised. - pub fn route_prefix(&self, prefix: String, options: MoqRouteOptions) -> Result, MoqError> { + /// [`MoqClaim::requested`] request; hold the claim while it should stay advertised. + pub fn claim(&self, prefix: String, options: MoqRouteOptions) -> Result, MoqError> { let _guard = crate::ffi::enter(); let options = options.try_into()?; self.inner.driver.check()?; - let result = self.inner.route_prefix(prefix, options); + let result = self.inner.claim(prefix, options); self.inner.driver.check()?; - Ok(Arc::new(MoqRoute::prefix(result?, self.inner.driver.clone()))) + Ok(Arc::new(MoqClaim::new(result?, self.inner.driver.clone()))) } } @@ -412,61 +425,10 @@ impl MoqOriginConsumer { // ---- MoqRoute ---- -/// The native route a [`MoqRoute`] holds: an exact route or a prefix claim. -enum Held { - Route(moq_net::origin::Route), - Claim(moq_net::origin::Claim), -} - -impl Held { - fn instance(&self) -> moq_net::Instance { - match self { - Self::Route(route) => route.instance(), - Self::Claim(claim) => claim.instance(), - } - } - - fn is_announced(&self) -> bool { - match self { - Self::Route(route) => route.is_announced(), - Self::Claim(claim) => claim.is_announced(), - } - } - - fn announce(&self) -> Result<(), moq_net::Error> { - match self { - Self::Route(route) => route.announce(), - Self::Claim(claim) => claim.announce(), - } - } - - fn withdraw(&self) { - match self { - Self::Route(route) => route.withdraw(), - Self::Claim(claim) => claim.withdraw(), - } - } - - fn set_cost(&self, cost: u64) -> Result<(), moq_net::Error> { - match self { - Self::Route(route) => route.set_cost(cost), - Self::Claim(claim) => claim.set_cost(cost), - } - } - - /// A claim's next request; an exact route yields none. - fn poll_requested(&self, waiter: &kio::Waiter) -> Poll> { - match self { - Self::Route(_) => Poll::Ready(None), - Self::Claim(claim) => claim.poll_requested(waiter), - } - } -} - impl MoqRoute { - /// An exact route's native options, always hidden so [`Self::exact`] attaches the catalog + /// An exact route's native options, always hidden so [`Self::new`] attaches the catalog /// track before anyone can find the route, and whether the caller asked it visible. - fn exact_options(options: MoqRouteOptions) -> Result<(moq_net::origin::RouteOptions, bool), MoqError> { + fn options(options: MoqRouteOptions) -> Result<(moq_net::origin::RouteOptions, bool), MoqError> { let visible = !options.hidden; let options = MoqRouteOptions { hidden: true, @@ -476,38 +438,29 @@ impl MoqRoute { Ok((options, visible)) } - /// Wrap an exact route created hidden, attaching the catalog track every FFI broadcast + /// Wrap a route created hidden, attaching the catalog track every FFI broadcast /// carries, then announce it when `visible`, so a reader that finds it finds the catalog. - fn exact(route: moq_net::origin::Route, driver: Background, visible: bool) -> Result { + fn new(route: moq_net::origin::Route, driver: Background, visible: bool) -> Result { let broadcast = MoqBroadcastProducer::from_inner(route.broadcast().clone(), driver.clone())?; if visible { route.announce()?; } - Ok(Self::new(Held::Route(route), Some(Arc::new(broadcast)), driver)) - } - - fn prefix(claim: moq_net::origin::Claim, driver: Background) -> Self { - Self::new(Held::Claim(claim), None, driver) - } - - fn new(route: Held, broadcast: Option>, driver: Background) -> Self { // Reading a hidden job's instance binds it, so one is cached only once it announces or // is read. - let instance = if route.is_announced() || broadcast.is_none() { - route.instance().to_string() - } else { - String::new() + let instance = match route.is_announced() { + true => route.instance().to_string(), + false => String::new(), }; - Self { + Ok(Self { instance: std::sync::Mutex::new(instance), reads: Polled::new(route).supervised(driver.clone()), - broadcast, + broadcast: Arc::new(broadcast), driver, - } + }) } /// Run `f` against the route, refused with `Cancelled` once it was cancelled. - fn with(&self, f: impl FnOnce(&Held) -> Result) -> Result { + fn with(&self, f: impl FnOnce(&moq_net::origin::Route) -> Result) -> Result { let _guard = crate::ffi::enter(); self.driver.check()?; let result = self.reads.peek(f).ok_or(MoqError::Cancelled)?; @@ -518,23 +471,18 @@ impl MoqRoute { #[uniffi::export] impl MoqRoute { - /// The broadcast this exact route owns, to fill with tracks. - /// - /// Errors on a prefix route, which owns none: answer its requests instead. - pub fn broadcast(&self) -> Result, MoqError> { - self.broadcast.clone().ok_or_else(|| MoqError::Internal { - reason: "a prefix route owns no broadcast; answer its requests".into(), - }) + /// The broadcast this route owns, to fill with tracks. + pub fn broadcast(&self) -> Arc { + self.broadcast.clone() } /// The stream this route serves now, or once cancelled, the last one it reported or /// announced under (empty for a hidden route that did neither). /// - /// Named options keep one instance. Unnamed, a prefix route moves to a fresh one each - /// time a job holding its current one ends. A job's route takes its prefix route's current - /// one when it first announces or when this first reads it. Read first, the job announces - /// under it, and [`MoqRoute::announce`] fails with `Unroutable` once the prefix route has - /// moved past it, so a signer built from it stays valid. + /// Named options keep one instance. A job's route takes its claim's current one when it + /// first announces or when this first reads it. Read first, the job announces under it, + /// and [`MoqRoute::announce`] fails with `Unroutable` once the claim has moved past it, so + /// a signer built from it stays valid. /// /// Named `instance_id` rather than `instance` because the generated C and C++ /// objects keep their handle in a private field named `instance`; the wrappers @@ -552,7 +500,7 @@ impl MoqRoute { /// A route created by [`MoqBroadcastRequest::route`] also answers the requesters waiting /// on its path. Errors with `Closed` once its broadcast closed, and with a protocol /// `Unroutable` when a request's route can never announce because the request was - /// released or its prefix route retracted meanwhile. + /// released or its claim retracted meanwhile. pub fn announce(&self) -> Result<(), MoqError> { let instance = self.with(|route| { route.announce()?; @@ -578,24 +526,95 @@ impl MoqRoute { self.with(|route| route.set_cost(cost)) } - /// Wait for the next broadcast a consumer requests beneath this prefix route. + /// Retract the route and release it here, not when the handle is. + /// + /// Terminal: later calls fail with `Cancelled`. The broadcast lives on for its other + /// handles until [`MoqBroadcastProducer::close`]. + pub fn cancel(&self) { + self.reads.cancel(); + } +} + +// ---- MoqClaim ---- + +impl MoqClaim { + fn new(claim: moq_net::origin::Claim, driver: Background) -> Self { + Self { + instance: std::sync::Mutex::new(claim.instance().to_string()), + reads: Polled::new(claim).supervised(driver.clone()), + driver, + } + } + + /// Run `f` against the claim, refused with `Cancelled` once it was cancelled. + fn with(&self, f: impl FnOnce(&moq_net::origin::Claim) -> Result) -> Result { + let _guard = crate::ffi::enter(); + self.driver.check()?; + let result = self.reads.peek(f).ok_or(MoqError::Cancelled)?; + self.driver.check()?; + Ok(result?) + } +} + +#[uniffi::export] +impl MoqClaim { + /// The stream this claim serves now, or once cancelled, the last one it reported or + /// announced under. + /// + /// Named options keep one instance. Unnamed, the claim moves to a fresh one each time a + /// job holding its current one ends. + /// + /// Named `instance_id` rather than `instance` for the reason [`MoqRoute::instance_id`] + /// gives. + pub fn instance_id(&self) -> String { + let mut last = self.instance.lock().unwrap(); + if let Some(current) = self.reads.peek(|claim| claim.instance().to_string()) { + *last = current; + } + last.clone() + } + + /// Make the claim visible, or keep it so. + pub fn announce(&self) -> Result<(), MoqError> { + let instance = self.with(|claim| { + claim.announce()?; + Ok(claim.instance().to_string()) + })?; + *self.instance.lock().unwrap() = instance; + Ok(()) + } + + /// Hide the claim from everyone, keeping its instance: `announce` brings it back. + /// Requests beneath it are rejected meanwhile. + pub fn withdraw(&self) -> Result<(), MoqError> { + self.with(|claim| { + claim.withdraw(); + Ok(()) + }) + } + + /// Re-price the claim in place: lower wins among routes covering the same prefix. A + /// hidden claim keeps the price for when it next announces. + pub fn set_cost(&self, cost: u64) -> Result<(), MoqError> { + self.with(|claim| claim.set_cost(cost)) + } + + /// Wait for the next broadcast a consumer requests beneath this claim. /// /// Serve a held broadcast, route a new one, or reject the returned request; the requesting - /// consumer stays pending until then. Returns `None` once the origin closes, and at once on - /// an exact route, which yields no requests. + /// consumer stays pending until then. Returns `None` once the claim is retracted or the + /// origin closes. pub async fn requested(&self) -> Result>, MoqError> { let request = self .reads - .wait(|route, waiter| Poll::Ready(Ok(ready!(route.poll_requested(waiter))))) + .wait(|claim, waiter| Poll::Ready(Ok(ready!(claim.poll_requested(waiter))))) .await?; Ok(request.map(|request| Arc::new(MoqBroadcastRequest::new(request, self.driver.clone())))) } - /// Retract the route and release it here, not when the handle is. + /// Retract the claim and release it here, not when the handle is. /// - /// Terminal: pending requests are rejected and later calls fail with `Cancelled`. An exact - /// route's broadcast lives on for its other handles until - /// [`MoqBroadcastProducer::close`]. + /// Terminal: pending requests are rejected and later calls fail with `Cancelled`. pub fn cancel(&self) { self.reads.cancel(); } @@ -627,29 +646,29 @@ impl MoqBroadcastRequest { /// Answer with the path's own exact route, owning a new broadcast. /// - /// Unless `options` names an instance, the route takes the one its prefix route lends - /// when it first announces or [`MoqRoute::instance_id`] first reads it, so readers that resolved the path through the prefix route - /// continue on it; its end then moves the prefix route to a fresh instance, so a job that - /// restarts is a new stream. A prefix route that names its instance lends none, and the + /// Unless `options` names an instance, the route takes the one its claim lends when it + /// first announces or [`MoqRoute::instance_id`] first reads it, so readers that resolved + /// the path through the claim continue on it; its end then moves the claim to a fresh + /// instance, so a job that restarts is a new stream. A claim that names its instance lends none, and the /// route mints its own. Created visible, it announces now and answers the waiting /// requesters; created hidden, they wait until [`MoqRoute::announce`], so the job can /// fill its catalog first, and cancelling the route before then refuses them. Ending the /// route withdraws only this path. pub fn route(&self, options: MoqRouteOptions) -> Result, MoqError> { let _guard = crate::ffi::enter(); - let (options, visible) = MoqRoute::exact_options(options)?; + let (options, visible) = MoqRoute::options(options)?; self.driver.check()?; let request = self.take()?; let result = request.route(options); self.driver.check()?; - Ok(Arc::new(MoqRoute::exact(result?, self.driver.clone(), visible)?)) + Ok(Arc::new(MoqRoute::new(result?, self.driver.clone(), visible)?)) } - /// Serve a held broadcast under the prefix route's instance without announcing an exact route. + /// Serve a held broadcast under the claim's instance without announcing an exact route. /// /// Every answer at this path must continue the same sequences and bytes. Start a new - /// prefix route for different content, or route a job, whose end moves the prefix route - /// to another instance. + /// claim for different content, or route a job, whose end moves the claim to another + /// instance. pub fn serve(&self, broadcast: &Arc) -> Result<(), MoqError> { let _guard = crate::ffi::enter(); self.driver.check()?; @@ -736,8 +755,8 @@ mod supervision_tests { #[tokio::test] async fn serving_held_content_consumes_only_the_request() { let origin = MoqOriginProducer::new(Default::default()); - let requests = origin.route_prefix("room".into(), Default::default()).unwrap(); - let source = origin.route("source".into(), hidden()).unwrap().broadcast().unwrap(); + let requests = origin.claim("room".into(), Default::default()).unwrap(); + let source = origin.route("source".into(), hidden()).unwrap().broadcast(); let held = source.consume().unwrap(); let consumer = origin.consume(); let (resolved, ()) = tokio::join!(consumer.request("room/camera".into(), None), async { @@ -775,7 +794,7 @@ mod supervision_tests { driver: completion.clone(), }); let route = origin.route("retained".into(), hidden()).unwrap(); - let dynamic = route.broadcast().unwrap().requests().unwrap(); + let dynamic = route.broadcast().requests().unwrap(); drop(origin); *trigger .write() @@ -795,7 +814,7 @@ mod supervision_tests { inner, driver: completion.clone(), }); - let broadcast = origin.route("retained".into(), hidden()).unwrap().broadcast().unwrap(); + let broadcast = origin.route("retained".into(), hidden()).unwrap().broadcast(); // A dynamic handle outlives the consumed producer, so only an explicit close ends it. let _dynamic = broadcast.requests().unwrap(); let consumer = broadcast.state.lock().unwrap().as_ref().unwrap().broadcast.consume(); @@ -822,7 +841,7 @@ mod supervision_tests { // The route owns the broadcast, and it is the only handle that keeps the origin // running once the producer is gone. let route = origin.route("retained".into(), hidden()).unwrap(); - let broadcast = route.broadcast().unwrap(); + let broadcast = route.broadcast(); // One importer shares a timebase and one doesn't, so both reservation paths carry the driver. let timebase = MoqMediaTimebase::new(broadcast.clone()).unwrap(); let container = MoqMediaContainerProducer::new( @@ -867,7 +886,7 @@ mod supervision_tests { driver: completion.clone(), }); let route = origin.route("routed".into(), Default::default()).unwrap(); - let broadcast = route.broadcast().unwrap(); + let broadcast = route.broadcast(); let track = broadcast.publish_track("data".into(), None).unwrap(); let open = track.append_group().unwrap(); let consumer = origin.consume().request("routed".into(), None).await.unwrap(); diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index d2473f8919b..1f445efbbd9 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -274,7 +274,7 @@ impl std::ops::Deref for Announced { fn create_announced(origin: &MoqOriginProducer, path: &str) -> Announced { let route = origin.route(path.into(), MoqRouteOptions::default()).unwrap(); Announced { - broadcast: route.broadcast().unwrap(), + broadcast: route.broadcast(), _route: route, } } @@ -444,7 +444,7 @@ async fn route_options_reach_the_announced_route() { assert_eq!(info.cost, 4); assert_eq!(info.instance, route.instance_id()); - route.broadcast().unwrap().close().unwrap(); + route.broadcast().close().unwrap(); } #[tokio::test] @@ -477,7 +477,7 @@ async fn route_options_name_an_instance_or_refuse() { Err(MoqError::InvalidInstance { .. }) )); assert!(matches!( - origin.route_prefix("refused".into(), empty), + origin.claim("refused".into(), empty), Err(MoqError::InvalidInstance { .. }) )); @@ -518,17 +518,6 @@ async fn a_new_route_at_a_path_restarts_its_followers() { second.cancel(); } -#[tokio::test] -async fn an_exact_route_yields_no_requests_and_a_prefix_route_no_broadcast() { - let origin = MoqOriginProducer::new(MoqOriginConfig::default()); - let exact = origin.route("live".into(), Default::default()).unwrap(); - assert!(exact.requested().await.unwrap().is_none()); - let prefix = origin.route_prefix("room".into(), Default::default()).unwrap(); - assert!(matches!(prefix.broadcast(), Err(MoqError::Internal { .. }))); - exact.cancel(); - prefix.cancel(); -} - /// A media track reserves through its demand, so an app that publishes /// pre-encoded frames (OBS) can follow the grant like a raw track can. #[tokio::test] @@ -3336,7 +3325,7 @@ async fn a_hidden_route_is_invisible_until_announced() { matches!(&update, MoqAnnounceEvent::Present { announce } if announce.prefix == "live"), "{update:?}" ); - route.broadcast().unwrap().close().unwrap(); + route.broadcast().close().unwrap(); } /// Waiting for an exact path must hand the broadcast back named by that path, the base a @@ -3696,9 +3685,9 @@ async fn resolve_honors_the_reference_instance() { }; let catalog_route = origin.route("a/pub".into(), options.clone()).unwrap(); - let catalog = catalog_route.broadcast().unwrap(); + let catalog = catalog_route.broadcast(); let source_route = origin.route("a/source".into(), options).unwrap(); - let source = source_route.broadcast().unwrap(); + let source = source_route.broadcast(); let _video = source.publish_track("video".into(), None).unwrap(); let plain = create_announced(&origin, "a/plain"); @@ -3782,7 +3771,7 @@ async fn announce_and_withdraw_toggle_discovery() { .expect("timed out requesting the reannounced broadcast") .expect("a reannounced broadcast resolves"); - route.broadcast().unwrap().close().unwrap(); + route.broadcast().close().unwrap(); } /// The route alone keeps its broadcast announced: dropping the broadcast handle retracts @@ -3792,21 +3781,20 @@ async fn the_route_keeps_its_broadcast_announced() { let origin = MoqOriginProducer::new(MoqOriginConfig::default()); let consumer = origin.consume(); let live = origin.route("live".into(), MoqRouteOptions::default()).unwrap(); - let broadcast = live.broadcast().unwrap(); - assert!(Arc::ptr_eq(&broadcast, &live.broadcast().unwrap())); + let broadcast = live.broadcast(); + assert!(Arc::ptr_eq(&broadcast, &live.broadcast())); drop(broadcast); await_announced(&consumer, "live").await; let dropped = origin.route("dropped".into(), MoqRouteOptions::default()).unwrap(); - let dropped_broadcast = dropped.broadcast().unwrap(); + let dropped_broadcast = dropped.broadcast(); await_announced(&consumer, "dropped").await; drop(dropped); let cancelled = origin.route("cancelled".into(), MoqRouteOptions::default()).unwrap(); - let cancelled_broadcast = cancelled.broadcast().unwrap(); + let cancelled_broadcast = cancelled.broadcast(); await_announced(&consumer, "cancelled").await; cancelled.cancel(); assert!(matches!(cancelled.announce(), Err(MoqError::Cancelled))); - assert!(matches!(cancelled.requested().await, Err(MoqError::Cancelled))); for path in ["dropped", "cancelled"] { let unroutable = kio::clock::timeout(TIMEOUT, consumer.request(path.into(), None)) .await @@ -3818,7 +3806,7 @@ async fn the_route_keeps_its_broadcast_announced() { broadcast.close().unwrap(); } - live.broadcast().unwrap().close().unwrap(); + live.broadcast().close().unwrap(); let unroutable = kio::clock::timeout(TIMEOUT, consumer.request("live".into(), None)) .await .expect("an unroutable request answers at once"); @@ -3832,7 +3820,7 @@ async fn a_closed_route_leaves_its_replacement_alone() { let origin = MoqOriginProducer::new(MoqOriginConfig::default()); let consumer = origin.consume(); let stale = origin.route("live".into(), MoqRouteOptions::default()).unwrap(); - stale.broadcast().unwrap().close().unwrap(); + stale.broadcast().close().unwrap(); let replacement = origin.route("live".into(), MoqRouteOptions::default()).unwrap(); assert!(matches!(stale.announce(), Err(MoqError::Closed))); @@ -3843,7 +3831,7 @@ async fn a_closed_route_leaves_its_replacement_alone() { .expect("timed out requesting the replacement") .expect("the replacement still resolves"); - replacement.broadcast().unwrap().close().unwrap(); + replacement.broadcast().close().unwrap(); } #[tokio::test] @@ -5011,13 +4999,13 @@ async fn follow() { _broadcast.close().unwrap(); } -fn serve(origin: &MoqOriginProducer, prefix: &str) -> Arc { - origin.route_prefix(prefix.into(), MoqRouteOptions::default()).unwrap() +fn serve(origin: &MoqOriginProducer, prefix: &str) -> Arc { + origin.claim(prefix.into(), MoqRouteOptions::default()).unwrap() } -/// The next request beneath a prefix route, failing the test once it yields none. -async fn requested(route: &MoqRoute) -> Result, MoqError> { - Ok(route.requested().await?.expect("the prefix route ended")) +/// The next request beneath a claim, failing the test once it yields none. +async fn requested(claim: &MoqClaim) -> Result, MoqError> { + Ok(claim.requested().await?.expect("the claim ended")) } #[tokio::test] @@ -5038,7 +5026,7 @@ async fn dynamic_broadcast_request() { assert_eq!(request.path().unwrap(), "dynamic/broadcast"); let job = request.route(hidden()).unwrap(); - let served = job.broadcast().unwrap(); + let served = job.broadcast(); let track = served.publish_track("status".into(), Some(timed_info())).unwrap(); // Only announce answers the requester, under the claim's instance and after admission. let instance = job.instance_id(); @@ -5097,7 +5085,7 @@ async fn dynamic_serves_a_request_under_a_prefix() { .unwrap(); assert_eq!(request.path().unwrap(), "live/cam"); let job = request.route(MoqRouteOptions::default()).unwrap(); - let served = job.broadcast().unwrap(); + let served = job.broadcast(); kio::clock::timeout(TIMEOUT, requesting) .await .expect("timed out waiting for the request to resolve") @@ -5138,7 +5126,7 @@ async fn dynamic_keeps_the_origin_alive() { .expect("the handler must still receive requests") .unwrap(); let job = request.route(MoqRouteOptions::default()).unwrap(); - let served = job.broadcast().unwrap(); + let served = job.broadcast(); kio::clock::timeout(TIMEOUT, requesting) .await .expect("timed out waiting for the request to resolve") @@ -6205,7 +6193,7 @@ async fn follow_retries_a_dropped_wait() { .expect("the retry waited for another instance") .unwrap() .unwrap(); - served.broadcast().unwrap().close().unwrap(); + served.broadcast().close().unwrap(); } /// Another instance taking over while `available()` resolves is the one it hands out, and @@ -6296,7 +6284,7 @@ async fn follow_hands_out_the_instance_again_after_an_end() { "the claim above did not answer the same instance" ); drop((served, dynamic)); - first_route.broadcast().unwrap().close().unwrap(); + first_route.broadcast().close().unwrap(); } /// An instance pins both resolutions to one publisher instance: a request for another one is @@ -6372,8 +6360,8 @@ async fn an_instance_pins_request_and_follow() { "the follower handed out another instance" ); drop(takeover); - first.broadcast().unwrap().close().unwrap(); - second.broadcast().unwrap().close().unwrap(); + first.broadcast().close().unwrap(); + second.broadcast().close().unwrap(); } /// Dropping a handed-out handle changes nothing about the path, so the follower hands out diff --git a/rs/moq-ffi/uniffi.toml b/rs/moq-ffi/uniffi.toml index 08b5bd52d35..c08ac74f571 100644 --- a/rs/moq-ffi/uniffi.toml +++ b/rs/moq-ffi/uniffi.toml @@ -6,3 +6,4 @@ "MoqSocketEndpoint.close" = "end" # See MoqRoute::instance_id: the C++ generator reserves `instance`, Kotlin does not. "MoqRoute.instance_id" = "instance" +"MoqClaim.instance_id" = "instance" diff --git a/rs/moq-gst/src/source/imp.rs b/rs/moq-gst/src/source/imp.rs index 394146b2d31..dfe6e543b3d 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -4448,7 +4448,7 @@ mod session_tests { let origin = origin(); let claim = origin - .route_prefix("", moq_net::origin::RouteOptions::default()) + .claim("", moq_net::origin::RouteOptions::default()) .unwrap(); let (answers, answered) = std::sync::mpsc::channel(); let handler = super::RUNTIME.spawn(async move { @@ -4484,7 +4484,7 @@ mod session_tests { let recorder = Recorder::attach(&element); let origin = origin(); let pool = origin - .route_prefix("", moq_net::origin::RouteOptions::default()) + .claim("", moq_net::origin::RouteOptions::default()) .unwrap(); let session = follow(&element, &origin); let pending = super::RUNTIME.block_on(async { diff --git a/rs/moq-hls/src/export/rendition.rs b/rs/moq-hls/src/export/rendition.rs index 751b74a1972..a11f6712bac 100644 --- a/rs/moq-hls/src/export/rendition.rs +++ b/rs/moq-hls/src/export/rendition.rs @@ -2791,7 +2791,7 @@ mod tests { .route("room/live", moq_net::origin::RouteOptions::hidden()) .unwrap(); let dynamic = origin - .route_prefix("room/secret", moq_net::origin::RouteOptions::default()) + .claim("room/secret", moq_net::origin::RouteOptions::default()) .unwrap(); let source = moq_mux::Source::new(origin.consume(), broadcast.broadcast().consume()); let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8); diff --git a/rs/moq-hls/src/server/include_tests.rs b/rs/moq-hls/src/server/include_tests.rs index 0a96fd3a833..43e1b9399c3 100644 --- a/rs/moq-hls/src/server/include_tests.rs +++ b/rs/moq-hls/src/server/include_tests.rs @@ -349,7 +349,7 @@ async fn an_include_rendition_whose_broadcast_failed_is_not_listed() { frames(&parent.video, 0); frames(&parent.audio, 0); let other = origin - .route_prefix("room/other", moq_net::origin::RouteOptions::default()) + .claim("room/other", moq_net::origin::RouteOptions::default()) .unwrap(); let child = Instance::random(); let mut value = catalog(); @@ -412,7 +412,7 @@ async fn an_include_rendition_is_listed_once_its_broadcast_resolves() { frames(&parent.audio, 0); // The include's only rendition reads a sibling whose route has not answered yet. let other = origin - .route_prefix("room/other", moq_net::origin::RouteOptions::default()) + .claim("room/other", moq_net::origin::RouteOptions::default()) .unwrap(); let child = Instance::random(); let mut value = catalog(); @@ -611,7 +611,7 @@ async fn a_refused_include_is_listed_once_announced() { frames(&parent.audio, 0); // An on-demand route that drops its prepared answer refuses the first resolution. let claim = origin - .route_prefix("room/ladder", moq_net::origin::RouteOptions::default()) + .claim("room/ladder", moq_net::origin::RouteOptions::default()) .unwrap(); let server = Server::new(origin.consume(), Default::default()).unwrap(); let refuse = async { diff --git a/rs/moq-mux/src/catalog/hang/consumer.rs b/rs/moq-mux/src/catalog/hang/consumer.rs index f6256e59a98..c7b1150dae4 100644 --- a/rs/moq-mux/src/catalog/hang/consumer.rs +++ b/rs/moq-mux/src/catalog/hang/consumer.rs @@ -142,7 +142,7 @@ mod test { async fn publish_catalog_served(published: Catalog<()>) -> Result> { let origin = crate::source::produce_origin(); let dynamic = origin - .route_prefix("", moq_net::origin::RouteOptions::default()) + .claim("", moq_net::origin::RouteOptions::default()) .unwrap(); let requesting = origin.consume().request("a/pub", None); // The handler hands its route back: dropping it would retract the route and end diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index b6a47a44adf..31f3bf9177c 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -10544,12 +10544,12 @@ async fn a_follower_ignores_a_covering_prefix_while_the_exact_route_serves() { let quiet = Duration::from_secs(1); let pool = origin - .route_prefix("pool", moq_net::origin::RouteOptions::default()) + .claim("pool", moq_net::origin::RouteOptions::default()) .unwrap(); assert!(kio::clock::timeout(quiet, follower.next()).await.is_err(), "a start"); drop(pool); let pool = origin - .route_prefix("pool", moq_net::origin::RouteOptions::default()) + .claim("pool", moq_net::origin::RouteOptions::default()) .unwrap(); assert!(kio::clock::timeout(quiet, follower.next()).await.is_err(), "a restart"); drop(pool); diff --git a/rs/moq-mux/src/source.rs b/rs/moq-mux/src/source.rs index 3c6e2758c39..b97e114403b 100644 --- a/rs/moq-mux/src/source.rs +++ b/rs/moq-mux/src/source.rs @@ -675,7 +675,7 @@ mod tests { settle().await; let source = resolved(&origin, "pub").await; let dynamic = origin - .route_prefix("media", moq_net::origin::RouteOptions::default()) + .claim("media", moq_net::origin::RouteOptions::default()) .unwrap(); let binding = source.bind(Some(&Relative::new("media").unwrap()), None).unwrap(); let request = dynamic.requested().await.unwrap(); diff --git a/rs/moq-net-tests/tests/integration/restart.rs b/rs/moq-net-tests/tests/integration/restart.rs index 4c2dd24f942..48d302fe339 100644 --- a/rs/moq-net-tests/tests/integration/restart.rs +++ b/rs/moq-net-tests/tests/integration/restart.rs @@ -649,7 +649,7 @@ struct Pool { impl Pool { fn new(origin: &origin::Producer) -> Self { - let claim = Rc::new(origin.route_prefix("pool", origin::RouteOptions::default()).unwrap()); + let claim = Rc::new(origin.claim("pool", origin::RouteOptions::default()).unwrap()); let outputs = Rc::new(RefCell::new(std::collections::HashMap::new())); let answered = Rc::new(RefCell::new(0)); let (handler, served, count) = (claim.clone(), outputs.clone(), answered.clone()); diff --git a/rs/moq-net-tests/tests/integration/serve.rs b/rs/moq-net-tests/tests/integration/serve.rs index 053f91db9f2..94bc1fd3ca9 100644 --- a/rs/moq-net-tests/tests/integration/serve.rs +++ b/rs/moq-net-tests/tests/integration/serve.rs @@ -16,7 +16,7 @@ async fn first_subscribe(version: &str, publish: bool) { let version: Version = version.parse().unwrap(); let server = origin(1); let client = origin(2); - let requests = server.route_prefix("", origin::RouteOptions::default()).unwrap(); + let requests = server.claim("", origin::RouteOptions::default()).unwrap(); let mut options = MockConnectOptions::new(version); options.server_publish = Some(server.consume()); options.client_subscribe = Some(client.clone()); diff --git a/rs/moq-net/benches/origin.rs b/rs/moq-net/benches/origin.rs index b3c4da140a6..ca95f426a38 100644 --- a/rs/moq-net/benches/origin.rs +++ b/rs/moq-net/benches/origin.rs @@ -141,7 +141,7 @@ fn bench_announce_covering(c: &mut Criterion) { let _routes: Vec<_> = (0..routes) .map(|i| { producer - .route_prefix(format!("room/{i}/mic.hang"), moq_net::origin::RouteOptions::default()) + .claim(format!("room/{i}/mic.hang"), moq_net::origin::RouteOptions::default()) .unwrap() }) .collect(); @@ -157,7 +157,7 @@ fn bench_announce_covering(c: &mut Criterion) { b.iter(|| { for (name, delivered) in [("room/live.chat", true), ("room/mic.hang", covering)] { let route = producer - .route_prefix(name, moq_net::origin::RouteOptions::default()) + .claim(name, moq_net::origin::RouteOptions::default()) .unwrap(); for cursor in &mut cursors { assert_eq!(cursor.next().now_or_never().flatten().is_some(), delivered); @@ -633,7 +633,7 @@ fn bench_announce_fronts(c: &mut Criterion) { let consumer = producer.consume(); // Served but never answered: every request under it parks a front. let _served = producer - .route_prefix("room", moq_net::origin::RouteOptions::default()) + .claim("room", moq_net::origin::RouteOptions::default()) .unwrap(); let _requests: Vec<_> = (0..fronts) .map(|i| consumer.request(format!("room/{i}"), None)) @@ -681,7 +681,7 @@ fn bench_lend(c: &mut Criterion) { let (producer, mut driver) = origin::Producer::new(origin::Config::default()); let consumer = producer.consume(); let claim = producer - .route_prefix("room", moq_net::origin::RouteOptions::default()) + .claim("room", moq_net::origin::RouteOptions::default()) .unwrap(); let waiter = kio::Waiter::noop(); let mut ask = |path: &str| { @@ -743,7 +743,7 @@ fn bench_serve_idle(c: &mut Criterion) { let dynamics: Vec<_> = (0..routes) .map(|i| { producer - .route_prefix( + .claim( format!(".stats/p{}/node/edge{i}", i % 8), moq_net::origin::RouteOptions::default(), ) diff --git a/rs/moq-net/benches/retirement.rs b/rs/moq-net/benches/retirement.rs index 7fe34dfcde7..5105df61760 100644 --- a/rs/moq-net/benches/retirement.rs +++ b/rs/moq-net/benches/retirement.rs @@ -24,7 +24,7 @@ fn retirement(c: &mut Criterion) { let routes: Vec<_> = (0..routes) .map(|i| { origin - .route_prefix( + .claim( format!("route/{i}"), moq_net::origin::RouteOptions::default(), ) @@ -55,7 +55,7 @@ fn retirement(c: &mut Criterion) { |fixture| { let replacement = fixture .0 - .route_prefix("route/0/jobs", moq_net::origin::RouteOptions::default()) + .claim("route/0/jobs", moq_net::origin::RouteOptions::default()) .unwrap(); let refused = fixture .5 diff --git a/rs/moq-net/benches/viewers.rs b/rs/moq-net/benches/viewers.rs index 77d9ffde5bf..a21995e8b00 100644 --- a/rs/moq-net/benches/viewers.rs +++ b/rs/moq-net/benches/viewers.rs @@ -188,7 +188,7 @@ fn bench_churn(c: &mut Criterion) { b.iter(|| { let covering = room .producer - .route_prefix("room", moq_net::origin::RouteOptions::default()) + .claim("room", moq_net::origin::RouteOptions::default()) .unwrap(); room.poll(); drop(covering); diff --git a/rs/moq-net/src/model/follow.rs b/rs/moq-net/src/model/follow.rs index 624bd6dc3ae..661773ed5cb 100644 --- a/rs/moq-net/src/model/follow.rs +++ b/rs/moq-net/src/model/follow.rs @@ -606,7 +606,7 @@ mod tests { /// it, the takeover's restart lands while resolving; at it, the origin holds that restart. async fn hands_out_a_takeover_once(dynamic_at: &str) { let origin = Hop::new(1).unwrap().produce(); - let dynamic = origin.route_prefix(dynamic_at, RouteOptions::default()).unwrap(); + let dynamic = origin.claim(dynamic_at, RouteOptions::default()).unwrap(); let mut announced = origin.consume().follow("live", None).unwrap(); // The wait is on the dynamic route's answer when the exact path takes over under another instance. @@ -633,7 +633,7 @@ mod tests { #[kio::test] async fn announced_waits_for_another_instance_after_a_dropped_takeover() { let origin = Hop::new(1).unwrap().produce(); - let dynamic = origin.route_prefix("live", RouteOptions::default()).unwrap(); + let dynamic = origin.claim("live", RouteOptions::default()).unwrap(); let mut announced = origin.consume().follow("live", None).unwrap(); let (takeover, _publish) = futures::join!(available(&mut announced), async { @@ -653,7 +653,7 @@ mod tests { #[kio::test] async fn announced_hands_out_a_gap_while_resolving_once() { let origin = Hop::new(1).unwrap().produce(); - let dynamic = origin.route_prefix("", RouteOptions::default()).unwrap(); + let dynamic = origin.claim("", RouteOptions::default()).unwrap(); let mut announced = origin.consume().follow("live", None).unwrap(); let (_arrival, _publish) = futures::join!(available(&mut announced), async { @@ -756,7 +756,7 @@ mod tests { #[kio::test] async fn announced_reports_a_dropped_prepared_answer() { let origin = Hop::new(1).unwrap().produce(); - let claim = origin.route_prefix("live", RouteOptions::default()).unwrap(); + let claim = origin.claim("live", RouteOptions::default()).unwrap(); let mut announced = origin.consume().follow("live", None).unwrap(); let (result, ()) = futures::join!( kio::clock::timeout(Duration::from_secs(1), announced.available()), @@ -789,7 +789,7 @@ mod tests { async fn announced_retries_a_refusal_on_another_route_of_the_instance() { let origin = Hop::new(1).unwrap().produce(); let instance = Instance::random(); - let claim = origin.route_prefix("", options(&instance)).unwrap(); + let claim = origin.claim("", options(&instance)).unwrap(); let mut announced = origin.consume().follow("live", None).unwrap(); let (result, ()) = futures::join!( kio::clock::timeout(Duration::from_secs(1), announced.available()), @@ -813,7 +813,7 @@ mod tests { #[kio::test] async fn announced_waits_for_a_route_change_after_a_refusal() { let origin = Hop::new(1).unwrap().produce(); - let claim = origin.route_prefix("live", RouteOptions::default()).unwrap(); + let claim = origin.claim("live", RouteOptions::default()).unwrap(); let mut announced = origin.consume().follow("live", None).unwrap(); let (result, ()) = futures::join!( kio::clock::timeout(Duration::from_secs(1), announced.available()), @@ -835,7 +835,7 @@ mod tests { #[kio::test] async fn announced_does_not_retry_a_refusal_after_a_takeover() { let origin = Hop::new(1).unwrap().produce(); - let dynamic = origin.route_prefix("", options(&Instance::random())).unwrap(); + let dynamic = origin.claim("", options(&Instance::random())).unwrap(); let exact = origin.route("live", options(&Instance::random())).unwrap(); let mut announced = origin.consume().follow("live", None).unwrap(); let _first = available(&mut announced).await; diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 5ca478fbb31..8abee6e8873 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -454,7 +454,7 @@ impl From for Preference { /// paths under its prefix are servable, never that any specific broadcast exists. The /// common convention is that a publisher announces each broadcast's exact path with /// [`Producer::route`], so subscribers can enumerate broadcasts; a service instead -/// announces one short prefix with [`Producer::route_prefix`] and answers whatever is +/// announces one short prefix with [`Producer::claim`] and answers whatever is /// requested beneath it. /// /// Applications never build one: a [`Route`] takes [`RouteOptions`], and the origin @@ -2317,7 +2317,7 @@ impl Producer { /// a request for its path fails with [`Error::Unroutable`], for a consumer of this /// origin exactly as for a peer. Create it hidden when the tracks a subscriber needs /// first, such as a catalog, are not there yet. To serve paths on demand without - /// publishing each one, use [`Self::route_prefix`]. + /// publishing each one, use [`Self::claim`]. /// /// Announcing is visible to local consumers before it returns; only lifecycle work /// (track serving, teardown) waits for the [`Driver`] to be polled. Register a @@ -2471,7 +2471,7 @@ impl Producer { /// can be served, answered by nothing. /// /// A request under an advertise-only route resolves [`Error::Unroutable`] - /// unless an announced broadcast or a prefix route ([`Self::route_prefix`]) covers + /// unless an announced broadcast or a prefix route ([`Self::claim`]) covers /// the path too. Tests use it to shape the route table; everything else /// advertises through a [`Route`] or [`Claim`], which serves what it claims. #[cfg(test)] @@ -2585,7 +2585,7 @@ impl Producer { /// /// The prefix must overlap this producer's pattern scope. Individual requests /// remain authoritative and are refused when they do not match the scope. - pub fn route_prefix( + pub fn claim( &self, prefix: impl TryInto>, options: RouteOptions, @@ -2785,7 +2785,7 @@ impl Producer { } /// What it takes to insert a route: the prefixes it covers and the origin table -/// to insert them into. Built by [`Producer::route`], [`Producer::route_prefix`] +/// to insert them into. Built by [`Producer::route`], [`Producer::claim`] /// and the advertise-only test helper. struct Announcing { hop: Hop, @@ -2956,7 +2956,7 @@ pub struct Route { /// A prefix route on an origin: a claim that every path beneath a prefix can be served, /// answering each request as it arrives. /// -/// Created by [`Producer::route_prefix`]. Requests arrive on [`Self::poll_requested`]; answer +/// Created by [`Producer::claim`]. Requests arrive on [`Self::poll_requested`]; answer /// each by serving a broadcast already held or by creating the path's own [`Route`]. /// /// Clones share one claim. Dropping the last clone retracts it and refuses the requests @@ -3237,7 +3237,7 @@ impl Claim { /// [`RouteOptions::with_instance`] named one. /// /// Unnamed, it can change: the claim moves to a fresh instance each time an answer - /// holding its current one ends. See [`Producer::route_prefix`]. + /// holding its current one ends. See [`Producer::claim`]. pub fn instance(&self) -> Instance { self.state.instance() } @@ -11501,7 +11501,7 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); - let server = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let server = producer.claim("room", RouteOptions::default()).unwrap(); let pending = consumer.request("room/alice", None); let request = queued(&server).await; @@ -11528,9 +11528,9 @@ mod tests { let consumer = producer.consume(); let excluded = producer.exclude(".stats").unwrap(); assert!(excluded.route(".stats/node", RouteOptions::default()).is_err()); - assert!(excluded.route_prefix(".stats", RouteOptions::default()).is_err()); + assert!(excluded.claim(".stats", RouteOptions::default()).is_err()); - let server = excluded.route_prefix("", RouteOptions::default()).unwrap(); + let server = excluded.claim("", RouteOptions::default()).unwrap(); let Err(err) = consumer.request(".stats/evil", None).await else { panic!("excluded path served") }; @@ -12114,7 +12114,7 @@ mod tests { async fn claim_answer_is_hidden_until_published_under_the_claims_instance() { let producer = origin(1).produce(); let consumer = producer.consume(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); let mut pending = Box::pin(consumer.request("room/alice", None)); assert!((&mut pending).now_or_never().is_none()); @@ -12142,7 +12142,7 @@ mod tests { async fn a_hidden_job_route_is_listed_only_once_announced() { let producer = origin(1).produce(); let mut announced = producer.consume().routes(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); announced.assert_next_active("room"); let pending = producer.consume().request("room/alice", None); let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap(); @@ -12229,7 +12229,7 @@ mod tests { #[cfg(feature = "async")] async fn a_refused_prepared_answer_cannot_announce_later() { let producer = origin(1).produce(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); let _pending = producer.consume().request("room/alice", None); let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap(); let clone = prepared.clone(); @@ -12244,7 +12244,7 @@ mod tests { async fn dropping_a_prepared_claim_answer_refuses_the_request() { let producer = origin(1).produce(); let consumer = producer.consume(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); let pending = consumer.request("room/alice", None); let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap(); drop(prepared); @@ -12257,7 +12257,7 @@ mod tests { async fn a_prepared_answer_for_an_abandoned_claim_is_never_announced() { let producer = origin(1).produce(); let mut announced = producer.consume().routes(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); announced.assert_next_active("room"); let _pending = producer.consume().request("room/alice", None); let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap(); @@ -12275,7 +12275,7 @@ mod tests { async fn a_job_route_for_a_withdrawn_prefix_is_never_announced() { let producer = origin(1).produce(); let mut announced = producer.consume().routes(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); announced.assert_next_active("room"); let pending = producer.consume().request("room/alice", None); let job = queued(&claim).await.route(RouteOptions::hidden()).unwrap(); @@ -12300,7 +12300,7 @@ mod tests { async fn a_prepared_answer_for_a_released_request_is_never_announced() { let producer = origin(1).produce(); let mut announced = producer.consume().routes(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); announced.assert_next_active("room"); let _pending = producer.consume().request("room/alice", None); let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap(); @@ -12319,7 +12319,7 @@ mod tests { #[cfg(feature = "async")] async fn a_withdrawn_publication_is_not_a_cached_claim_answer() { let producer = origin(1).produce(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); let path = Path::from_static("room/alice"); let pending = producer.consume().request(path.clone(), None); let publication = queued(&claim).await.route(RouteOptions::default()).unwrap(); @@ -12345,7 +12345,7 @@ mod tests { let producer = origin(1).produce(); let consumer = producer.consume(); let mut announced = consumer.routes(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); announced.assert_next_active("room"); let first = claim.instance(); @@ -12398,7 +12398,7 @@ mod tests { async fn a_hidden_job_takes_the_claims_instance_when_it_announces() { let producer = origin(1).produce(); let consumer = producer.consume(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); let alice = consumer.request("room/alice", None); let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap(); @@ -12426,7 +12426,7 @@ mod tests { async fn a_job_that_read_its_instance_is_refused_once_the_claim_moves() { let producer = origin(1).produce(); let consumer = producer.consume(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); let alice = consumer.request("room/alice", None); let prepared = queued(&claim).await.route(RouteOptions::hidden()).unwrap(); @@ -12457,7 +12457,7 @@ mod tests { async fn a_pinned_request_reaches_its_job_after_a_sibling_moves_the_claim() { let producer = origin(1).produce(); let consumer = producer.consume(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); let lent = claim.instance(); let reader = consumer.request("room/alice", None); @@ -12481,7 +12481,7 @@ mod tests { async fn a_request_pinned_to_an_ended_job_is_refused() { let producer = origin(1).produce(); let consumer = producer.consume(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); let pending = consumer.request("room/alice", None); let job = queued(&claim).await.route(RouteOptions::default()).unwrap(); @@ -12511,7 +12511,7 @@ mod tests { async fn a_claim_and_its_job_end_independently() { let producer = origin(1).produce(); let consumer = producer.consume(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); let pending = consumer.request("room/alice", None); let job = queued(&claim).await.route(RouteOptions::default()).unwrap(); let held = pending.await.unwrap(); @@ -12534,7 +12534,7 @@ mod tests { let consumer = producer.consume(); let stable = instance(); let claim = producer - .route_prefix("room", RouteOptions::default().with_instance(stable.clone(), 0)) + .claim("room", RouteOptions::default().with_instance(stable.clone(), 0)) .unwrap(); let pending = consumer.request("room/alice", None); @@ -12544,7 +12544,7 @@ mod tests { drop(minted); assert_eq!(claim.instance(), stable); - let lending = producer.route_prefix("lent", RouteOptions::default()).unwrap(); + let lending = producer.claim("lent", RouteOptions::default()).unwrap(); let lent = lending.instance(); let named = instance(); let pending = consumer.request("lent/bob", None); @@ -12565,7 +12565,7 @@ mod tests { async fn a_pinned_request_resolves_only_through_the_published_instance() { let producer = origin(1).produce(); let consumer = producer.consume(); - let claim = producer.route_prefix("room", RouteOptions::default()).unwrap(); + let claim = producer.claim("room", RouteOptions::default()).unwrap(); let unknown = consumer.request("room/alice", crate::Instance::random()); assert!(matches!(unknown.await, Err(Error::Unroutable))); @@ -15713,7 +15713,7 @@ mod tests { assert!(routes.next().await.is_some()); drop(routes); drop(overlap); - let source = producer.route_prefix("project/room", RouteOptions::default()).unwrap(); + let source = producer.claim("project/room", RouteOptions::default()).unwrap(); let pending = consumer.request("room/lobby.chat", None); let request = source.requested().await.unwrap(); request.serve(local.broadcast().consume()); diff --git a/rs/moq-net/tests/integration/announce_covering_route.rs b/rs/moq-net/tests/integration/announce_covering_route.rs index acaad683d1a..1b6f671a0c7 100644 --- a/rs/moq-net/tests/integration/announce_covering_route.rs +++ b/rs/moq-net/tests/integration/announce_covering_route.rs @@ -133,7 +133,7 @@ async fn relays_route_a_covering_claim_that_listings_omit() { let version: Version = version.parse().unwrap(); let publisher = produce_origin(1); let claim = publisher - .route_prefix("room", moq_net::origin::RouteOptions::default()) + .claim("room", moq_net::origin::RouteOptions::default()) .unwrap(); let listed = publisher .route("lobby.chat", moq_net::origin::RouteOptions::hidden()) diff --git a/rs/moq-net/tests/integration/claim_continues.rs b/rs/moq-net/tests/integration/claim_continues.rs index 95dfc568fe2..bbb7886e47e 100644 --- a/rs/moq-net/tests/integration/claim_continues.rs +++ b/rs/moq-net/tests/integration/claim_continues.rs @@ -55,7 +55,7 @@ struct Worker { impl Worker { fn new(hop: u64, claim: &str, name: &'static str) -> Self { let origin = produce_origin(hop); - let claim = Rc::new(origin.route_prefix(claim, origin::RouteOptions::default()).unwrap()); + let claim = Rc::new(origin.claim(claim, origin::RouteOptions::default()).unwrap()); let outputs = Rc::new(RefCell::new(Vec::new())); let (handler, served) = (claim.clone(), outputs.clone()); drop(kio::clock::sim::spawn(async move { diff --git a/rs/moq-net/tests/integration/drained_claim.rs b/rs/moq-net/tests/integration/drained_claim.rs index e0ebe12e46f..268c2f6dba3 100644 --- a/rs/moq-net/tests/integration/drained_claim.rs +++ b/rs/moq-net/tests/integration/drained_claim.rs @@ -57,7 +57,7 @@ impl Worker { let origin = produce_origin(hop); let claim = Rc::new( origin - .route_prefix("pool", moq_net::origin::RouteOptions::default()) + .claim("pool", moq_net::origin::RouteOptions::default()) .unwrap(), ); let outputs = Rc::new(RefCell::new(Vec::new())); diff --git a/rs/moq-net/tests/integration/wide_hop.rs b/rs/moq-net/tests/integration/wide_hop.rs index a42bd3b0c94..cac5164fd57 100644 --- a/rs/moq-net/tests/integration/wide_hop.rs +++ b/rs/moq-net/tests/integration/wide_hop.rs @@ -29,7 +29,7 @@ async fn widest_hop_crosses_each_varint_form() { let _upstream = peer(upstream, &source, &relay).await; let _downstream = peer(downstream.parse().unwrap(), &relay, &sink).await; let _route = source - .route_prefix("room", moq_net::origin::RouteOptions::default()) + .claim("room", moq_net::origin::RouteOptions::default()) .unwrap(); kio::clock::sim::idle().await; diff --git a/rs/moq-relay/src/cluster.rs b/rs/moq-relay/src/cluster.rs index 45c6959b97f..dbfb8f76b50 100644 --- a/rs/moq-relay/src/cluster.rs +++ b/rs/moq-relay/src/cluster.rs @@ -2786,9 +2786,9 @@ mod tests { "route {path}, peer={peer}" ); assert_eq!( - publisher.route_prefix(path, options()).is_ok(), + publisher.claim(path, options()).is_ok(), peer, - "route_prefix {path}, peer={peer}" + "claim {path}, peer={peer}" ); } assert!(publisher.route(".statsish", options()).is_ok()); diff --git a/rs/moq-room/src/room.rs b/rs/moq-room/src/room.rs index d4768347d05..c394de44207 100644 --- a/rs/moq-room/src/room.rs +++ b/rs/moq-room/src/room.rs @@ -185,7 +185,7 @@ mod tests { let mut room = Room::new(&origin.consume(), None); let claim = origin - .route_prefix("bob/camera", moq_net::origin::RouteOptions::default()) + .claim("bob/camera", moq_net::origin::RouteOptions::default()) .expect("claim"); let (request, nothing) = tokio::join!(claim.requested(), kio::clock::timeout(wait, room.next())); assert!(nothing.is_err(), "nothing serves bob yet"); diff --git a/rs/moq-webrtc/src/egress.rs b/rs/moq-webrtc/src/egress.rs index a5722823352..73ecd6fa1c4 100644 --- a/rs/moq-webrtc/src/egress.rs +++ b/rs/moq-webrtc/src/egress.rs @@ -1273,7 +1273,7 @@ mod tests { // The better rendition lives in a broadcast whose request is never answered. let _handler = origin - .route_prefix("missing", moq_net::origin::RouteOptions::default()) + .claim("missing", moq_net::origin::RouteOptions::default()) .unwrap(); let mut config = VideoConfig::new(VideoCodec::VP8); config.container = hang::catalog::Container::Legacy; diff --git a/swift/Sources/Moq/Origin.swift b/swift/Sources/Moq/Origin.swift index 44a196c274d..091804c8885 100644 --- a/swift/Sources/Moq/Origin.swift +++ b/swift/Sources/Moq/Origin.swift @@ -1,6 +1,6 @@ import MoqFFI -/// The publish side of an origin: create routes that own broadcasts or serve +/// The publish side of an origin: create routes that own broadcasts, or claims that serve /// them on demand, so subscribers can discover them. public final class OriginProducer: Sendable { let ffi: MoqOriginProducer @@ -37,17 +37,17 @@ public final class OriginProducer: Sendable { options: MoqRouteOptions(hidden: hidden, cost: cost, instance: instance, epoch: epoch))) } - /// Create a route over `prefix` that serves the requests beneath it. + /// Claim `prefix` and serve the requests beneath it. /// - /// A route claims `prefix` and every path beneath it (`""` claims every path). + /// A claim covers `prefix` and every path beneath it (`""` claims every path). /// A service that only serves some of them rejects the rest as they are - /// requested. Iterate the route, or call `requested()`, to answer each request; hold + /// requested. Iterate the claim, or call `requested()`, to answer each request; hold /// it while it should stay advertised. - public func routePrefix( + public func claim( prefix: String, hidden: Bool = false, cost: UInt64 = 0, instance: String? = nil, epoch: UInt64 = 0 - ) throws -> Route { - Route( - try ffi.routePrefix( + ) throws -> Claim { + Claim( + try ffi.claim( prefix: prefix, options: MoqRouteOptions(hidden: hidden, cost: cost, instance: instance, epoch: epoch))) } @@ -68,10 +68,11 @@ public final class BroadcastRequest: Sendable { /// Answer with the path's own exact route, owning a new broadcast. /// - /// Unless `instance` names one, it takes the instance its prefix route lends when it first - /// announces or `Route.instance` first reads it, so readers that resolved the path through the prefix route continue on it; - /// its end then moves the prefix route to a fresh instance, so a restarted job is a new - /// stream. A prefix route that names its instance lends none, and the route mints its own. + /// Unless `instance` names one, it takes the instance its claim lends when it first + /// announces or `Route.instance` first reads it, so readers that resolved the path through + /// the claim continue on it; its end then moves the claim to a fresh instance, so a + /// restarted job is a new stream. A claim that names its instance lends none, and the route + /// mints its own. /// Created visible, it announces now and answers the waiting requesters; created `hidden`, they wait until /// `Route.announce()`, so the job can fill its catalog first. public func route( @@ -81,7 +82,7 @@ public final class BroadcastRequest: Sendable { try ffi.route(options: MoqRouteOptions(hidden: hidden, cost: cost, instance: instance, epoch: epoch))) } - /// Serve held content under the prefix route's continuous sequence space, without an exact route. + /// Serve held content under the claim's continuous sequence space, without an exact route. public func serve(broadcast: BroadcastConsumer) throws { try ffi.serve(broadcast: broadcast.ffi) } @@ -92,39 +93,25 @@ public final class BroadcastRequest: Sendable { } } -/// A route on an origin: an exact route owning one broadcast, or a prefix route yielding -/// the requests beneath it. Iterate a prefix route directly: -/// `for try await request in route { ... }`; cancelling the consuming task cancels the route. +/// An exact route on an origin, owning one broadcast. /// -/// Releasing or cancelling it retracts the route, as does closing an exact route's -/// broadcast; a `BroadcastProducer` alone does not keep it announced. -public final class Route: AsyncSequence, Sendable { - /// The broadcast request emitted by this sequence. - public typealias Element = BroadcastRequest - +/// Releasing or cancelling it retracts the route, as does closing its broadcast; a +/// `BroadcastProducer` alone does not keep it announced. +public final class Route: Sendable { let ffi: MoqRoute - private let owned: BroadcastProducer? + + /// The broadcast this route owns, the same one on every read. + public let broadcast: BroadcastProducer init(_ ffi: MoqRoute) { self.ffi = ffi - // A prefix route owns no broadcast. - owned = (try? ffi.broadcast()).map { BroadcastProducer($0) } - } - - /// The broadcast this exact route owns, the same one on every read. Throws on a prefix - /// route, which owns none. - public var broadcast: BroadcastProducer { - get throws { - if let owned { return owned } - return BroadcastProducer(try ffi.broadcast()) - } + broadcast = BroadcastProducer(ffi.broadcast()) } - /// The stream this route serves now. A named instance never changes. Unnamed, a prefix - /// route moves to a fresh one each time a job holding its current one ends. A job's route - /// takes its prefix route's current one when it first announces or when this first reads - /// it. Read first, the job announces under it, and `announce()` throws `Unroutable` once - /// the prefix route has moved past it, so a signer built from it stays valid. + /// The stream this route serves now. A named instance never changes. A job's route takes + /// its claim's current one when it first announces or when this first reads it. Read + /// first, the job announces under it, and `announce()` throws `Unroutable` once the claim + /// has moved past it, so a signer built from it stays valid. public var instance: String { ffi.instanceId() } /// Make the route visible, or keep it so; throws `Closed` once its broadcast closed. @@ -142,19 +129,61 @@ public final class Route: AsyncSequence, Sendable { try ffi.setCost(cost: cost) } - /// The next broadcast requested beneath this prefix route, or `nil` once the origin - /// closes, and at once on an exact route. + /// Retract the route now: later calls throw `Cancelled`. Its broadcast lives on until + /// closed. + public func cancel() { + ffi.cancel() + } +} + +/// A prefix route on an origin: a claim that every path beneath a prefix can be served, +/// yielding each request as it arrives. Iterate it directly: +/// `for try await request in claim { ... }`; cancelling the consuming task cancels the claim. +/// +/// Releasing or cancelling it retracts the claim and rejects the requests still waiting. +public final class Claim: AsyncSequence, Sendable { + /// The broadcast request emitted by this sequence. + public typealias Element = BroadcastRequest + + let ffi: MoqClaim + + init(_ ffi: MoqClaim) { + self.ffi = ffi + } + + /// The stream this claim serves now. A named instance never changes. Unnamed, the claim + /// moves to a fresh one each time a job holding its current one ends. + public var instance: String { ffi.instanceId() } + + /// Make the claim visible, or keep it so. + public func announce() throws { + try ffi.announce() + } + + /// Hide the claim, keeping its instance: `announce()` brings it back. Requests beneath it + /// are rejected meanwhile. + public func withdraw() throws { + try ffi.withdraw() + } + + /// Re-price the claim in place: lower wins among routes covering the same prefix. + public func setCost(_ cost: UInt64) throws { + try ffi.setCost(cost: cost) + } + + /// The next broadcast requested beneath this claim, or `nil` once the claim is retracted + /// or the origin closes. public func requested() async throws -> BroadcastRequest? { try await ffi.requested().map { BroadcastRequest($0) } } - /// Retract the route now: pending requests are rejected and later calls throw - /// `Cancelled`. An exact route's broadcast lives on until closed. + /// Retract the claim now: pending requests are rejected and later calls throw + /// `Cancelled`. public func cancel() { ffi.cancel() } - /// Create an iterator that cancels the route when iteration is cancelled. + /// Create an iterator that cancels the claim when iteration is cancelled. public func makeAsyncIterator() -> AsyncThrowingStream.Iterator { moqStream(cancel: { [ffi] in ffi.cancel() }) { [ffi] in try await ffi.requested().map { BroadcastRequest($0) } diff --git a/swift/Tests/MoqTests/FfiBench.swift b/swift/Tests/MoqTests/FfiBench.swift index 09e86dfd7ad..680af329f83 100644 --- a/swift/Tests/MoqTests/FfiBench.swift +++ b/swift/Tests/MoqTests/FfiBench.swift @@ -73,7 +73,7 @@ final class FfiBench: XCTestCase { defer { withExtendedLifetime(origin) {} } let route = try origin.route(path: "bench", hidden: true) defer { withExtendedLifetime(route) {} } - let broadcast = try route.broadcast + let broadcast = route.broadcast let tracks = try (0..publish()->route(path, hidden), "route"); - auto broadcast = ok(route->broadcast(), "route broadcast"); + auto broadcast = route->broadcast(); auto catalog = ok(moq::MediaCatalogProducer::init(broadcast), "catalog producer"); auto media = ok( moq::MediaTrackStreamProducer::video(broadcast, moq::MediaTarget::kNamed{}, {moq::VideoFormat::kAvc3, {}}), @@ -261,7 +261,7 @@ int publish( std::puts("finish ended"); std::fflush(stdout); auto health_route = ok(session->publish()->route(path + ".health", hidden), "health route"); - auto health = ok(health_route->broadcast(), "health broadcast"); + auto health = health_route->broadcast(); auto track = ok(health->publish_track("live", std::nullopt), "health track"); const std::string payload = "session-alive"; ok(track->write_frame({std::vector(payload.begin(), payload.end()), std::nullopt}), "health write"); diff --git a/test/interop/clients/go/main.go b/test/interop/clients/go/main.go index c41b5ce5cc8..ed0082e89ee 100644 --- a/test/interop/clients/go/main.go +++ b/test/interop/clients/go/main.go @@ -150,10 +150,7 @@ func publish(ctx context.Context, url, broadcast string, opts dialOptions, timeo return err } defer route.Cancel() - producer, err := route.Broadcast() - if err != nil { - return err - } + producer := route.Broadcast() defer producer.Close() catalog, err := moqmedia.NewCatalogProducer(producer) @@ -246,10 +243,7 @@ func publish(ctx context.Context, url, broadcast string, opts dialOptions, timeo return err } defer healthRoute.Cancel() - health, err := healthRoute.Broadcast() - if err != nil { - return err - } + health := healthRoute.Broadcast() defer health.Close() live, err := health.PublishTrack("live", nil) if err != nil { From cb35554c67c8ce9c5372961fc866abcbe9eec466 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 21:36:24 -0800 Subject: [PATCH 08/12] quest(route-roles): finished, the split lands in every language Co-Authored-By: Claude Opus 5.5 --- quest/m2/README.md | 1 - quest/m2/route-roles.md | 52 ----------------------------------------- 2 files changed, 53 deletions(-) delete mode 100644 quest/m2/route-roles.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 1ae9ab6e886..5e2533122a6 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -190,7 +190,6 @@ quests that require them. - [Subscribe ranges](/quest/m2/subscribe-ranges/README.md) - a lite-07 SUBSCRIBE asks for past and live ranges with absolute or relative ends, in either order, and replaces FETCH for multi-group reads (single-group FETCH stays); merged ranges never starve a subscriber; relays fill misses by range, including over moq-transport - [Address groups by timestamp](/quest/m2/time-addressing/README.md) - group start timestamps replace sequence numbers in the moq-net API and lite-07 wire, while old subscribers, old publishers, and published JS clients keep working - [Cluster routing](/quest/m2/cluster-routing/README.md) - prove shared routing contracts, implement per-origin routes, and connect outbound local clusters -- [A route's role is its type](/quest/m2/route-roles.md) - no route method panics, throws, or errors because the other constructor made the route; prototypes of a single prefix route and an exact/prefix split decide the shape - [A group a subscriber gives up on is always reported](/quest/m2/group-drops.md) - the wire names every abandoned group and the drop signal is public, so readers count losses instead of stalling - [Stream credit by priority](/quest/m1/stream-credit/README.md) - every stream opens through one priority entry point, and a higher-priority group takes over or resets a lower one when credit runs out (held in m1 by an open claim) - [Finalize moq-lite-07](/quest/m2/lite07-finalize.md) - when the maintainer cuts it, lite-07 negotiates as `moq-lite-07` and the next release ships it diff --git a/quest/m2/route-roles.md b/quest/m2/route-roles.md deleted file mode 100644 index ee27cc11666..00000000000 --- a/quest/m2/route-roles.md +++ /dev/null @@ -1,52 +0,0 @@ -# [L] A route's role is its type - -## Goal - -No route method panics, throws, or returns an error because the route was -made by the other constructor. Today one `Route` type serves both exact -routes (`origin.route(path)`) and prefix routes (`route_prefix`): -`Route::broadcast()` panics on a prefix route in Rust -(`rs/moq-net/src/model/origin.rs`, "# Panics"), throws in JS -(`js/net/src/origin.ts`), and returns `MoqError::Internal` in moq-ffi -(`rs/moq-ffi/src/origin.rs`), while `requested()` ends at once on an exact -route. The fix lands in Rust, JS, moq-ffi, the hand-written C ABI, and every -binding wrapper, and `RouteInfo`'s public `Default` (whose `instance()` -panics) goes private. - -## Plan - -Decided 2026-11-07 (maintainer, /quest-plan from the API shape audit): -replace [moq-dev/moq#7806](https://github.com/moq-dev/moq/pull/7806)'s -single handle with a shape where the misuse is unrepresentable. ✅ Prototype -two shapes and pick from the prototypes (rejected: an `Option`-returning -`broadcast()`, which keeps a runtime check in every caller; keeping #7806 as -is). "Every route is a prefix on the wire" (maintainer), so: - -- **Single prefix Route**: one `Route` always claims a prefix. - `route.broadcast(suffix)` publishes a broadcast under it, an exact route is - the empty suffix, and `requested()` yields requests for any suffix the - route covers. -- **Split**: `route()` returns `Route` (with `broadcast()`), `route_prefix()` - returns a `Claim` (with `requested()`), and the shared methods (`announce`, - `withdraw`, `set_cost`, `set_auth`, `instance`) are on both. - -Build both in Rust first, port each to the in-repo callers (moq-mux, hang, -moq-cli, moq-relay, moq-archive, moq-ffi, moq-c) and sketch the diff for -downstream callers (`.route(` and `route_prefix` sites), then -put the comparison in the PR under `## Waiting` with a recommendation. After -the maintainer picks, land the winner in JS, moq-ffi, moq-c, and the -wrappers in the same PR. The route instance accessor's five spellings across -bindings stay with [the exporter](/quest/m3/ffi-exporter.md). - -Status (2026-11-08, [moq-dev/moq#8292](https://github.com/moq-dev/moq/pull/8292)): -the split is built in Rust (moq-net returns a `Claim` from `route_prefix`; moq-ffi -and moq-c wrap both kinds in a private enum, so their API is unchanged so far). The single -prefix Route is sketched in the PR with caller diffs, not built: building it means -redesigning the origin table (exact routes become serving entries, sibling broadcasts -share one instance, job routes answer requests differently). - -## Waiting - -- Maintainer: pick split or single prefix on moq-dev/moq#8292, and whether the split - renames `route_prefix` to `claim`; recommended: split, renamed. Done when the PR has a - reply naming the shape. From eee114769d2a710d18c85725fe148d8e2babcade Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 21:42:54 -0800 Subject: [PATCH 09/12] feat(js/net)!: claim splits from route `routePrefix` becomes `claim`, returning a Claim with requested(); Route owns its broadcast as a field and has no requested(). Co-Authored-By: Claude Opus 5.5 --- doc/concept/identity.md | 2 +- doc/lib/js/net.md | 2 +- js/net/api/index.api.md | 18 +- js/net/bench/broadcasts.ts | 4 +- js/net/bench/requests.ts | 14 +- js/net/src/connection/forward.ts | 6 +- js/net/src/connection/pool.test.ts | 2 +- js/net/src/group-id.test.ts | 2 +- js/net/src/ietf/datagram.test.ts | 2 +- js/net/src/ietf/fetch.test.ts | 2 +- js/net/src/ietf/publisher.test.ts | 30 +-- js/net/src/integration.test.ts | 8 +- js/net/src/lite/publisher.test.ts | 8 +- js/net/src/lite/tracks.test.ts | 6 +- js/net/src/origin-demand.test.ts | 44 ++-- js/net/src/origin-request.test.ts | 64 ++--- js/net/src/origin.test.ts | 134 +++++----- js/net/src/origin.ts | 296 ++++++++++++++-------- js/net/src/untimed.test.ts | 2 +- js/net/src/wire.ts | 6 +- js/watch/src/broadcast.test.ts | 24 +- js/watch/src/include.test.ts | 2 +- test/interop/clients/js-native/claims.ts | 2 +- test/interop/clients/js-native/replace.ts | 2 +- test/relay-fill/relay.ts | 6 +- 25 files changed, 392 insertions(+), 296 deletions(-) diff --git a/doc/concept/identity.md b/doc/concept/identity.md index 0d79ba5f360..2a37ec4ef44 100644 --- a/doc/concept/identity.md +++ b/doc/concept/identity.md @@ -32,7 +32,7 @@ no credential, and auth decides who may publish the path. keeps its instance on every route, which is what lets a subscription move between them. - **A stable instance is a promise.** A publisher may name its own instance - (`Route::with_instance(instance, epoch)` in Rust, `origin.route(path, { instance, epoch })` + (`RouteOptions::with_instance(instance, epoch)` in Rust, `origin.route(path, { instance, epoch })` in JavaScript) only if it continues the sequence space across restarts and announces a higher **epoch** each time, for example a counter persisted on disk. Breaking the promise splices unrelated groups into every reader's diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index faf1519921b..3fef17c21c3 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -39,7 +39,7 @@ route.announce(); ``` - **The origin holds the routes, not the connection.** `origin.route(path)` creates a route that owns a new broadcast; fill its tracks through `route.broadcast`. Closing a session withdraws its announcements and leaves the routes for the next one. A route is visible at once unless created `{ hidden: true }`, which keeps it invisible, locally and remotely, until `announce()`. `withdraw()` hides it again and `announce()` brings the same stream back. `close()` retracts it and closes its broadcast, as closing the broadcast does. -- **Answer claimed paths with a route.** `origin.routePrefix(prefix)` claims a prefix, and `route.requested()` yields each requested path. Answer with `request.route()`, a new exact route under the claim's instance (a fresh one if the claim names its own), so on `moq-lite-07-wip` readers resolved through the claim continue (older wires mint another instance for it, restarting their subscription), or `request.route({ hidden: true })` to fill its broadcast before `announce()` answers the requesters; closing it or its broadcast before then refuses them as unroutable, so `using job = request.route({ hidden: true })` refuses on a throw. Serve a broadcast you already hold with `request.serve(broadcast)`, or refuse with `request.reject(err)`. +- **Answer claimed paths with a route.** `origin.claim(prefix)` returns a `Claim` over a prefix, and `claim.requested()` yields each requested path. Answer with `request.route()`, a new exact route under the claim's instance (a fresh one if the claim names its own), so on `moq-lite-07-wip` readers resolved through the claim continue (older wires mint another instance for it, restarting their subscription), or `request.route({ hidden: true })` to fill its broadcast before `announce()` answers the requesters; closing it or its broadcast before then refuses them as unroutable, so `using job = request.route({ hidden: true })` refuses on a throw. Serve a broadcast you already hold with `request.serve(broadcast)`, or refuse with `request.reject(err)`. - **End content by finishing tracks.** A broadcast has no finished state. When the input ends, `finish()` each track, then `close()` it; closing a track without finishing aborts it. The broadcast stays announced and keeps serving them until you `close()` it. How long to keep it up for late readers is yours to decide. - **Requests can pin an instance.** `consumer.request(path, { instance })` resolves only through a route announcing that [publisher instance](/concept/moq-lite#publisher-instances). The resolved broadcast's `instance` names the stream it came through, pinned or not. `origin.route(path)` mints a random instance when it is created and keeps it across `withdraw()` and `announce()`. Unless one is named, a claim moves to a fresh instance each time a job holding its current one ends, and a job takes the claim's. Pass `origin.route(path, { instance, epoch })` only for a publisher that continues its group sequences across restarts and raises the epoch each time. - **Follow restarts.** `origin.follow(path)` follows whichever publisher instance serves the path: its `active` changes to a fresh broadcast on a restart, clears on an end, and resolves again on the next start, so read it reactively and close it when done. Instances are never stitched, so subscribe again to each new broadcast. Another route of the same instance taking over (instances travel only on `moq-lite-07-wip`; older wires mint one per announcement) keeps `active` as is, and each track subscription resumes there from the first group it lacks. A refusal ends it. Pass `{ instance }` to pin one stream, which it waits for again after an end. `request(path)` instead keeps its accepted instance and ends once that instance stops serving; while pending, it fails `Unroutable` once discovery of its path has synced without a route for it. To list what is live, iterate `announced(scope)`. See [identity and recovery](/concept/identity) to choose between following and holding one instance. diff --git a/js/net/api/index.api.md b/js/net/api/index.api.md index 40d9626fd6a..5713cfbbf59 100644 --- a/js/net/api/index.api.md +++ b/js/net/api/index.api.md @@ -443,6 +443,17 @@ export namespace Instance { } export namespace Origin { + export class Claim { + [Symbol.dispose](): void; + announce(): void; + get announced(): boolean; + close(): void; + get instance(): Instance.Valid; + requested(): AsyncIterableIterator; + setAuth(auth?: Auth.Credential): void; + setCost(cost: Origin.Cost): void; + withdraw(): void; + } export class Consumer implements Origin.Reader { announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; get closed(): Signals.GetPromise; @@ -463,6 +474,7 @@ export namespace Origin { export class Producer implements Origin.Table { constructor(); announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; + claim(prefix: Path.Valid, options?: Origin.RouteOptions): Origin.Claim; close(abort?: Error): void; get closed(): Signals.GetPromise; consume(): Origin.Consumer; @@ -470,7 +482,6 @@ export namespace Origin { follow(path: Path.Valid, options?: Origin.FollowOptions): Origin.Following; request(path: Path.Valid, options?: Origin.RequestOptions): Origin.Requesting; route(path: Path.Valid, options?: Origin.RouteOptions): Origin.Route; - routePrefix(prefix: Path.Valid, options?: Origin.RouteOptions): Origin.Route; scope(root: Path.Valid, patterns: Path.Patterns): Origin.Producer; } export interface Reader { @@ -499,10 +510,9 @@ export namespace Origin { [Symbol.dispose](): void; announce(): void; get announced(): boolean; - get broadcast(): Broadcast.Producer; + readonly broadcast: Broadcast.Producer; close(): void; get instance(): Instance.Valid; - requested(): AsyncIterableIterator; setAuth(auth?: Auth.Credential): void; setCost(cost: Origin.Cost): void; withdraw(): void; @@ -521,8 +531,8 @@ export namespace Origin { instance?: Instance.Valid; } export interface Table extends Origin.Reader { + claim(prefix: Path.Valid, options?: Origin.RouteOptions): Origin.Claim; route(path: Path.Valid, options?: Origin.RouteOptions): Origin.Route; - routePrefix(prefix: Path.Valid, options?: Origin.RouteOptions): Origin.Route; } } diff --git a/js/net/bench/broadcasts.ts b/js/net/bench/broadcasts.ts index ec5b9d44e8d..035d93fa940 100644 --- a/js/net/bench/broadcasts.ts +++ b/js/net/bench/broadcasts.ts @@ -38,7 +38,7 @@ for (const scope of [ for (const observerCount of observerCounts) { const origin = new Producer(); const handles = Array.from({ length: routeCount }, (_, index) => - origin.routePrefix(Path.from(`room/${index}${scope === "full-name" ? ".chat" : ""}`)), + origin.claim(Path.from(`room/${index}${scope === "full-name" ? ".chat" : ""}`)), ); const touched = Path.from( scope === "rooted-producers" ? "0" : scope === "full-name" ? "room/0.chat" : "room/0", @@ -233,7 +233,7 @@ const nextInstance = Instance.parse("01900000-0000-7000-8000-000000000002"); for (const pathCount of routeCounts) { for (const readerCount of observerCounts) { const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room"), { instance }); + const dynamic = origin.claim(Path.from("room"), { instance }); const pending = dynamic.requested(); const requests = Array.from({ length: pathCount }, (_, index) => Array.from({ length: readerCount }, () => origin.consume().request(Path.from(`room/${index}`))), diff --git a/js/net/bench/requests.ts b/js/net/bench/requests.ts index 44e1da5645d..f2bee4376d0 100644 --- a/js/net/bench/requests.ts +++ b/js/net/bench/requests.ts @@ -71,7 +71,7 @@ console.log("unrelated,waiters,cancel_us"); for (const unrelated of [8, 128, 2048]) for (const waiters of [1, 8, 32]) { const origin = new Producer(); - origin.routePrefix(Path.from("pending")); + origin.claim(Path.from("pending")); const held = Array.from({ length: unrelated }, (_, i) => origin.request(Path.from(`pending/${i}`))); const wire = wireOf(origin.consume()); const samples: number[] = []; @@ -139,9 +139,9 @@ for (const failovers of [0, 1, 16, 128]) const sources: Broadcast[] = []; for (let i = 0; i < failovers; i++) { const instance = Instance.random(); - const primary = origin.routePrefix(prefix, { instance, cost: 0n }); + const primary = origin.claim(prefix, { instance, cost: 0n }); const ar = primary.requested(); - const br = origin.routePrefix(prefix, { instance, cost: 1n }).requested(); + const br = origin.claim(prefix, { instance, cost: 1n }).requested(); const held = origin.request(path); const source = new Broadcast(); sources.push(source); @@ -151,8 +151,8 @@ for (const failovers of [0, 1, 16, 128]) entries.push({ primary, ar, br, held }); } const instance = Instance.random(); - origin.routePrefix(prefix, { instance }); - for (let i = 0; i < extraRoutes; i++) origin.routePrefix(prefix, { instance, cost: BigInt(i + 1) }); + origin.claim(prefix, { instance }); + for (let i = 0; i < extraRoutes; i++) origin.claim(prefix, { instance, cost: BigInt(i + 1) }); const pending = []; for (const entry of entries) { entry.primary.close(); @@ -214,7 +214,7 @@ for (const operation of ["cancel-forward", "cancel-reverse", "drain-local"]) const settled: number[] = []; for (let round = 0; round < 4; round++) { const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("pending")); + const dynamic = origin.claim(Path.from("pending")); const requests = dynamic.requested(); const wire = wireOf(origin.consume()); const names = Array.from({ length: paths }, (_, i) => Path.from(`pending/${i}`)); @@ -272,7 +272,7 @@ for (const survivor of [false, true]) const origin = new Producer(); const prefix = Path.from("competing"); const path = Path.from("competing/touched"); - for (let i = 0; i < routes; i++) origin.routePrefix(prefix, { cost: BigInt(i) }); + for (let i = 0; i < routes; i++) origin.claim(prefix, { cost: BigInt(i) }); const wire = wireOf(origin.consume()); const kept = survivor ? new AbortController() : undefined; const remaining = kept ? wire.demand(path, undefined, kept.signal).catch(() => {}) : undefined; diff --git a/js/net/src/connection/forward.ts b/js/net/src/connection/forward.ts index 7f290064a14..f0c9346a967 100644 --- a/js/net/src/connection/forward.ts +++ b/js/net/src/connection/forward.ts @@ -9,7 +9,7 @@ import { type Dispose, race } from "@moq/signals"; import type * as Announce from "../announced.ts"; import { routesEqual, type WireRoute } from "../hop.ts"; import { coveringPrefixes } from "../internal.ts"; -import type { Producer as OriginProducer, Route } from "../origin.ts"; +import type { Claim, Producer as OriginProducer } from "../origin.ts"; import * as Path from "../path.ts"; import { after } from "../util/timer.ts"; import { type RequestSlot, wireOf } from "../wire.ts"; @@ -39,7 +39,7 @@ interface Interest { * request handing over to another never retracts it. The first reporter drives it. */ interface Reported { - handle: Route; + handle: Claim; /** Each request's latest route for the prefix. */ readonly reporters: Map; } @@ -290,7 +290,7 @@ export function forwardAnnounced(conn: Established, origin: OriginProducer): voi } /** Answer the requests under a received route by consuming them from the session. */ -async function drive(handle: Route, conn: Established): Promise { +async function drive(handle: Claim, conn: Established): Promise { const session = wireOf(conn); try { for await (const request of handle.requested()) { diff --git a/js/net/src/connection/pool.test.ts b/js/net/src/connection/pool.test.ts index 101114ca703..e3d67f125fb 100644 --- a/js/net/src/connection/pool.test.ts +++ b/js/net/src/connection/pool.test.ts @@ -259,7 +259,7 @@ test("a borrowed connection origin exposes live routes and dynamic serving", asy announcement = event; }); const prefix = Path.from("on-demand"); - const route = table.routePrefix(prefix); + const route = table.claim(prefix); await advance(); expect(announcement).toMatchObject({ kind: "present", prefix }); let withdrawal: unknown; diff --git a/js/net/src/group-id.test.ts b/js/net/src/group-id.test.ts index e17c1de620d..54754b10c3c 100644 --- a/js/net/src/group-id.test.ts +++ b/js/net/src/group-id.test.ts @@ -90,7 +90,7 @@ for (const wire of WIRES) { const datagrams = wire.datagrams ? publication.broadcast.createDatagrams("video") : undefined; const track = publication.broadcast.createTrack("video"); - const dynamic = relay.routePrefix(path); + const dynamic = relay.claim(path); const inputs: BroadcastConsumer[] = []; const forwarding = (async () => { for await (const request of dynamic.requested()) { diff --git a/js/net/src/ietf/datagram.test.ts b/js/net/src/ietf/datagram.test.ts index 951390840ea..1fd75f7454e 100644 --- a/js/net/src/ietf/datagram.test.ts +++ b/js/net/src/ietf/datagram.test.ts @@ -191,7 +191,7 @@ test("a relay shares one IETF subscription across stream and datagram readers", accept({ url, transport: upstream.server, publish: source.consume() }), ]); const original = wireOf(peers[0]).consume(path); - const requests = relay.routePrefix(path); + const requests = relay.claim(path); const cursor = requests.requested(); const routing = (async () => { for await (const request of cursor) request.serve(original); diff --git a/js/net/src/ietf/fetch.test.ts b/js/net/src/ietf/fetch.test.ts index bf0cbc5b5fd..cdff63b1950 100644 --- a/js/net/src/ietf/fetch.test.ts +++ b/js/net/src/ietf/fetch.test.ts @@ -505,7 +505,7 @@ test("a FETCH preserves relayed metadata and cached groups without upstream FETC while (await group?.readFrame()) {} group?.close(); } - const requests = fx.origin.routePrefix(Path.from("relayed")); + const requests = fx.origin.claim(Path.from("relayed")); const cursor = requests.requested(); const requested = cursor.next(); const type = { ...range(version, at(3, 0), at(3, 0)), trackNamespace: Path.from("relayed") }; diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index 4e00bb0a26d..ebf934aecca 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -276,7 +276,7 @@ test("TRACK_STATUS finished at once is answered on every draft", async () => { const pair = createMockTransportPair(ALPNS[version]); const session = new NativeSession(pair.server, version, true); const { pub, origin } = publisher(pair.server, { session }); - const requests = origin.routePrefix(Path.from("room")).requested(); + const requests = origin.claim(Path.from("room")).requested(); // The FIN arrives while the broadcast still resolves. const { stream, wire, finish } = requestStream(version); @@ -322,7 +322,7 @@ test("TRACK_STATUS outside the grant is refused on every draft", async () => { const session = new NativeSession(pair.server, version, true); const grant = new Signal(nothing()); const { pub, origin } = publisher(pair.server, { session, grant }); - const requests = origin.routePrefix(Path.from("room")).requested(); + const requests = origin.claim(Path.from("room")).requested(); const outside = requestStream(version); await pub.runTrackStatusRequest(trackStatus("room"), outside.stream); @@ -349,7 +349,7 @@ test("a second GOAWAY on an unanswered SUBSCRIBE closes the session", async () = const pair = createMockTransportPair(ALPNS[version]); const session = new NativeSession(pair.server, version, true); const { pub, origin } = publisher(pair.server, { session }); - const requests = origin.routePrefix(Path.from("room")).requested(); + const requests = origin.claim(Path.from("room")).requested(); const held = requestStream(version); const task = pub.runSubscribe( @@ -415,7 +415,7 @@ test("a TRACK_STATUS refusal that may pass invites a retry", async () => { const pair = createMockTransportPair(ALPNS[version]); const session = new NativeSession(pair.server, version, true); const { pub, origin } = publisher(pair.server, { session }); - const requests = origin.routePrefix(Path.from("room")).requested(); + const requests = origin.claim(Path.from("room")).requested(); const status = requestStream(version); const answering = pub.runTrackStatusRequest(trackStatus("room"), status.stream); @@ -450,7 +450,7 @@ test("a relay forwards an upstream SUBSCRIBE refusal's retry interval", async () const pair = createMockTransportPair(ALPNS[version]); const session = new NativeSession(pair.server, version, true); const { pub, origin } = publisher(pair.server, { session }); - const requests = origin.routePrefix(Path.from("room")).requested(); + const requests = origin.claim(Path.from("room")).requested(); const reader = requestStream(version); const subscribing = pub.runSubscribe( @@ -488,7 +488,7 @@ test("a cancelled TRACK_STATUS releases its demand on every draft", async () => const pair = createMockTransportPair(ALPNS[version]); const session = new NativeSession(pair.server, version, true); const { pub, origin } = publisher(pair.server, { session }); - const requests = origin.routePrefix(Path.from("room")).requested(); + const requests = origin.claim(Path.from("room")).requested(); // The broadcast is still resolving: its handler never answers. const early = requestStream(version); @@ -540,7 +540,7 @@ test("a SUBSCRIBE withdrawn during setup releases its demand on every draft", as const pair = createMockTransportPair(ALPNS[version]); const session = new NativeSession(pair.server, version, true); const { pub, origin } = publisher(pair.server, { session }); - const requests = origin.routePrefix(Path.from("room")).requested(); + const requests = origin.claim(Path.from("room")).requested(); // The broadcast is still resolving: its handler never answers. const early = requestStream(version); @@ -757,7 +757,7 @@ test("reserved namespace requests get DOES_NOT_EXIST while other dot namespaces // Navigation segments cannot be published. A covering application // route still proves these reserved requests are refused before lookup. const navigation = path.split("/")[0] === "."; - const claim = navigation ? origin.routePrefix(Path.empty()) : undefined; + const claim = navigation ? origin.claim(Path.empty()) : undefined; const requested = claim?.requested().next(); const broadcast = navigation ? undefined : publish(origin, Path.from(path)); const track = broadcast?.createTrack("video", { timescale: Timescale.MILLI }); @@ -1263,7 +1263,7 @@ test("a subscription outside a covering route's claim does not hear it", async ( const pair = createMockTransportPair(ALPN.DRAFT_18); const { pub, origin } = publisher(pair.server, { requiresSolicitation: true }); const chat = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.subtree(Path.from("room/chat"))])); - const dynamic = chat.routePrefix(Path.from("room")); + const dynamic = chat.claim(Path.from("room")); const subscription = await Stream.open(pair.client, { version: VERSION }); const accepted = await Stream.accept(pair.server, VERSION); @@ -1295,8 +1295,8 @@ test("a subscription hears the best covering route its claim allows", async () = const { pub, origin } = publisher(pair.server, { requiresSolicitation: true }); const scoped = (path: string) => origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.subtree(Path.from(path))])); - const chat = scoped("room/chat").routePrefix(Path.from("room"), { cost: 1n }); - const video = scoped("room/video").routePrefix(Path.from("room"), { cost: 5n }); + const chat = scoped("room/chat").claim(Path.from("room"), { cost: 1n }); + const video = scoped("room/video").claim(Path.from("room"), { cost: 5n }); const subscription = await Stream.open(pair.client, { version: VERSION }); const accepted = await Stream.accept(pair.server, VERSION); @@ -1336,8 +1336,8 @@ test("a subscription hears a broader covering route when the narrowest cannot se }); const chat = origin .scope(Path.empty(), new Path.Patterns([Path.Pattern.subtree(Path.from("tenant/chat"))])) - .routePrefix(Path.from("tenant")); - const broad = origin.routePrefix(Path.empty(), { cost: 5n }); + .claim(Path.from("tenant")); + const broad = origin.claim(Path.empty(), { cost: 5n }); const subscription = await Stream.open(pair.client, { version: VERSION }); const accepted = await Stream.accept(pair.server, VERSION); @@ -1374,7 +1374,7 @@ test("a covering route's claim is compared relative to the served root", async ( requiresSolicitation: true, }); const chat = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.subtree(Path.from("tenant/room/chat"))])); - const dynamic = chat.routePrefix(Path.from("tenant/room")); + const dynamic = chat.claim(Path.from("tenant/room")); const subscription = await Stream.open(pair.client, { version: VERSION }); const accepted = await Stream.accept(pair.server, VERSION); @@ -3710,7 +3710,7 @@ test("a paused relay subscription reacquires its upstream datagrams", async () = ]); const original = wireOf(peers[0]).consume(Path.from("test")); const relay = new OriginProducer(); - const requests = relay.routePrefix(Path.from("test")); + const requests = relay.claim(Path.from("test")); const cursor = requests.requested(); const routing = (async () => { for await (const request of cursor) request.serve(original); diff --git a/js/net/src/integration.test.ts b/js/net/src/integration.test.ts index 5c37972039c..14eddf13579 100644 --- a/js/net/src/integration.test.ts +++ b/js/net/src/integration.test.ts @@ -935,7 +935,7 @@ test("integration: a peer is served the cheaper route it was offered, not the lo const instance = Instance.random(); const localRoute = origin.route(path, { instance, cost: 5n }); const local = localRoute.broadcast; - const dynamic = origin.routePrefix(path, { instance, cost: 1n }); + const dynamic = origin.claim(path, { instance, cost: 1n }); const [client, server] = await Promise.all([ connect(url, { transport: pair.client }), @@ -2670,7 +2670,7 @@ test.each([Lite.ALPN_06, Lite.ALPN_07_WIP, Ietf.ALPN.DRAFT_18, Ietf.ALPN.DRAFT_2 const pair = createMockTransportPair(protocol); const origin = new OriginProducer(); const consumer = new OriginProducer(); - const handle = origin.routePrefix(Path.empty()); + const handle = origin.claim(Path.empty()); const held = new BroadcastProducer(); held.createTrack("chat", { timescale: Timescale.MILLI }).writeFrame(textFrame("hello")); const serving = (async () => { @@ -2705,7 +2705,7 @@ test.each([Lite.ALPN_06, Ietf.ALPN.DRAFT_18, Ietf.ALPN.DRAFT_22])( const pair = createMockTransportPair(protocol); const origin = new OriginProducer(); const consumer = new OriginProducer(); - const handle = origin.routePrefix(Path.empty()); + const handle = origin.claim(Path.empty()); const serving = (async () => { const requests = handle.requested(); const request = (await requests.next()).value; @@ -2745,7 +2745,7 @@ test.each(["request", "follow"] as const)( const origin = new OriginProducer(); const consumer = new OriginProducer(); const path = Path.from("live/cam"); - const handle = origin.routePrefix(Path.empty()); + const handle = origin.claim(Path.empty()); const serving = (async () => { const requests = handle.requested(); const request = (await requests.next()).value; diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index 59ad1f9ac55..49dd740c65c 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -732,7 +732,7 @@ async function servedSubscription( broadcast = new BroadcastProducer(); const front = new Front(); front.serve(broadcast.consume()); - const dynamic = origin.routePrefix(Path.from("test")); + const dynamic = origin.claim(Path.from("test")); void (async () => { for await (const request of dynamic.requested()) request.serve(front.consumer); })(); @@ -3235,7 +3235,7 @@ test("lite draft-06: closing while announces wait for the setup grant does not h test("lite draft-06: a grant that shrinks while a TRACK resolves refuses it", async () => { const pair = createMockTransportPair(ALPN_06); const origin = new OriginProducer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const requests = handle.requested(); const grant = new Signal(grantOf("live")); const publisher = new Publisher(pair.server, Version.DRAFT_06, randomHop(), origin.consume(), { @@ -3276,7 +3276,7 @@ test("lite draft-06: a grant that shrinks while a TRACK resolves refuses it", as test("lite draft-06: a grant that shrinks while TRACK_INFO is blocked resets it", async () => { const pair = createMockTransportPair(ALPN_06); const origin = new OriginProducer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const requests = handle.requested(); const grant = new Signal(grantOf("live")); const publisher = new Publisher(pair.server, Version.DRAFT_06, randomHop(), origin.consume(), { @@ -3339,7 +3339,7 @@ test("lite draft-06: a grant that shrinks while TRACK_INFO is blocked resets it" test("lite draft-06: a grant that shrinks while the broadcast resolves resets the subscription", async () => { const pair = createMockTransportPair(ALPN_06); const origin = new OriginProducer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const requests = handle.requested(); const grant = new Signal(grantOf("live")); const publisher = new Publisher(pair.server, Version.DRAFT_06, randomHop(), origin.consume(), { diff --git a/js/net/src/lite/tracks.test.ts b/js/net/src/lite/tracks.test.ts index cd3beebc5ab..69e50891b4c 100644 --- a/js/net/src/lite/tracks.test.ts +++ b/js/net/src/lite/tracks.test.ts @@ -405,7 +405,7 @@ test("a newer listing of a broadcast on one session replaces the older", async ( test("a path served through a covering prefix route is NOT_FOUND", async () => { const origin = new OriginProducer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); void (async () => { for await (const request of dynamic.requested()) { const served = new BroadcastProducer(); @@ -422,7 +422,7 @@ test("a path served through a covering prefix route is NOT_FOUND", async () => { test("a local read through a covering prefix route is NOT_FOUND, and through its exact route lists", async () => { const origin = new OriginProducer(); for (const prefix of ["room", "room/bob"]) { - const dynamic = origin.routePrefix(Path.from(prefix)); + const dynamic = origin.claim(Path.from(prefix)); void (async () => { for await (const request of dynamic.requested()) { const served = new BroadcastProducer(); @@ -524,7 +524,7 @@ test("an instance-pinned front lists its serving route's tracks", async () => { test("a front pinned to a named instance served through a covering prefix route is NOT_FOUND", async () => { const origin = new OriginProducer(); - const dynamic = origin.routePrefix(Path.from("room"), { instance: Instance.parse("named") }); + const dynamic = origin.claim(Path.from("room"), { instance: Instance.parse("named") }); void (async () => { for await (const request of dynamic.requested()) { const served = new BroadcastProducer(); diff --git a/js/net/src/origin-demand.test.ts b/js/net/src/origin-demand.test.ts index a3511747e5d..0675f3b62ee 100644 --- a/js/net/src/origin-demand.test.ts +++ b/js/net/src/origin-demand.test.ts @@ -27,7 +27,7 @@ test.each(["lite", "ietf", "fetch", "track"] as const)( async (kind) => { const pair = createMockTransportPair(); const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); const publisher = kind === "ietf" ? new IetfPublisher({ @@ -106,7 +106,7 @@ test.each(["lite", "ietf", "fetch", "track"] as const)( test("last cancellation finishes the internal wait and discards a late consumer", async () => { const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); const requests = dynamic.requested(); const hold = new AbortController(); const wait = wireOf(origin.consume()).demand(path, undefined, hold.signal); @@ -149,7 +149,7 @@ test.each([true, false])( "shared local/remote demand is withdrawn whichever leaves last (local first: %s)", async (localFirst) => { const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); const requests = dynamic.requested(); const hold = new AbortController(); const wait = wireOf(origin.consume()) @@ -193,7 +193,7 @@ test.each([ ] as const)("cancelling one waiter preserves a second %s requester across %i routes", async (other, routes) => { const origin = new Producer(); const prefix = Path.from("room"); - const dynamics = Array.from({ length: routes }, (_, i) => origin.routePrefix(prefix, { cost: BigInt(i) })); + const dynamics = Array.from({ length: routes }, (_, i) => origin.claim(prefix, { cost: BigInt(i) })); const hold = new AbortController(); const wire = wireOf(origin.consume()); const first = wire.demand(path, undefined, hold.signal).catch(() => undefined); @@ -223,7 +223,7 @@ test.each([ test("an already cancelled signal never enqueues or subscribes to abort", async () => { const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); const requests = dynamic.requested(); const hold = new AbortController(); hold.abort(); @@ -245,7 +245,7 @@ test.each(["accept", "reject", "cancel"] as const)( "%s releases the abort listener without closing a shared producer", async (action) => { const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); const requests = dynamic.requested(); const source = new Broadcast(); const keeper = source.consume(); @@ -281,12 +281,12 @@ test.each(["accept", "reject", "cancel"] as const)( test("a pending local request changing routes withdraws the old route's work", async () => { const origin = new Producer(); - const first = origin.routePrefix(Path.from("room"), { cost: 5n }); + const first = origin.claim(Path.from("room"), { cost: 5n }); const a = first.requested(); const local = origin.request(path); const old = (await a.next()).value; if (!old) throw new Error("expected a pending request"); - const second = origin.routePrefix(Path.from("room"), { cost: 1n }); + const second = origin.claim(Path.from("room"), { cost: 1n }); const b = second.requested(); const fresh = (await b.next()).value; if (!fresh) throw new Error("expected a pending request"); @@ -314,7 +314,7 @@ test("a pending local request changing routes withdraws the old route's work", a test("cancelling an old instance waiter does not decrement a new instance's demand", async () => { const origin = new Producer(); const instance = Instance.random(); - const dynamic = origin.routePrefix(Path.from("room"), { instance }); + const dynamic = origin.claim(Path.from("room"), { instance }); const requests = dynamic.requested(); const wire = wireOf(origin.consume()); const hold = new AbortController(); @@ -346,8 +346,8 @@ test.each(["answer", "release"] as const)( const origin = new Producer(); const instance = Instance.random(); const prefix = Path.from("room"); - const a = origin.routePrefix(prefix, { instance, cost: 1n }); - const b = origin.routePrefix(prefix, { instance, cost: 5n }); + const a = origin.claim(prefix, { instance, cost: 1n }); + const b = origin.claim(prefix, { instance, cost: 5n }); const ar = a.requested(); const br = b.requested(); const held = origin.request(path); @@ -355,7 +355,7 @@ test.each(["answer", "release"] as const)( (await ar.next()).value.serve(source); await settle(); // Another instance wins new requests. The old handle stays on its own instance. - const c = origin.routePrefix(prefix, { instance: Instance.random(), cost: 0n }); + const c = origin.claim(prefix, { instance: Instance.random(), cost: 0n }); a.close(); await settle(); const pending = (await br.next()).value; @@ -407,8 +407,8 @@ test.each([0, 1])( // Each instance undercuts the last, so it wins the path for the request made now. const instance = Instance.parse(`instance-${i + 1}`); const cost = BigInt(4 - 2 * i); - const primary = origin.routePrefix(prefix, { instance, cost }); - const standby = origin.routePrefix(prefix, { instance, cost: cost + 1n }); + const primary = origin.claim(prefix, { instance, cost }); + const standby = origin.claim(prefix, { instance, cost: cost + 1n }); const ar = primary.requested(); const br = standby.requested(); const held = origin.request(path); @@ -418,7 +418,7 @@ test.each([0, 1])( await settle(); entries.push({ primary, ar, br, held }); } - origin.routePrefix(prefix, { instance: Instance.parse("instance-3"), cost: 0n }); + origin.claim(prefix, { instance: Instance.parse("instance-3"), cost: 0n }); const pending = []; for (const entry of entries) { entry.primary.close(); @@ -459,7 +459,7 @@ test.each([0, 1])( test("a normal FETCH request FIN keeps unanswered origin demand alive", async () => { const pair = createMockTransportPair(); const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); const requests = dynamic.requested(); const publisher = new LitePublisher(pair.server, LiteVersion.DRAFT_06, randomHop(), origin.consume()); let input!: ReadableStreamDefaultController; @@ -500,7 +500,7 @@ test.each(["accept", "reject"] as const)( "cancellation racing %s releases only the cancelled waiter", async (answer) => { const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); const requests = dynamic.requested(); const wire = wireOf(origin.consume()); const hold = new AbortController(); @@ -529,7 +529,7 @@ test.each(["accept", "reject"] as const)( test.each([true, false])("last waiter cancellation and accept in one turn (cancel first: %s)", async (cancelFirst) => { const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); const requests = dynamic.requested(); const wire = wireOf(origin.consume()); const hold = new AbortController(); @@ -570,7 +570,7 @@ test.each([true, false])("last waiter cancellation and accept in one turn (cance test.each([true, false])("local demand survives same-turn cancellation only when rejoined: %s", async (rejoin) => { const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); const requests = dynamic.requested(); const local = origin.request(path); const hold = new AbortController(); @@ -616,7 +616,7 @@ test.each([true, false])("local demand survives same-turn cancellation only when test("queued cancellation preserves order, replacement identity, and empty-queue wakeup", async () => { const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); const requests = dynamic.requested(); const wire = wireOf(origin.consume()); const holds = Array.from({ length: 4 }, () => new AbortController()); @@ -642,7 +642,7 @@ test("queued cancellation preserves order, replacement identity, and empty-queue test("reset clears queued work while a handler is suspended and admits the new instance", async () => { const origin = new Producer(); const instance = Instance.random(); - const dynamic = origin.routePrefix(Path.from("room"), { instance }); + const dynamic = origin.claim(Path.from("room"), { instance }); const requests = dynamic.requested(); const wire = wireOf(origin.consume()); const waits = [path, Path.from("room/obsolete")].map((name) => wire.demand(name, instance).catch(() => {})); @@ -666,7 +666,7 @@ test("reset clears queued work while a handler is suspended and admits the new i test("concurrent handlers consume queued requests once across empty batches", async () => { const origin = new Producer(); - const dynamic = origin.routePrefix(Path.from("room")); + const dynamic = origin.claim(Path.from("room")); const handlers = [dynamic.requested(), dynamic.requested()]; const wire = wireOf(origin.consume()); const waits: Promise[] = []; diff --git a/js/net/src/origin-request.test.ts b/js/net/src/origin-request.test.ts index 01b77ae4888..ea7accf8a22 100644 --- a/js/net/src/origin-request.test.ts +++ b/js/net/src/origin-request.test.ts @@ -160,7 +160,7 @@ test("followers track the serving prefix, ignoring descendants and re-prices", a const origin = new Producer(); const source = new BroadcastProducer(); const keeper = source.consume(); - const prefix = origin.routePrefix(Path.from("pool")); + const prefix = origin.claim(Path.from("pool")); const serving = (async () => { for await (const request of prefix.requested()) request.serve(source.consume()); })(); @@ -196,7 +196,7 @@ test("followers track the serving prefix, ignoring descendants and re-prices", a test("a follower ignores a covering route whose scope excludes its path", async () => { const origin = new Producer(); const scoped = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("room/*/chat")])); - const prefix = scoped.routePrefix(Path.from("room/alice")); + const prefix = scoped.claim(Path.from("room/alice")); const exactRoute = origin.route(Path.from("room/alice"), { cost: 5n }); const exact = exactRoute.broadcast; const request = origin.follow(Path.from("room/alice")); @@ -213,7 +213,7 @@ test("a follower tracks a route replaced by an identical one", async () => { const origin = new Producer(); const path = Path.from("room"); const serve = (source: BroadcastProducer) => { - const route = origin.routePrefix(path); + const route = origin.claim(path); void (async () => { for await (const request of route.requested()) request.serve(source.consume()); })(); @@ -244,7 +244,7 @@ test("an origin closing settles a follower a served route resolved", async () => const origin = new Producer(); const path = Path.from("room"); const source = new BroadcastProducer(); - const route = origin.routePrefix(path); + const route = origin.claim(path); void (async () => { for await (const request of route.requested()) request.serve(source.consume()); })(); @@ -263,7 +263,7 @@ test("an origin closing settles a follower a served route resolved", async () => test("a follower keeps a refusal that lands with a re-price", async () => { const origin = new Producer(); const path = Path.from("room"); - const route = origin.routePrefix(path); + const route = origin.claim(path); const requested = route.requested(); const request = origin.follow(path); const pending = (await requested.next()).value; @@ -294,7 +294,7 @@ for (const received of [false, true]) { const events: string[] = []; const stop = wireOf(origin).interests((prefix, wanted) => events.push(`${prefix} ${wanted}`)); const source = new BroadcastProducer(); - const route = received ? wireOf(origin).receive(path, WireRoute.default) : origin.routePrefix(path); + const route = received ? wireOf(origin).receive(path, WireRoute.default) : origin.claim(path); void (async () => { for await (const request of route.requested()) request.serve(source.consume()); })(); @@ -318,7 +318,7 @@ for (const received of [false, true]) { test("a hidden job route is hidden until announced under its own instance", async () => { const origin = new Producer(); const path = Path.from("room/alice"); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const requests = claim.requested(); const request = origin.request(path); const pending = (await requests.next()).value; @@ -339,7 +339,7 @@ test("a hidden job route is hidden until announced under its own instance", asyn test("a visible job route answers its waiting requesters at once", async () => { const origin = new Producer(); const path = Path.from("room/alice"); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const requests = claim.requested(); const first = origin.request(path); const pending = (await requests.next()).value; @@ -375,7 +375,7 @@ test("a visible job route answers its waiting requesters at once", async () => { test("a hidden job route's broadcast cannot announce itself", async () => { const origin = new Producer(); const path = Path.from("room/alice"); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const requests = claim.requested(); const request = origin.request(path); const pending = (await requests.next()).value; @@ -396,7 +396,7 @@ test("a hidden job route's broadcast cannot announce itself", async () => { test("an application serves held content without an exact route", async () => { const origin = new Producer(); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const requests = claim.requested(); const request = origin.request(Path.from("room/alice")); const pending = (await requests.next()).value; @@ -418,7 +418,7 @@ test("an application serves held content without an exact route", async () => { for (const withdraw of ["withdraw", "replace"] as const) { test(`a job's route is not cached after ${withdraw}`, async () => { const origin = new Producer(); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const requests = claim.requested(); const path = Path.from("room/alice"); const first = origin.request(path); @@ -446,7 +446,7 @@ for (const withdraw of ["withdraw", "replace"] as const) { test("closing a hidden job route refuses the request and closes its broadcast", async () => { const origin = new Producer(); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const requests = claim.requested(); const request = origin.request(Path.from("room/alice")); const pending = (await requests.next()).value; @@ -465,7 +465,7 @@ test("closing a hidden job route refuses the request and closes its broadcast", test("a job route for an abandoned claim is never announced", async () => { const origin = new Producer(); const path = Path.from("room/alice"); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const requests = claim.requested(); const request = origin.request(path); const pending = (await requests.next()).value; @@ -487,7 +487,7 @@ for (const cleanup of ["close", "dispose", "broadcast"] as const) { test(`a hidden job route's ${cleanup} releases shared requesters and admits a new request`, async () => { const origin = new Producer(); const path = Path.from("room/alice"); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const requests = claim.requested(); const first = origin.request(path); const pending = (await requests.next()).value; @@ -523,7 +523,7 @@ for (const cleanup of ["close", "dispose", "broadcast"] as const) { test("a throwing handler disposes its job route and leaves the claim answerable", async () => { const origin = new Producer(); const path = Path.from("room/alice"); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const failed = (async () => { for await (const request of claim.requested()) { using job = request.route({ hidden: true }); @@ -552,7 +552,7 @@ test("a throwing handler disposes its job route and leaves the claim answerable" test("announcing a job route again keeps it answering under one instance", async () => { const origin = new Producer(); const path = Path.from("room/alice"); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const requests = claim.requested(); const request = origin.request(path); const pending = (await requests.next()).value; @@ -577,7 +577,7 @@ for (const cleanup of ["close", "dispose", "broadcast", "announce"] as const) { test(`an old job route's ${cleanup} cannot refuse the next request for its path`, async () => { const origin = new Producer(); const path = Path.from("room/alice"); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const requests = claim.requested(); const first = origin.request(path); const pending = (await requests.next()).value; @@ -631,7 +631,7 @@ test("an instance-pinned follower resumes when its instance returns after a gap" const source = new BroadcastProducer(); const keeper = source.consume(); const serve = (instance: Instance.Valid, broadcast: BroadcastProducer) => { - const route = origin.routePrefix(path, { instance: instance }); + const route = origin.claim(path, { instance: instance }); void (async () => { for await (const request of route.requested()) request.serve(broadcast.consume()); })(); @@ -782,7 +782,7 @@ test("a pending request waits for a session before concluding absence", async () test("a follower retains a selected handler's explicit unroutable refusal", async () => { const origin = new Producer(); const path = Path.from("room/audio"); - const route = origin.routePrefix(path); + const route = origin.claim(path); const pending = route.requested(); const requested = origin.follow(path); const request = (await pending.next()).value; @@ -799,14 +799,14 @@ test("a follower retains a selected handler's explicit unroutable refusal", asyn test("a pending request retries a route gap and never retargets after resolving", async () => { const origin = new Producer(); const path = Path.from("room/audio"); - const first = origin.routePrefix(path); + const first = origin.claim(path); const requested = origin.request(path); const before = await first.requested().next(); expect(before.value).toBeDefined(); first.close(); await settle(); expect(requested.closed.peek()).toBeUndefined(); - const second = origin.routePrefix(path); + const second = origin.claim(path); const pending = (await second.requested().next()).value; if (!pending) throw new Error("replacement route was not requested"); const source = new BroadcastProducer(); @@ -852,8 +852,8 @@ test.each(["request", "follow"] as const)("a %s pinned to a losing instance reso const origin = new Producer(); const path = Path.from("room/audio"); const pinned = Instance.random(); - const losing = origin.routePrefix(path, { instance: pinned, cost: 9n }); - const winning = origin.routePrefix(path, { instance: Instance.random(), cost: 1n }); + const losing = origin.claim(path, { instance: pinned, cost: 9n }); + const winning = origin.claim(path, { instance: Instance.random(), cost: 1n }); const asked = losing.requested(); const requested = origin[method](path, { instance: pinned }); const pending = (await asked.next()).value; @@ -893,7 +893,7 @@ test("a peer's pin is served by a local broadcast that loses the path", async () const path = Path.from("room/audio"); const pinned = Instance.random(); const publication = origin.route(path, { instance: pinned, cost: 9n }); - const winning = origin.routePrefix(path, { instance: Instance.random(), cost: 1n }); + const winning = origin.claim(path, { instance: Instance.random(), cost: 1n }); expect(wire.local(path)).toBeUndefined(); expect(wire.local(path, pinned)).toBeDefined(); expect(await wire.demand(path, pinned)).toBeDefined(); @@ -907,7 +907,7 @@ test("a peer's pin is served by a local broadcast that loses the path", async () test("a peer's pin reaches its job after a sibling moved the claim on", async () => { const origin = new Producer(); const wire = wireOf(origin.consume()); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const minted = claim.instance; const requests = claim.requested(); const reader = origin.request(Path.from("room/alice")); @@ -938,7 +938,7 @@ test("a peer's pin reaches its job after a sibling moved the claim on", async () test.each(["request", "follow"] as const)("a %s through a claim continues on its job's route", async (method) => { const origin = new Producer(); const path = Path.from("room/alice"); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const minted = claim.instance; const requests = claim.requested(); const reader = method === "request" ? origin.request(path) : origin.follow(path); @@ -978,7 +978,7 @@ test("a restarted job gets a fresh instance and its old one is refused", async ( const origin = new Producer(); const wire = wireOf(origin.consume()); const path = Path.from("room/alice"); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const minted = claim.instance; const requests = claim.requested(); const first = origin.request(path); @@ -1015,7 +1015,7 @@ test("a restarted job gets a fresh instance and its old one is refused", async ( // when an unrelated job ends keeps its request and answers it under the claim's new instance. test("a hidden job announces under the instance its claim moved to", async () => { const origin = new Producer(); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const minted = claim.instance; const requests = claim.requested(); const alice = origin.request(Path.from("room/alice")); @@ -1047,7 +1047,7 @@ test("a hidden job announces under the instance its claim moved to", async () => // the worker, which prepares the job under the claim's new instance. Every requester waits on. test("a job that read its instance is refused once its claim moves", async () => { const origin = new Producer(); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const minted = claim.instance; const requests = claim.requested(); const alice = origin.request(Path.from("room/alice")); @@ -1088,7 +1088,7 @@ test("a job that read its instance is refused once its claim moves", async () => // the claim when it ends. test("one job ending leaves another job's instance alone", async () => { const origin = new Producer(); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const minted = claim.instance; const requests = claim.requested(); const jobs = []; @@ -1124,7 +1124,7 @@ test("one job ending leaves another job's instance alone", async () => { test("a claim naming its instance gives each job a fresh one", async () => { const origin = new Producer(); const stable = Instance.parse("stable"); - const claim = origin.routePrefix(Path.from("room"), { instance: stable, epoch: 1n }); + const claim = origin.claim(Path.from("room"), { instance: stable, epoch: 1n }); const requests = claim.requested(); const request = origin.request(Path.from("room/alice")); const pending = (await requests.next()).value; @@ -1144,7 +1144,7 @@ test("a claim naming its instance gives each job a fresh one", async () => { // request for a held path is answered again without asking the handler, under the new instance. test("a claim moving on keeps its held answers", async () => { const origin = new Producer(); - const claim = origin.routePrefix(Path.from("room")); + const claim = origin.claim(Path.from("room")); const minted = claim.instance; const requests = claim.requested(); const held = new BroadcastProducer(); diff --git a/js/net/src/origin.test.ts b/js/net/src/origin.test.ts index 77833c9937b..c78aac8da43 100644 --- a/js/net/src/origin.test.ts +++ b/js/net/src/origin.test.ts @@ -146,7 +146,7 @@ test("a borrowed table exposes dynamic serving and a live scoped broadcast map", expect(changes.some((value) => value.get(localPath)?.cost === 4n)).toBe(true); const prefix = Path.from("room"); - const dynamic = table.routePrefix(prefix, { cost: 2n }); + const dynamic = table.claim(prefix, { cost: 2n }); await new Promise((resolve) => setImmediate(resolve)); expect(live.peek().get(prefix)).toEqual(WireRoute.normalize({ ...wireOf(dynamic).info, cost: 2n })); dynamic.setCost(3n); @@ -1086,8 +1086,8 @@ test("a hidden route is invisible to everyone until announce", async () => { test("closing the origin ends a hidden or withdrawn prefix route's requests", async () => { const origin = new Producer(); - const hidden = origin.routePrefix(Path.from("hidden"), { hidden: true }); - const withdrawn = origin.routePrefix(Path.from("withdrawn")); + const hidden = origin.claim(Path.from("hidden"), { hidden: true }); + const withdrawn = origin.claim(Path.from("withdrawn")); withdrawn.withdraw(); const pending = [hidden.requested().next(), withdrawn.requested().next()]; @@ -1097,7 +1097,7 @@ test("closing the origin ends a hidden or withdrawn prefix route's requests", as test("a prefix route refuses to announce or re-price once its origin closed, like an exact one", () => { const origin = new Producer(); - const prefix = origin.routePrefix(Path.from("live")); + const prefix = origin.claim(Path.from("live")); const exact = origin.route(Path.from("room")); origin.close(); expect(prefix.announced).toBe(false); @@ -1107,13 +1107,12 @@ test("a prefix route refuses to announce or re-price once its origin closed, lik expect(() => exact.setCost(1n)).toThrow(); }); -test("a prefix route can start hidden, withdraw and come back while it keeps yielding requests", async () => { +test("a claim can start hidden, withdraw and come back while it keeps yielding requests", async () => { const origin = new Producer(); const consumer = origin.consume(); const prefix = Path.from("jobs"); const path = Path.from("jobs/a"); - const route = origin.routePrefix(prefix, { hidden: true, cost: 3n }); - expect(() => route.broadcast).toThrow("a prefix route owns no broadcast"); + const route = origin.claim(prefix, { hidden: true, cost: 3n }); expect(route.announced).toBe(false); expect(wireOf(consumer).routes(path)).toBe(false); const requests = route.requested(); @@ -1154,15 +1153,14 @@ test("a prefix route can start hidden, withdraw and come back while it keeps yie dropped.close(); route.close(); expect((await requests.next()).done).toBe(true); - expect(() => route.announce()).toThrow("route is closed"); + expect(() => route.announce()).toThrow("claim is closed"); source.close(); origin.close(); }); -test("an exact route yields no requests", async () => { +test("closing an exact route closes its broadcast", () => { const origin = new Producer(); const route = origin.route(Path.from("room")); - expect((await route.requested().next()).done).toBe(true); route.close(); expect(route.broadcast.closed.peek()).toBeNull(); origin.close(); @@ -1258,7 +1256,7 @@ test("the cheapest received route competes with the local broadcast, not the new test("a handle serves a request under live", async () => { const origin = new Producer(); const consumer = origin.consume(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); expect(await consumer.routes().next()).toMatchObject({ prefix: Path.from("live"), kind: "start" }); @@ -1285,7 +1283,7 @@ test("a handle serves a request under live", async () => { test("an originated route serves held content a session delivered", async () => { const origin = new Producer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const it = handle.requested(); const pending = wireOf(origin.consume()).demand(Path.from("live/cam")); const { value: req } = await it.next(); @@ -1323,7 +1321,7 @@ test("a received route still serves a broadcast a session delivered", async () = test("a re-priced route is delivered as an update", async () => { const origin = new Producer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const announced = origin.consume().routes(); expect(await announced.next()).toMatchObject({ prefix: Path.from("live"), kind: "start" }); handle.setCost(5n); @@ -1336,7 +1334,7 @@ test("a re-priced route is delivered as an update", async () => { test("an accepted dynamic broadcast is retired when it closes, and its handle resumes", async () => { const origin = new Producer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const path = Path.from("live/cam"); const request = origin.request(path); const it = handle.requested(); @@ -1370,7 +1368,7 @@ test("an accepted dynamic broadcast is retired when it closes, and its handle re test("reject surfaces the error from demand", async () => { const origin = new Producer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const consumer = origin.consume(); const it = handle.requested(); const pending = wireOf(consumer).demand(Path.from("live/cam")); @@ -1387,8 +1385,8 @@ test("a peer is offered and served the cheapest originated route", async () => { const origin = new Producer(); const consumer = origin.consume(); const prefix = Path.from("live"); - const cheap = origin.routePrefix(prefix, { instance: INSTANCE, cost: 1n }); - const pricey = origin.routePrefix(prefix, { instance: INSTANCE, cost: 10n }); + const cheap = origin.claim(prefix, { instance: INSTANCE, cost: 1n }); + const pricey = origin.claim(prefix, { instance: INSTANCE, cost: 10n }); expect(wireOf(consumer).advertised.peek()?.get(prefix)?.[0]?.route).toEqual( WireRoute.normalize({ instance: INSTANCE, cost: 1n }), @@ -1419,7 +1417,7 @@ test("a peer is offered and served the cheapest originated route", async () => { test("a shared reject still surfaces from demand", async () => { const origin = new Producer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const consumer = origin.consume(); const it = handle.requested(); @@ -1441,7 +1439,7 @@ test("a shared reject still surfaces from demand", async () => { test("a request refusal does not keep demand from asking again", async () => { const origin = new Producer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const consumer = origin.consume(); const it = handle.requested(); @@ -1465,7 +1463,7 @@ test("a request refusal does not keep demand from asking again", async () => { test("advancing requested without settling rejects the previous request", async () => { const origin = new Producer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const consumer = origin.consume(); const it = handle.requested(); @@ -1489,7 +1487,7 @@ test("advancing requested without settling rejects the previous request", async test("a rejected request is not asked of the same route again", async () => { const origin = new Producer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const it = handle.requested(); const request = origin.request(Path.from("live/cam")); @@ -1813,8 +1811,8 @@ test("a request ends when its winning source goes, even with a standby", async ( test("a refusal is terminal, never falling through to a broader route", async () => { const origin = new Producer(); const consumer = origin.consume(); - const narrow = origin.routePrefix(Path.from("live")); - const wide = origin.routePrefix(Path.from("")); + const narrow = origin.claim(Path.from("live")); + const wide = origin.claim(Path.from("")); const wideRequests = wide.requested(); const wideAsked = wideRequests.next(); @@ -1850,8 +1848,8 @@ test("a better route's refusal ends a served request", async () => { // The narrower route is asked while the broad one keeps serving, then says no. A // costlier sibling at the same prefix could serve, but is never asked. - const narrow = origin.routePrefix(Path.from("live"), { instance: INSTANCE, cost: 1n }); - const sibling = origin.routePrefix(Path.from("live"), { instance: INSTANCE, cost: 2n }); + const narrow = origin.claim(Path.from("live"), { instance: INSTANCE, cost: 1n }); + const sibling = origin.claim(Path.from("live"), { instance: INSTANCE, cost: 2n }); const siblingRequests = sibling.requested(); const siblingAsked = siblingRequests.next(); const { value: req } = await narrow.requested().next(); @@ -1876,14 +1874,14 @@ test("a better route's refusal ends a served request", async () => { test("a refusal from a superseded route does not end the request", async () => { const origin = new Producer(); const consumer = origin.consume(); - const wide = origin.routePrefix(Path.from("")); + const wide = origin.claim(Path.from("")); const wideRequests = wide.requested(); const request = consumer.request(Path.from("live/cam")); const { value: stale } = await wideRequests.next(); // A narrower route takes over the pending request before the broad one answers. - const narrow = origin.routePrefix(Path.from("live")); + const narrow = origin.claim(Path.from("live")); const { value: req } = await narrow.requested().next(); stale?.reject(new Error("unserved")); await settle(); @@ -1905,7 +1903,7 @@ test("a refusal from a superseded route does not end the request", async () => { test("a refusal from a route a local broadcast superseded does not end the request", async () => { const origin = new Producer(); const consumer = origin.consume(); - const wide = origin.routePrefix(Path.from("live")); + const wide = origin.claim(Path.from("live")); const wideRequests = wide.requested(); const request = consumer.request(Path.from("live/cam")); @@ -1931,7 +1929,7 @@ test("a refusal from a route a local broadcast superseded does not end the reque test("close rejects queued requests as unroutable", async () => { const origin = new Producer(); - const handle = origin.routePrefix(Path.from("live")); + const handle = origin.claim(Path.from("live")); const waiting = handle.requested().next(); const request = origin.request(Path.from("live/cam")); const { value: req } = await waiting; @@ -1969,9 +1967,9 @@ test("announced lists full names while covering views and session advertisements const origin = new Producer(); const patterns = new Path.Patterns([Path.Pattern.parse("*.hang"), Path.Pattern.parse("**/*.chat")]); const reader = origin.scope(Path.from("project"), patterns).consume(); - const cam = origin.routePrefix(Path.from("project/cam.hang")); - const overlap = origin.routePrefix(Path.from("project/room/mic.hang")); - const chat = origin.routePrefix(Path.from("project/lobby.chat")); + const cam = origin.claim(Path.from("project/cam.hang")); + const overlap = origin.claim(Path.from("project/room/mic.hang")); + const chat = origin.claim(Path.from("project/lobby.chat")); const selected = await announcedView(reader); const covering = await announcedView(reader, undefined, { covering: true }); const all = [Path.from("cam.hang"), Path.from("lobby.chat"), Path.from("room/mic.hang")]; @@ -1979,7 +1977,7 @@ test("announced lists full names while covering views and session advertisements expect([...covering.peek().keys()].sort()).toEqual(all); expect(Array.from(wireOf(reader).advertised.peek()?.keys() ?? []).sort()).toEqual(all); - const nested = origin.routePrefix(Path.from("project/room/lobby.chat")); + const nested = origin.claim(Path.from("project/room/lobby.chat")); await new Promise((resolve) => setImmediate(resolve)); expect(selected.peek().has(Path.from("room/lobby.chat"))).toBe(true); overlap.setCost(2n); @@ -2002,7 +2000,7 @@ test("announced filters before rooting and retains lifecycle, routing and watch const interests: string[] = []; const unlisten = wireOf(origin).interests((prefix, wanted) => interests.push(`${wanted ? "+" : "-"}${prefix}`)); const source = new BroadcastProducer(); - const broad = origin.routePrefix(Path.from("room")); + const broad = origin.claim(Path.from("room")); const stream = reader.routes(); const events = stream[Symbol.asyncIterator](); const covering = await announcedView(reader, undefined, { covering: true }); @@ -2017,7 +2015,7 @@ test("announced filters before rooting and retains lifecycle, routing and watch expect(request.active.peek()).toBeDefined(); request.close(); - const exact = origin.routePrefix(root, { instance: INSTANCE }); + const exact = origin.claim(root, { instance: INSTANCE }); expect(await events.next()).toMatchObject({ value: { kind: "start", prefix: Path.empty(), captures: expect.any(Array) }, }); @@ -2169,7 +2167,7 @@ test("a rooted producer shares the table and enforces its pattern union", async await new Promise((resolve) => setImmediate(resolve)); expect(() => scoped.request(Path.from("room/alice/deep"))).toThrow("outside the origin scope"); await new Promise((resolve) => setImmediate(resolve)); - expect(() => scoped.routePrefix(Path.from("other"))).toThrow("outside the origin scope"); + expect(() => scoped.claim(Path.from("other"))).toThrow("outside the origin scope"); await new Promise((resolve) => setImmediate(resolve)); expect(() => scoped.scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("other/**")]))).toThrow( "do not overlap", @@ -2197,8 +2195,8 @@ test("closing a derived handle releases only what it registered", async () => { const scoped = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.subtree(Path.from("room"))])); const wide = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.all()])); const inside = publish(scoped, Path.from("room/alice")); - const claim = scoped.routePrefix(Path.from("room/claim")); - const ranked = wide.routePrefix(Path.from("ranked")); + const claim = scoped.claim(Path.from("room/claim")); + const ranked = wide.claim(Path.from("ranked")); const peer = serve(scoped, Path.from("room/peer"), provider(new BroadcastProducer())); scoped.close(); @@ -2212,7 +2210,7 @@ test("closing a derived handle releases only what it registered", async () => { // A released handle refuses new work, so a borrower notices instead of publishing into nothing. expect(() => scoped.route(Path.from("room/late"), { hidden: true }).broadcast).toThrow("origin handle is closed"); - scoped.routePrefix(Path.from("room/late")).close(); + scoped.claim(Path.from("room/late")).close(); expect((await announcedView(origin)).peek().has(Path.from("room/late"))).toBe(false); // The owner and fresh handles keep working. @@ -2310,7 +2308,7 @@ test("closing a derived handle withdraws the sessions and answers attached throu test("a scoped dynamic only serves allowed paths and presents relative requests", async () => { const origin = new Producer(); const scoped = origin.scope(Path.from("tenant"), new Path.Patterns([Path.Pattern.parse("room/*/chat")])); - const dynamic = scoped.routePrefix(Path.from("room")); + const dynamic = scoped.claim(Path.from("room")); await new Promise((resolve) => setImmediate(resolve)); const denied = origin.request(Path.from("tenant/room/alice/video")); await new Promise((resolve) => setImmediate(resolve)); @@ -2355,9 +2353,7 @@ test("scoped wire views filter and rebase advertisements and blind requests", () test("a scoped dynamic is announced only to readers its scope can serve", async () => { const origin = new Producer(); - const dynamic = origin - .scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("*/chat")])) - .routePrefix(Path.empty()); + const dynamic = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("*/chat")])).claim(Path.empty()); const chat = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("room/chat")])); const video = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("room/video")])); await new Promise((resolve) => setImmediate(resolve)); @@ -2374,8 +2370,8 @@ test("a scoped dynamic is announced only to readers its scope can serve", async test("a rooted reader presents the most specific covering route", async () => { const origin = new Producer(); - const narrow = origin.routePrefix(Path.from("room/alice"), { cost: 9n }); - const broad = origin.routePrefix(Path.from("room"), { cost: 1n }); + const narrow = origin.claim(Path.from("room/alice"), { cost: 9n }); + const broad = origin.claim(Path.from("room"), { cost: 1n }); const rooted = origin.scope(Path.from("room/alice"), new Path.Patterns([Path.Pattern.all()])); await new Promise((resolve) => setImmediate(resolve)); expect((await announcedView(rooted)).peek().get(Path.empty())?.cost).toBe(9n); @@ -2389,8 +2385,8 @@ test("a rooted reader presents the most specific covering route", async () => { test("a scoped reader picks the best route its scope can see at a prefix", async () => { const origin = new Producer(); const scoped = (pattern: string) => origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.parse(pattern)])); - const chat = scoped("*/chat").routePrefix(Path.empty(), { cost: 1n }); - const video = scoped("*/video").routePrefix(Path.empty(), { cost: 5n }); + const chat = scoped("*/chat").claim(Path.empty(), { cost: 1n }); + const video = scoped("*/video").claim(Path.empty(), { cost: 5n }); const reader = scoped("room/video"); await new Promise((resolve) => setImmediate(resolve)); @@ -2420,7 +2416,7 @@ test("a scoped reader sees a local broadcast that only loses to a route outside const origin = new Producer(); const chat = origin .scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("room/*/chat")])) - .routePrefix(Path.from("room/alice"), { instance: INSTANCE, cost: 0n }); + .claim(Path.from("room/alice"), { instance: INSTANCE, cost: 0n }); const localRoute = origin.route(Path.from("room/alice"), { instance: INSTANCE, cost: 5n }); const local = localRoute.broadcast; const reader = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("room/*")])); @@ -2454,7 +2450,7 @@ test("broadcast handles carry the path they were created or requested at", async expect(clone?.path).toBe(Path.from("room/alice")); // A dynamic handler's standalone broadcast is named by the request, too. - const dynamic = origin.routePrefix(Path.from("live")); + const dynamic = origin.claim(Path.from("live")); const request = origin.request(Path.from("live/bob")); const pending = await dynamic.requested().next(); const served = new BroadcastProducer(); @@ -2476,7 +2472,7 @@ test("a higher epoch of a dynamic route supersedes a cheaper local broadcast of const path = Path.from("camera"); const instance = Instance.random(); const localRoute = origin.route(path, { instance, epoch: 1n, cost: 0n }); - const dynamic = origin.routePrefix(path, { instance, epoch: 2n, cost: 10n }); + const dynamic = origin.claim(path, { instance, epoch: 2n, cost: 10n }); const served = new BroadcastProducer(); const requests = dynamic.requested(); const request = origin.consume().request(path); @@ -2498,8 +2494,8 @@ test("a higher epoch that is not the best route still supersedes a local broadca const path = Path.from("camera"); const stale = Instance.random(); const localRoute = origin.route(path, { instance: stale, epoch: 1n, cost: 0n }); - const newer = origin.routePrefix(path, { instance: stale, epoch: 2n, cost: 10n }); - const other = origin.routePrefix(path, { instance: Instance.random(), cost: 5n }); + const newer = origin.claim(path, { instance: stale, epoch: 2n, cost: 10n }); + const other = origin.claim(path, { instance: Instance.random(), cost: 5n }); const served = new BroadcastProducer(); const requests = other.requested(); const request = origin.consume().request(path); @@ -2522,7 +2518,7 @@ test("a publisher weighs a local broadcast against the routes it may forward onl const path = Path.from("camera"); const instance = Instance.random(); const localRoute = origin.route(path, { instance, epoch: 1n, cost: 0n }); - const originated = origin.routePrefix(path, { cost: 5n }); + const originated = origin.claim(path, { cost: 5n }); // A session delivered the higher epoch, which a publisher never forwards back out. const received = wireOf(origin).receive(path, { instance, epoch: 2n, cost: 10n, hops: [PEER] }); expect(wireOf(origin.consume()).local(path, instance)).toBeDefined(); @@ -2535,8 +2531,8 @@ test("a publisher weighs a local broadcast against the routes it may forward onl test("a scope's merged covering prefixes never supersede across prefixes", async () => { const origin = new Producer(); const instance = Instance.random(); - const room = origin.routePrefix(Path.from("room"), { instance, epoch: 2n }); - const video = origin.routePrefix(Path.from("room/video"), { instance, epoch: 1n }); + const room = origin.claim(Path.from("room"), { instance, epoch: 2n }); + const video = origin.claim(Path.from("room/video"), { instance, epoch: 1n }); const reader = origin.scope(Path.from("room/video"), new Path.Patterns([Path.Pattern.all()])).consume(); await settle(); const table = wireOf(reader).advertised.peek(); @@ -2553,14 +2549,14 @@ test("supersession only counts routes the reader can see", async () => { const instance = Instance.random(); const video = origin .scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("*/video")])) - .routePrefix(Path.empty(), { instance, epoch: 1n }); + .claim(Path.empty(), { instance, epoch: 1n }); const live = await announcedView(origin, Path.Pattern.parse("room/video"), { covering: true }); await settle(); expect(live.peek().size).toBe(1); // A higher epoch the reader cannot see never hides the route it can. const chat = origin .scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("*/chat")])) - .routePrefix(Path.empty(), { instance, epoch: 2n }); + .claim(Path.empty(), { instance, epoch: 2n }); await settle(); expect([...live.peek().values()].map((route) => route.epoch)).toEqual([1n]); chat.close(); @@ -2602,7 +2598,7 @@ test("demand held across an instance change asks again, unless it named the old const origin = new Producer(); const consumer = origin.consume(); const path = Path.from("live/cam"); - const handle = origin.routePrefix(Path.from("live"), { instance: INSTANCE }); + const handle = origin.claim(Path.from("live"), { instance: INSTANCE }); const it = handle.requested(); const pinned = wireOf(consumer).demand(path, INSTANCE); const unpinned = wireOf(consumer).demand(path); @@ -2631,7 +2627,7 @@ test("a demand refused across an instance change does not lose the carried deman const origin = new Producer(); const consumer = origin.consume(); const path = Path.from("live/cam"); - const handle = origin.routePrefix(Path.from("live"), { instance: INSTANCE }); + const handle = origin.claim(Path.from("live"), { instance: INSTANCE }); const it = handle.requested(); const unpinned = wireOf(consumer).demand(path); const pinned = wireOf(consumer).demand(path, INSTANCE); @@ -2651,7 +2647,7 @@ test("a demand refused across an instance change does not lose the carried deman test("demand held across an instance round trip still asks again", async () => { const origin = new Producer(); const path = Path.from("live/cam"); - const handle = origin.routePrefix(Path.from("live"), { instance: INSTANCE }); + const handle = origin.claim(Path.from("live"), { instance: INSTANCE }); const it = handle.requested(); const demanded = wireOf(origin.consume()).demand(path); const { value: req } = await it.next(); @@ -2677,7 +2673,7 @@ test("demand held across an instance round trip still asks again", async () => { test("re-pricing from the current route keeps the instance", () => { const origin = new Producer(); - const handle = origin.routePrefix(Path.from("live"), { instance: INSTANCE, cost: 5n }); + const handle = origin.claim(Path.from("live"), { instance: INSTANCE, cost: 5n }); handle.setCost(1n); expect(wireOf(handle).info).toEqual(WireRoute.normalize({ instance: INSTANCE, cost: 1n })); @@ -2743,7 +2739,7 @@ test("a request held across an instance change asks again and never takes the ol const origin = new Producer(); const prefix = Path.from("room"); const path = Path.from("room/cam"); - const dynamic = origin.routePrefix(prefix, { instance: INSTANCE }); + const dynamic = origin.claim(prefix, { instance: INSTANCE }); const unpinned = origin.consume().request(path); const pinned = origin.consume().request(path, { instance: INSTANCE }); const requests = dynamic.requested(); @@ -2776,7 +2772,7 @@ test.each([ const origin = new Producer(); const prefix = Path.from("live"); const path = Path.from("live/cam"); - const dynamic = origin.routePrefix(prefix, { instance: named }); + const dynamic = origin.claim(prefix, { instance: named }); // A claim naming no instance serves one of its own. const from = dynamic.instance; expect(from).toBeDefined(); @@ -2863,7 +2859,7 @@ test.each([ test("an instance update does not retain an answer that already closed", async () => { const origin = new Producer(); const path = Path.from("live/cam"); - const dynamic = origin.routePrefix(Path.from("live"), { instance: INSTANCE }); + const dynamic = origin.claim(Path.from("live"), { instance: INSTANCE }); const requests = dynamic.requested(); const held = origin.consume().request(path); const old = new BroadcastProducer(); @@ -2891,7 +2887,7 @@ test("an instance update does not retain an answer that already closed", async ( test("an unread resolved request retains its broadcast until its last handle closes", async () => { const origin = new Producer(); const path = Path.from("live/cam"); - const dynamic = origin.routePrefix(Path.from("live"), { instance: INSTANCE }); + const dynamic = origin.claim(Path.from("live"), { instance: INSTANCE }); const requests = dynamic.requested(); const held = origin.consume().request(path); const old = new SessionBroadcast(); @@ -2911,7 +2907,7 @@ test("an unread resolved request retains its broadcast until its last handle clo test("a session's re-request after an instance update asks the handler again", async () => { const origin = new Producer(); const path = Path.from("live/cam"); - const dynamic = origin.routePrefix(Path.from("live"), { instance: INSTANCE }); + const dynamic = origin.claim(Path.from("live"), { instance: INSTANCE }); const requests = dynamic.requested(); const wire = wireOf(origin.consume()); @@ -2941,8 +2937,8 @@ test("an update does not override route selection: another claim at the instance const origin = new Producer(); const prefix = Path.from("live"); const path = Path.from("live/cam"); - const first = origin.routePrefix(prefix, { instance: INSTANCE, cost: 1n }); - const second = origin.routePrefix(prefix, { instance: INSTANCE, cost: 5n }); + const first = origin.claim(prefix, { instance: INSTANCE, cost: 1n }); + const second = origin.claim(prefix, { instance: INSTANCE, cost: 5n }); const firstRequests = first.requested(); const secondRequests = second.requested(); @@ -3015,7 +3011,7 @@ test("published names refuse navigation segments", () => { for (const name of ["room/./cam", "room/../cam", ".", ".."]) { const path = Path.from(name); expect(() => origin.route(path, { hidden: true }).broadcast).toThrow(); - expect(() => origin.routePrefix(path)).toThrow(); + expect(() => origin.claim(path)).toThrow(); expect(() => wireOf(origin).receive(path, WireRoute.default)).toThrow(); } const scoped = origin.scope(Path.from("room/.."), new Path.Patterns([Path.Pattern.all()])); diff --git a/js/net/src/origin.ts b/js/net/src/origin.ts index dfdfba82a1a..ac99fb1aee0 100644 --- a/js/net/src/origin.ts +++ b/js/net/src/origin.ts @@ -355,7 +355,7 @@ function unroutable(): StreamError { // A selected handler refused these requests; a coalesced route gap can have the same error. const refusedRequests = new WeakSet>(); -/** A prefix route's queue of requests, from {@link Producer.routePrefix}: what a handler drains. */ +/** A claim's queue of requests, from {@link Producer.claim}: what a handler drains. */ class ServeState { readonly root: Path.Valid; /** The prefix the route claims; every served path is at or beneath it. */ @@ -1257,21 +1257,21 @@ export interface Table extends Reader { /** Create a route at exactly `path`, owning a new broadcast; see {@link Producer.route}. */ route(path: Path.Valid, options?: RouteOptions): Route; - /** Create a route over `prefix` that yields requests; see {@link Producer.routePrefix}. */ - routePrefix(prefix: Path.Valid, options?: RouteOptions): Route; + /** Claim `prefix`, yielding the requests beneath it; see {@link Producer.claim}. */ + claim(prefix: Path.Valid, options?: RouteOptions): Claim; } /** - * How an application advertises a {@link Route}: its visibility at creation, its price, its - * credential, and, rarely, a stable instance. + * How an application advertises a {@link Route} or {@link Claim}: its visibility at creation, + * its price, its credential, and, rarely, a stable instance. * * The default announces at once, at cost 0, under the session's scope, serving a fresh random * instance minted when the route is created. A job's route ({@link Request.route}) instead - * continues its prefix route's instance when that one was minted; see {@link Route.instance}. + * continues its claim's instance when that one was minted; see {@link Route.instance}. */ export interface RouteOptions { /** - * Create the route hidden: it exists for nobody until {@link Route.announce}. For a + * Create the route hidden: it exists for nobody until it announces. For a * publisher that fills its catalog first, or answers a negotiation, before readers may find it. */ hidden?: boolean; @@ -1317,8 +1317,9 @@ export interface FollowOptions { instance?: Instance.Valid; } -// Route constructors, assigned in the classes' static blocks so neither class exposes one. -let makeRoute: (control: RouteControl) => Route; +// Route constructors, assigned in the classes' static blocks so no class exposes one. +let makeRoute: (broadcast: broadcast.Producer, control: RouteControl) => Route; +let makeClaim: (control: RouteControl, requested: () => AsyncIterableIterator) => Claim; let exactRoute: (producer: Producer, path: Path.Valid, options: RouteOptions, request: Request) => Route; /** @@ -1332,8 +1333,8 @@ let exactRoute: (producer: Producer, path: Path.Valid, options: RouteOptions, re * * Create a {@link route} at a path and fill its broadcast; create it hidden and * {@link Route.announce} it once its first tracks exist, since nobody can see or reach a hidden - * route. To publish broadcasts on demand instead, claim a prefix with {@link routePrefix} and - * answer the requests beneath it. + * route. To publish broadcasts on demand instead, {@link claim} a prefix and answer the + * requests beneath it. * * @public */ @@ -1433,7 +1434,7 @@ export class Producer implements Table { * exists for nobody until {@link Route.announce}: announce streams skip it and a request * for its path finds nothing, on this origin exactly as at a peer. Create it hidden when * the tracks a subscriber needs first, such as a catalog, are not there yet. To serve paths - * on demand without publishing each one, use {@link routePrefix}. + * on demand without publishing each one, use {@link claim}. * * Closing the route retracts it and closes its broadcast, and so does closing the * broadcast. Creating a path again supersedes the previous route: the origin retracts it @@ -1537,8 +1538,7 @@ export class Producer implements Table { if (announced()) this.#advertiseExact(path, front, info); }; - const route = makeRoute({ - broadcast: producer, + const route = makeRoute(producer, { instance: () => { if (claim && !bound && pending) { info = { ...info, ...claim.current() }; @@ -1550,7 +1550,6 @@ export class Producer implements Table { withdraw: retract, announced, change: (update) => change(WireRoute.normalize({ ...info, ...update })), - requested: async function* () {}, close: release, info: () => (announced() ? this.#state.advertisedLocal.peek()?.get(path) : undefined), update: (next) => { @@ -1590,25 +1589,25 @@ export class Producer implements Table { } /** - * Create a route over `prefix` that yields the requests beneath it. + * Claim `prefix`, yielding the requests beneath it. * - * A route is always a prefix: it claims `prefix` and every path beneath it (the empty - * prefix claims every path). A service that only serves some of them advertises the - * covering prefix and rejects the rest as they are requested; consumers narrow with a - * {@link Path.Pattern} locally. The route is priced, credentialed and shown like an exact - * one, and forwarded by sessions while it is visible. + * A route is always a prefix on the wire: a claim covers `prefix` and every path beneath it + * (the empty prefix claims every path). A service that only serves some of them advertises + * the covering prefix and rejects the rest as they are requested; consumers narrow with a + * {@link Path.Pattern} locally. The claim is priced, credentialed and shown like an exact + * route, and forwarded by sessions while it is visible. * * A consumer resolving a path under it that no announced local broadcast wins is handed to - * {@link Route.requested} as a {@link Request}: answer it by serving a broadcast already held - * ({@link Request.serve}), under this route's instance, or by creating the path's own exact - * route ({@link Request.route}), a job. Without {@link RouteOptions.instance} this route + * {@link Claim.requested} as a {@link Request}: answer it by serving a broadcast already held + * ({@link Request.serve}), under this claim's instance, or by creating the path's own exact + * route ({@link Request.route}), a job. Without {@link RouteOptions.instance} this claim * serves a minted instance that its jobs continue, so a reader resolved through it keeps - * reading when the job's route lands; once a job stops being advertised, this route moves to + * reading when the job's route lands; once a job stops being advertised, this claim moves to * a fresh instance, so restarting the job never splices into a copy of the last. With a named * instance, each job mints its own. A publisher that knows its broadcasts creates each one's * exact {@link route} instead, so subscribers can enumerate them. */ - routePrefix(prefix: Path.Valid, options: RouteOptions = {}): Route { + claim(prefix: Path.Valid, options: RouteOptions = {}): Claim { const info = WireRoute.normalize({ instance: options.instance, epoch: options.epoch, @@ -1619,11 +1618,11 @@ export class Producer implements Table { } /** Land a route a peer announced, taken as given. Not originated, so a session never announces it back. */ - #receive(prefix: Path.Valid, route?: Partial): Route { + #receive(prefix: Path.Valid, route?: Partial): Claim { return this.#serving(prefix, WireRoute.normalize(route), false, false, true); } - #serving(prefix: Path.Valid, route: WireRoute, originated: boolean, publishes: boolean, visible: boolean): Route { + #serving(prefix: Path.Valid, route: WireRoute, originated: boolean, publishes: boolean, visible: boolean): Claim { prefix = this.#scope.prefix(prefix); // A route that names no instance serves one of its own, and a claim hands that one to its jobs. const minted = route.instance === undefined; @@ -1646,7 +1645,7 @@ export class Producer implements Table { // Closing the origin drops the whole table without visiting each route, so a route // still marked inserted learns of it here, matching an exact route's "origin is closed". const open = () => { - if (ended) throw new Error("route is closed"); + if (ended) throw new Error("claim is closed"); if (this.#state.routes.peek()) return; inserted = false; throw new Error("origin is closed"); @@ -1729,30 +1728,32 @@ export class Producer implements Table { } const publisher = publishes ? this : undefined; - return makeRoute({ - instance: () => entry.route.peek().instance as Instance.Valid, - announce: insert, - withdraw: () => { - if (ended || !inserted) return; - remove(() => server.reset()); - }, - announced: () => inserted && this.#state.routes.peek() !== undefined, - change: (changed) => update(WireRoute.normalize({ ...entry.route.peek(), ...changed })), - requested: () => serveRequests(server, publisher), - close: release, - info: () => (inserted && this.#state.routes.peek() ? entry.route.peek() : undefined), - update: (next) => { - // A route naming no instance keeps the one it serves. - const named = WireRoute.normalize(next); - const current = entry.route.peek(); - update( - named.instance === undefined - ? { ...named, instance: current.instance, epoch: current.epoch } - : named, - ); - insert(); + return makeClaim( + { + instance: () => entry.route.peek().instance as Instance.Valid, + announce: insert, + withdraw: () => { + if (ended || !inserted) return; + remove(() => server.reset()); + }, + announced: () => inserted && this.#state.routes.peek() !== undefined, + change: (changed) => update(WireRoute.normalize({ ...entry.route.peek(), ...changed })), + close: release, + info: () => (inserted && this.#state.routes.peek() ? entry.route.peek() : undefined), + update: (next) => { + // A route naming no instance keeps the one it serves. + const named = WireRoute.normalize(next); + const current = entry.route.peek(); + update( + named.instance === undefined + ? { ...named, instance: current.instance, epoch: current.epoch } + : named, + ); + insert(); + }, }, - }); + () => serveRequests(server, publisher), + ); } /** @@ -2715,21 +2716,29 @@ export class Consumer implements Reader { } } -/** What one {@link Route} does, exact or prefix. */ +/** What a {@link Route} and a {@link Claim} share: the advertisement and how it is changed. */ interface RouteControl { - readonly broadcast?: broadcast.Producer; instance(): Instance.Valid; announce(): void; withdraw(): void; announced(): boolean; change(update: Partial>): void; - requested(): AsyncIterableIterator; close(): void; info(): WireRoute | undefined; update(info: Partial): void; } -/** The requests arriving on a prefix route's `server`, each answerable with a route of `publisher`'s when it has one. */ +// Expose `control` to the protocol layer, which advertises a route as a session's update does. +function registerControl(handle: Route | Claim, control: RouteControl): void { + registerWire(handle, { + get info() { + return control.info(); + }, + update: (info) => control.update(info), + }); +} + +/** The requests arriving on a claim's `server`, each answerable with a route of `publisher`'s when it has one. */ async function* serveRequests(server: ServeState, publisher: Producer | undefined): AsyncIterableIterator { let current: Request | undefined; const drop = () => { @@ -2761,11 +2770,9 @@ async function* serveRequests(server: ServeState, publisher: Producer | undefine } /** - * A route in an origin: an exact one owning its broadcast, or a prefix one answering the - * requests beneath it. + * An exact route in an origin, owning its broadcast. * - * Create an exact route with {@link Producer.route}, a prefix route with - * {@link Producer.routePrefix}, or a job's exact route with {@link Request.route}. + * Create one with {@link Producer.route}, or a job's with {@link Request.route}. * * ```ts * // Fill the catalog before readers can find it. @@ -2781,40 +2788,28 @@ async function* serveRequests(server: ServeState, publisher: Producer | undefine * @public */ export class Route { + /** The broadcast this route owns, to fill with tracks. */ + readonly broadcast: broadcast.Producer; readonly #control: RouteControl; - private constructor(control: RouteControl) { + private constructor(producer: broadcast.Producer, control: RouteControl) { + this.broadcast = producer; this.#control = control; - registerWire(this, { - get info() { - return control.info(); - }, - update: (info) => control.update(info), - }); + registerControl(this, control); } static { - makeRoute = (control) => new Route(control); - } - - /** The broadcast this exact route owns, to fill with tracks. Throws on a prefix route, which owns none. */ - get broadcast(): broadcast.Producer { - const producer = this.#control.broadcast; - if (!producer) throw new Error("a prefix route owns no broadcast; answer its requests"); - return producer; + makeRoute = (producer, control) => new Route(producer, control); } /** * The stream this route serves, minted when it was created unless {@link RouteOptions.instance} * named one. * - * A prefix route that minted its instance moves to a fresh one, as a restart, the moment a - * job's route carrying its instance stops being advertised. A job's route - * ({@link Request.route}) naming no instance takes its prefix route's current one when it - * first announces or when this first reads it. Read first, the job announces under it, and - * {@link announce} throws {@link StreamCode | StreamCode.Unroutable} once the prefix route has - * moved past it, so a signer built from it stays valid. A prefix route naming its instance - * gives each job a fresh one instead. + * A job's route ({@link Request.route}) naming none takes its claim's current one when it + * first announces, or when this reads it first. Read before announcing, it is the one the job + * announces under, and {@link announce} throws {@link StreamCode | StreamCode.Unroutable} once + * the claim has moved past it, so a signer built from it stays valid. */ get instance(): Instance.Valid { return this.#control.instance(); @@ -2826,9 +2821,9 @@ export class Route { * Visible to local consumers before it returns. A job's route ({@link Request.route}) also * answers the requesters waiting on its path. Throws once the route or its broadcast closed, * and, announcing nothing, with {@link StreamCode | StreamCode.Unroutable} when a job's request - * was released or its prefix route retracted meanwhile, or when the job read its - * {@link instance} and its prefix route has moved past it since: that route can never - * announce. In that last case its requesters ask the prefix route again. + * was released or its claim retracted meanwhile, or when the job read its {@link instance} and + * its claim has moved past it since: that route can never announce. In that last case its + * requesters ask the claim again. */ announce(): void { this.#control.announce(); @@ -2866,22 +2861,117 @@ export class Route { this.#control.change({ auth }); } + /** Retract the route for good, closing its broadcast and refusing a job's waiting requesters. Idempotent. */ + close(): void { + this.#control.close(); + } + + /** Calls {@link close}, so `using` retracts the route. */ + [Symbol.dispose](): void { + this.close(); + } +} + +/** + * A prefix route in an origin: a claim that every path beneath a prefix can be served, + * answering each request as it arrives. + * + * Create one with {@link Producer.claim}. Requests arrive on {@link requested}; answer each by + * serving a broadcast already held or by creating the path's own {@link Route}. + * + * ```ts + * const claim = origin.claim(Path.from("room")); + * for await (const request of claim.requested()) { + * const route = request.route({ hidden: true }); + * route.broadcast.createTrack("catalog.json"); + * route.announce(); // answers the requesters + * } + * ``` + * + * {@link close} retracts it and rejects the requests still waiting. + * + * @public + */ +export class Claim { + readonly #control: RouteControl; + readonly #requested: () => AsyncIterableIterator; + + private constructor(control: RouteControl, requested: () => AsyncIterableIterator) { + this.#control = control; + this.#requested = requested; + registerControl(this, control); + } + + static { + makeClaim = (control, requested) => new Claim(control, requested); + } + + /** + * The stream this claim serves, minted when it was created unless {@link RouteOptions.instance} + * named one. + * + * Unnamed, it can change: the claim moves to a fresh instance, as a restart, each time a job's + * route holding its current one stops being advertised. A claim naming its instance gives each + * job a fresh one instead. See {@link Producer.claim}. + */ + get instance(): Instance.Valid { + return this.#control.instance(); + } + + /** + * Make the claim visible, or keep it so. Idempotent. Visible to local consumers before it + * returns. Throws once the claim or the origin closed. + */ + announce(): void { + this.#control.announce(); + } + + /** + * Hide the claim from everyone, local and remote alike, keeping its instance: {@link announce} + * brings it back. Requests beneath it fail with {@link StreamCode | StreamCode.Unroutable} + * meanwhile. Idempotent. + */ + withdraw(): void { + this.#control.withdraw(); + } + + /** Whether the claim is visible. */ + get announced(): boolean { + return this.#control.announced(); + } + /** - * The requests beneath this prefix route, as they arrive, each to answer with - * {@link Request.serve}, {@link Request.route} or {@link Request.reject}. Advancing the - * iterator or closing it without answering rejects the request. Ends once the route is - * closed or the origin closes, and at once on an exact route, which yields no requests. + * Re-price the claim: lower wins among routes covering the same prefix and anonymity. A + * visible claim changes in place, as an update to its readers; a hidden one announces at + * this price. Throws once the claim or the origin closed. + */ + setCost(cost: Cost): void { + this.#control.change({ cost }); + } + + /** + * Swap the credential the advertising request carries; see {@link RouteOptions.auth}. + * Undefined advertises under the session's scope. Throws once the claim or the origin closed. + */ + setAuth(auth?: Credential): void { + this.#control.change({ auth }); + } + + /** + * The requests beneath this claim, as they arrive, each to answer with {@link Request.serve}, + * {@link Request.route} or {@link Request.reject}. Advancing the iterator or closing it without + * answering rejects the request. Ends once the claim is closed or the origin closes. */ requested(): AsyncIterableIterator { - return this.#control.requested(); + return this.#requested(); } - /** Retract the route for good, closing its broadcast and rejecting anything still waiting. Idempotent. */ + /** Retract the claim for good, rejecting the requests still waiting. Idempotent. */ close(): void { this.#control.close(); } - /** Calls {@link close}, so `using` retracts the route. */ + /** Calls {@link close}, so `using` retracts the claim. */ [Symbol.dispose](): void { this.close(); } @@ -2890,8 +2980,8 @@ export class Route { /** * A pending request for a broadcast to be served on demand. * - * Yielded by {@link Route.requested}. Answer it one of three ways: {@link serve} a broadcast - * already held, under the prefix route's instance; create the path's own exact route with + * Yielded by {@link Claim.requested}. Answer it one of three ways: {@link serve} a broadcast + * already held, under the claim's instance; create the path's own exact route with * {@link route}, a job; or {@link reject} it with an error. Advancing the iterator or closing it * without answering rejects the request. * @@ -2940,20 +3030,20 @@ export class Request { /** * Answer with the path's own exact route, owning a new broadcast. * - * Unless `options` names an instance, the route continues the prefix route's minted + * Unless `options` names an instance, the route continues the claim's minted * instance, bound when it first announces or {@link Route.instance} first reads it, so readers that resolved the path through the - * prefix route keep reading the same stream. Once this route stops being advertised the - * prefix route moves to a fresh instance, so a job that restarts beneath it is a new stream + * claim keep reading the same stream. Once this route stops being advertised the + * claim moves to a fresh instance, so a job that restarts beneath it is a new stream * for its restarted sequences, and a request naming the ended instance is refused. Under a - * prefix route naming its instance, the route mints a fresh one. Closing the route withdraws - * only this path: the prefix route keeps answering later requests. Created + * claim naming its instance, the route mints a fresh one. Closing the route withdraws + * only this path: the claim keeps answering later requests. Created * visible, the route announces now and answers the requesters waiting on its path. Created * {@link RouteOptions.hidden | hidden}, they wait until {@link Route.announce}, so the job can * fill its catalog first; closing the route or its broadcast before then refuses them. * * Throws {@link StreamCode | StreamCode.Unroutable} on a request a session forwarded, which can * only {@link serve} its peer's broadcast, and, announcing nothing, once the request was - * released or its prefix route retracted. Otherwise it throws as {@link Producer.route} does. + * released or its claim retracted. Otherwise it throws as {@link Producer.route} does. */ route(options: RouteOptions = {}): Route { if (this.#done) throw new Error("request is closed"); @@ -2964,11 +3054,11 @@ export class Request { } /** - * Serve a held broadcast under this prefix route without announcing an exact route. + * Serve a held broadcast under this claim without announcing an exact route. * * Takes ownership of a consumer; a producer stays the caller's. Every answer at this - * path belongs to the prefix route's instance and must continue the same sequences and - * bytes. Start a new prefix route for different content, or use {@link route} for a job + * path belongs to the claim's instance and must continue the same sequences and + * bytes. Start a new claim for different content, or use {@link route} for a job * that can restart independently. */ serve(source: broadcast.Producer | broadcast.Consumer): void { diff --git a/js/net/src/untimed.test.ts b/js/net/src/untimed.test.ts index eae4fe355e2..86c2d644e13 100644 --- a/js/net/src/untimed.test.ts +++ b/js/net/src/untimed.test.ts @@ -128,7 +128,7 @@ test("a forwarded untimed track stays untimed", async () => { // Serve the downstream session from the upstream one through a copy the forwarding // node produces. - const dynamic = relay.routePrefix(Path.from("test")); + const dynamic = relay.claim(Path.from("test")); const inputs: BroadcastConsumer[] = []; const forwarding = (async () => { for await (const request of dynamic.requested()) { diff --git a/js/net/src/wire.ts b/js/net/src/wire.ts index 5913f25a88e..feacff363d0 100644 --- a/js/net/src/wire.ts +++ b/js/net/src/wire.ts @@ -62,7 +62,7 @@ export interface OriginProducer { /** Whether an advertised prefix overlaps the handle's allowed paths. */ accepts(prefix: Path.Valid): boolean; /** Land a route a peer announced, taken as given and never forwarded back to a peer. */ - receive(prefix: Path.Valid, route?: Partial): origin.Route; + receive(prefix: Path.Valid, route?: Partial): origin.Claim; attach(discovery: boolean): Dispose; /** * Hold the origin's announcement streams overlapping `prefix` unsynced until @@ -77,7 +77,7 @@ export interface OriginProducer { routes(path: Path.Valid): boolean; } -/** The protocol-facing operations behind an origin route. */ +/** The protocol-facing operations behind an origin route or claim. */ export interface Route { /** The metadata the route is advertised with, or undefined while hidden. */ readonly info: WireRoute | undefined; @@ -177,7 +177,7 @@ export function wireOf(handle: broadcast.Producer): Produced; export function wireOf(handle: broadcast.Producer | broadcast.Consumer): Broadcast; export function wireOf(handle: origin.Producer): OriginProducer; export function wireOf(handle: origin.Consumer): OriginConsumer; -export function wireOf(handle: origin.Route): Route; +export function wireOf(handle: origin.Route | origin.Claim): Route; export function wireOf(handle: import("./connection/established.ts").Established): Established; /** Return the package-private view for a handle. */ export function wireOf(handle: object): View { diff --git a/js/watch/src/broadcast.test.ts b/js/watch/src/broadcast.test.ts index 11d27d4d592..3d3cdb7737d 100644 --- a/js/watch/src/broadcast.test.ts +++ b/js/watch/src/broadcast.test.ts @@ -34,7 +34,7 @@ function broadcast(name: string, paths: string[] = [name]): { source: Broadcast; } // Answer every request `claim` receives with a new exact broadcast, returning the answers. -function serve(claim: Origin.Route): Moq.Broadcast.Producer[] { +function serve(claim: Origin.Claim): Moq.Broadcast.Producer[] { const answers: Moq.Broadcast.Producer[] = []; void (async () => { for await (const request of claim.requested()) answers.push(request.route().broadcast); @@ -488,7 +488,7 @@ describe("blind resolution", () => { await settle(); // Stand in for a claim answering the request. - const route = owner.routePrefix(Path.from("blind.hang")); + const route = owner.claim(Path.from("blind.hang")); const requests = route.requested(); const next = await requests.next(); if (!next.value) throw new Error("expected a request"); @@ -600,7 +600,7 @@ describe("restart", () => { it("moves to a more specific announcement of another instance", async () => { const owner = new Origin.Producer(); const name = Path.from("pool/job.hang"); - const pool = owner.routePrefix(Path.from("pool")); + const pool = owner.claim(Path.from("pool")); const answers = serve(pool); const source = new Broadcast({ origin: owner, name, enabled: true, follow: true, catalogFormat: "manual" }); await settle(); @@ -631,7 +631,7 @@ describe("restart", () => { it("plays a claim's job on the instance it resolved", async () => { const owner = new Origin.Producer(); const name = Path.from("pool/job.hang"); - const pool = owner.routePrefix(Path.from("pool")); + const pool = owner.claim(Path.from("pool")); const answers = serve(pool); const source = new Broadcast({ origin: owner, name, enabled: true, follow: true, catalogFormat: "manual" }); const handed: unknown[] = []; @@ -668,7 +668,7 @@ describe("restart", () => { // The exact route goes, which ends the request on it, and a prefix answers before the table // is read again. The player still has to ask again. exact.close(); - const pool = owner.routePrefix(Path.from("pool")); + const pool = owner.claim(Path.from("pool")); const answers = serve(pool); await settle(); const resumed = source.out.active.peek(); @@ -686,7 +686,7 @@ describe("restart", () => { it("falls back to a covering prefix when the exact route ends", async () => { const owner = new Origin.Producer(); const name = Path.from("pool/job.hang"); - const pool = owner.routePrefix(Path.from("pool")); + const pool = owner.claim(Path.from("pool")); const answers = serve(pool); const exact = publish(owner, name); const source = new Broadcast({ origin: owner, name, enabled: true, follow: true, catalogFormat: "manual" }); @@ -719,7 +719,7 @@ describe("refusal", () => { it("reports an unroutable refusal of a restarted publisher", async () => { const owner = new Origin.Producer(); const name = Path.from("room/live.hang"); - const first = owner.routePrefix(Path.from("room")); + const first = owner.claim(Path.from("room")); const answers = serve(first); const source = new Broadcast({ origin: owner, name, enabled: true, follow: true, catalogFormat: "manual" }); await settle(); @@ -728,7 +728,7 @@ describe("refusal", () => { // The publisher restarts, and refuses with the same code an ended instance reports. first.close(); for (const answer of answers) answer.close(); - const second = owner.routePrefix(Path.from("room")); + const second = owner.claim(Path.from("room")); const refused = await second.requested().next(); refused.value?.reject(new Moq.Error.Stream(Moq.StreamCode.Unroutable, { message: "refused" })); await settle(); @@ -764,7 +764,7 @@ describe("refusal", () => { for (const follow of [true, false]) { it(`reports a refusal until a fresh request (follow: ${follow})`, async () => { const owner = new Origin.Producer(); - const route = owner.routePrefix(Path.from("room")); + const route = owner.claim(Path.from("room")); const requests = route.requested(); const name = new Signal(Path.from("room/refused.hang")); const enabled = new Signal(true); @@ -1046,7 +1046,7 @@ describe("wildcard renditions", () => { await settle(); expect(videoRenditions(source)).toEqual(["source"]); - const worker = owner.routePrefix(Path.from(".pro/transcode")); + const worker = owner.claim(Path.from(".pro/transcode")); const requests = worker.requested(); await settle(); expect(videoRenditions(source)).toEqual(["source", "transcode"]); @@ -1093,8 +1093,8 @@ describe("wildcard renditions", () => { try { // A catch-all (an archive) and a narrower pool both cover the derived path. - const archive = owner.routePrefix(Path.empty()); - const worker = owner.routePrefix(Path.from(".pro/transcode")); + const archive = owner.claim(Path.empty()); + const worker = owner.claim(Path.from(".pro/transcode")); await settle(); expect(videoRenditions(source)).toEqual(["source", "transcode"]); diff --git a/js/watch/src/include.test.ts b/js/watch/src/include.test.ts index 67f4f2fb416..a7b1dbcd0d0 100644 --- a/js/watch/src/include.test.ts +++ b/js/watch/src/include.test.ts @@ -103,7 +103,7 @@ it("opens a listed include only on selection, keeping its rendition IDs its own" it("reads an unavailable include as offline without touching the parent", async () => { const origin = new Origin.Producer(); publish(origin, "room/main.hang"); - const claim = origin.routePrefix(Path.from("room/absent.hang")); + const claim = origin.claim(Path.from("room/absent.hang")); const requests = claim.requested(); const source = new Broadcast({ origin, diff --git a/test/interop/clients/js-native/claims.ts b/test/interop/clients/js-native/claims.ts index 0e6fe045ff7..680fbca6c39 100644 --- a/test/interop/clients/js-native/claims.ts +++ b/test/interop/clients/js-native/claims.ts @@ -20,7 +20,7 @@ function endpoint(address: string): URL { const published = new Moq.Origin.Producer(); const received = new Moq.Origin.Producer(); -const claim = published.routePrefix(Moq.Path.from(prefix)); +const claim = published.claim(Moq.Path.from(prefix)); const broadcasts = new Map(); const serving = (async () => { for await (const request of claim.requested()) { diff --git a/test/interop/clients/js-native/replace.ts b/test/interop/clients/js-native/replace.ts index f29c751d464..b1e158c7b0b 100644 --- a/test/interop/clients/js-native/replace.ts +++ b/test/interop/clients/js-native/replace.ts @@ -21,7 +21,7 @@ function endpoint(address: string): URL { const published = new Moq.Origin.Producer(); const received = [new Moq.Origin.Producer(), new Moq.Origin.Producer(), new Moq.Origin.Producer()]; -const claim = published.routePrefix(Moq.Path.from(prefix)); +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 }); diff --git a/test/relay-fill/relay.ts b/test/relay-fill/relay.ts index 81cdaad706c..6f318227bbd 100644 --- a/test/relay-fill/relay.ts +++ b/test/relay-fill/relay.ts @@ -38,7 +38,7 @@ const clock = new Manual(); const installed = clock.install(); // A session never announces a received broadcast to another, so the relay advertises it itself. const origin = new Producer(); -const route = origin.routePrefix(path); +const claim = origin.claim(path); async function dial(address: string, publish?: ReturnType) { const url = new URL(address); @@ -55,7 +55,7 @@ async function dial(address: string, publish?: ReturnType) const source = await dial(upstream); const sinks: Awaited>[] = []; const serving = (async () => { - for await (const request of route.requested()) request.serve(wireOf(source).consume(path)); + for await (const request of claim.requested()) request.serve(wireOf(source).consume(path)); })(); console.log("ready"); const lines = createInterface({ input: process.stdin }); @@ -78,7 +78,7 @@ try { } } finally { lines.close(); - route.close(); + claim.close(); await serving; for (const sink of sinks) await sink.close(); await source.close(); From b29f3468a326e9c83192e481543d78f1211341ba Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 22:19:23 -0800 Subject: [PATCH 10/12] chore: fmt after the claim rename Co-Authored-By: Claude Opus 5.5 --- rs/moq-cli/src/play/media.rs | 12 +++--------- rs/moq-gst/src/source/imp.rs | 8 ++------ rs/moq-mux/src/catalog/hang/consumer.rs | 4 +--- rs/moq-mux/src/container/ts/export_test.rs | 8 ++------ rs/moq-mux/src/source.rs | 4 +--- rs/moq-net/benches/origin.rs | 4 +--- rs/moq-net/benches/retirement.rs | 5 +---- rs/moq-net/src/model/origin.rs | 6 +----- rs/moq-net/tests/integration/drained_claim.rs | 6 +----- rs/moq-net/tests/integration/wide_hop.rs | 4 +--- 10 files changed, 14 insertions(+), 47 deletions(-) diff --git a/rs/moq-cli/src/play/media.rs b/rs/moq-cli/src/play/media.rs index b4c02fa339a..bda878bd2c2 100644 --- a/rs/moq-cli/src/play/media.rs +++ b/rs/moq-cli/src/play/media.rs @@ -1913,9 +1913,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn a_refused_broadcast_ends_the_player() { let origin = moq_tokio::origin::spawn(); - let handler = origin - .claim("", moq_net::origin::RouteOptions::default()) - .unwrap(); + let handler = origin.claim("", moq_net::origin::RouteOptions::default()).unwrap(); let recorder = Recorder::default(); let player = tokio::spawn(media(&origin, Duration::from_millis(50), recorder.clone()).run()); let request = handler.requested().await.unwrap(); @@ -2076,9 +2074,7 @@ mod tests { // The broadcast ends while its route stands, so the player goes idle. kio::clock::sleep(Duration::from_secs(60)).await; - let pool = origin - .claim("", moq_net::origin::RouteOptions::default()) - .unwrap(); + let pool = origin.claim("", moq_net::origin::RouteOptions::default()).unwrap(); drop(exact); let (served, served_catalog, mut new) = answer(&pool).await; write(&mut new, 10, NEW).await; @@ -2112,9 +2108,7 @@ mod tests { } exact.withdraw(); - let pool = origin - .claim("", moq_net::origin::RouteOptions::default()) - .unwrap(); + let pool = origin.claim("", moq_net::origin::RouteOptions::default()).unwrap(); let (mirror, mirror_catalog, mut copy) = answer(&pool).await; for index in 50..60 { copy.write(packet(index, NEW)).unwrap(); diff --git a/rs/moq-gst/src/source/imp.rs b/rs/moq-gst/src/source/imp.rs index dfe6e543b3d..fffec37f724 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -4447,9 +4447,7 @@ mod session_tests { let recorder = Recorder::attach(&element); let origin = origin(); - let claim = origin - .claim("", moq_net::origin::RouteOptions::default()) - .unwrap(); + let claim = origin.claim("", moq_net::origin::RouteOptions::default()).unwrap(); let (answers, answered) = std::sync::mpsc::channel(); let handler = super::RUNTIME.spawn(async move { while let Some(request) = claim.requested().await { @@ -4483,9 +4481,7 @@ mod session_tests { let element = element(); let recorder = Recorder::attach(&element); let origin = origin(); - let pool = origin - .claim("", moq_net::origin::RouteOptions::default()) - .unwrap(); + let pool = origin.claim("", moq_net::origin::RouteOptions::default()).unwrap(); let session = follow(&element, &origin); let pending = super::RUNTIME.block_on(async { kio::clock::timeout(Duration::from_secs(10), pool.requested()) diff --git a/rs/moq-mux/src/catalog/hang/consumer.rs b/rs/moq-mux/src/catalog/hang/consumer.rs index c7b1150dae4..4fe96145f57 100644 --- a/rs/moq-mux/src/catalog/hang/consumer.rs +++ b/rs/moq-mux/src/catalog/hang/consumer.rs @@ -141,9 +141,7 @@ mod test { /// takes when it answers an origin request. async fn publish_catalog_served(published: Catalog<()>) -> Result> { let origin = crate::source::produce_origin(); - let dynamic = origin - .claim("", moq_net::origin::RouteOptions::default()) - .unwrap(); + let dynamic = origin.claim("", moq_net::origin::RouteOptions::default()).unwrap(); let requesting = origin.consume().request("a/pub", None); // The handler hands its route back: dropping it would retract the route and end // the broadcast it just served. diff --git a/rs/moq-mux/src/container/ts/export_test.rs b/rs/moq-mux/src/container/ts/export_test.rs index 31f3bf9177c..7c00fc0918f 100644 --- a/rs/moq-mux/src/container/ts/export_test.rs +++ b/rs/moq-mux/src/container/ts/export_test.rs @@ -10543,14 +10543,10 @@ async fn a_follower_ignores_a_covering_prefix_while_the_exact_route_serves() { let mut follower = super::Follower::new(open_export(source, std::time::Duration::ZERO).await.unwrap()).unwrap(); let quiet = Duration::from_secs(1); - let pool = origin - .claim("pool", moq_net::origin::RouteOptions::default()) - .unwrap(); + let pool = origin.claim("pool", moq_net::origin::RouteOptions::default()).unwrap(); assert!(kio::clock::timeout(quiet, follower.next()).await.is_err(), "a start"); drop(pool); - let pool = origin - .claim("pool", moq_net::origin::RouteOptions::default()) - .unwrap(); + let pool = origin.claim("pool", moq_net::origin::RouteOptions::default()).unwrap(); assert!(kio::clock::timeout(quiet, follower.next()).await.is_err(), "a restart"); drop(pool); assert!(kio::clock::timeout(quiet, follower.next()).await.is_err(), "an end"); diff --git a/rs/moq-mux/src/source.rs b/rs/moq-mux/src/source.rs index b97e114403b..c7c3bd050e9 100644 --- a/rs/moq-mux/src/source.rs +++ b/rs/moq-mux/src/source.rs @@ -674,9 +674,7 @@ mod tests { let _catalog = origin.route("pub", Default::default()).unwrap(); settle().await; let source = resolved(&origin, "pub").await; - let dynamic = origin - .claim("media", moq_net::origin::RouteOptions::default()) - .unwrap(); + let dynamic = origin.claim("media", moq_net::origin::RouteOptions::default()).unwrap(); let binding = source.bind(Some(&Relative::new("media").unwrap()), None).unwrap(); let request = dynamic.requested().await.unwrap(); diff --git a/rs/moq-net/benches/origin.rs b/rs/moq-net/benches/origin.rs index ca95f426a38..4de84066bda 100644 --- a/rs/moq-net/benches/origin.rs +++ b/rs/moq-net/benches/origin.rs @@ -156,9 +156,7 @@ fn bench_announce_covering(c: &mut Criterion) { } b.iter(|| { for (name, delivered) in [("room/live.chat", true), ("room/mic.hang", covering)] { - let route = producer - .claim(name, moq_net::origin::RouteOptions::default()) - .unwrap(); + let route = producer.claim(name, moq_net::origin::RouteOptions::default()).unwrap(); for cursor in &mut cursors { assert_eq!(cursor.next().now_or_never().flatten().is_some(), delivered); } diff --git a/rs/moq-net/benches/retirement.rs b/rs/moq-net/benches/retirement.rs index 5105df61760..ae644aad268 100644 --- a/rs/moq-net/benches/retirement.rs +++ b/rs/moq-net/benches/retirement.rs @@ -24,10 +24,7 @@ fn retirement(c: &mut Criterion) { let routes: Vec<_> = (0..routes) .map(|i| { origin - .claim( - format!("route/{i}"), - moq_net::origin::RouteOptions::default(), - ) + .claim(format!("route/{i}"), moq_net::origin::RouteOptions::default()) .unwrap() }) .collect(); diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index 8abee6e8873..0a926c3ad83 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -2585,11 +2585,7 @@ impl Producer { /// /// The prefix must overlap this producer's pattern scope. Individual requests /// remain authoritative and are refused when they do not match the scope. - pub fn claim( - &self, - prefix: impl TryInto>, - options: RouteOptions, - ) -> Result { + pub fn claim(&self, prefix: impl TryInto>, options: RouteOptions) -> Result { // A minted instance lives in the table, which moves it on as its jobs end; see // [`OriginState::advance`]. let info = RouteInfo { diff --git a/rs/moq-net/tests/integration/drained_claim.rs b/rs/moq-net/tests/integration/drained_claim.rs index 268c2f6dba3..48051ece208 100644 --- a/rs/moq-net/tests/integration/drained_claim.rs +++ b/rs/moq-net/tests/integration/drained_claim.rs @@ -55,11 +55,7 @@ struct Worker { impl Worker { fn new(hop: u64, name: &'static str) -> Self { let origin = produce_origin(hop); - let claim = Rc::new( - origin - .claim("pool", moq_net::origin::RouteOptions::default()) - .unwrap(), - ); + let claim = Rc::new(origin.claim("pool", moq_net::origin::RouteOptions::default()).unwrap()); let outputs = Rc::new(RefCell::new(Vec::new())); let (handler, served) = (claim.clone(), outputs.clone()); drop(kio::clock::sim::spawn(async move { diff --git a/rs/moq-net/tests/integration/wide_hop.rs b/rs/moq-net/tests/integration/wide_hop.rs index cac5164fd57..0d89b6a1d16 100644 --- a/rs/moq-net/tests/integration/wide_hop.rs +++ b/rs/moq-net/tests/integration/wide_hop.rs @@ -28,9 +28,7 @@ async fn widest_hop_crosses_each_varint_form() { let upstream: Version = "moq-transport-18".parse().unwrap(); let _upstream = peer(upstream, &source, &relay).await; let _downstream = peer(downstream.parse().unwrap(), &relay, &sink).await; - let _route = source - .claim("room", moq_net::origin::RouteOptions::default()) - .unwrap(); + let _route = source.claim("room", moq_net::origin::RouteOptions::default()).unwrap(); kio::clock::sim::idle().await; let ids = |route: origin::RouteInfo| route.hops().collect::>(); From 2f2da91762f4a110232c78b1f8f9c3b1e295d442 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 22:48:35 -0800 Subject: [PATCH 11/12] chore(js/net): fmt after the merge Co-Authored-By: Claude Opus 5.5 --- js/net/src/origin.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/js/net/src/origin.test.ts b/js/net/src/origin.test.ts index 07823b56cad..b56dc11bc95 100644 --- a/js/net/src/origin.test.ts +++ b/js/net/src/origin.test.ts @@ -2353,9 +2353,7 @@ test("scoped wire views filter and rebase advertisements and blind requests", () test("a scoped dynamic is announced only to readers its scope can serve", async () => { const origin = new Producer(); - const dynamic = origin - .scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("*/chat")])) - .claim(Path.empty()); + const dynamic = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("*/chat")])).claim(Path.empty()); const chat = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("room/chat")])); const video = origin.scope(Path.empty(), new Path.Patterns([Path.Pattern.parse("room/video")])); await new Promise((resolve) => setImmediate(resolve)); From fb5e40c26c20e66361b7841c123250018d780073 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 8 Nov 2026 22:55:57 -0800 Subject: [PATCH 12/12] docs(c): the instance borrow note covers claims too Co-Authored-By: Claude Opus 5.5 --- doc/lib/c/index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index f9175f39911..970c4d63df5 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -96,8 +96,8 @@ answer with `moq_broadcast_request_serve()`, `moq_broadcast_request_route()`, or `moq_claim_set_cost()`, and `moq_claim_free()` control the claim. Unless one is named, a claim moves to a fresh instance (`moq_claim_instance()`) each time a job holding its current one ends, and a job from `moq_broadcast_request_route()` takes the claim's, so on moq-lite 07 a reader resolved through the -claim does not restart; older wires mint another instance for the job's route, restarting it. The string `moq_route_instance()` writes is borrowed until the -next `moq_route_instance()` on that route or `moq_route_free()`. +claim does not restart; older wires mint another instance for the job's route, restarting it. The string `moq_route_instance()` or `moq_claim_instance()` writes is +borrowed until the next such call on that handle, or until it is freed. Raw video encoders take an exact numerator/denominator frame rate, such as 30000/1001. Publication track names stay separate from codec settings. For simulcast, give each rendition the next one down as the `lower` handle in its `moq_video_encode_options`: it stops encoding, advertised as disabled, while its bandwidth grant cannot fund it, and resumes once the grant recovers. A rung only disables while the session probes for bandwidth, which on native transports takes moq-quic with BBR3. For pre-encoded video, publish from the lowest rendition up and set `moq_video_init.lower` to the next lower media handle. Reserve each track with `moq_allocator_reserve_media`, then bind its reservation with `moq_rate_control_create` and call `moq_rate_control_update` on every frame. Apply changed targets to your encoder and `moq_publish_media_set_enabled`, resuming video on a keyframe; close the control and reservation separately when done.