Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions dart/moq_ffi/lib/src/moq.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12039,11 +12039,11 @@ void _checkApiChecksums() {
throw UniffiInternalError.panicked("UniFFI API checksum mismatch");
}
if (uniffi_moq_ffi_checksum_method_moqoriginconsumer_announced_broadcast() !=
19912) {
33060) {
throw UniffiInternalError.panicked("UniFFI API checksum mismatch");
}
if (uniffi_moq_ffi_checksum_method_moqoriginconsumer_request_broadcast() !=
37085) {
18586) {
throw UniffiInternalError.panicked("UniFFI API checksum mismatch");
}
if (uniffi_moq_ffi_checksum_method_moqorigindynamic_cancel() != 47453) {
Expand Down
2 changes: 1 addition & 1 deletion py/moq-rs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ Every handle whose cleanup is `cancel()` is an async context manager, so exiting
- Async iterator yielding `BroadcastRequest`
- **`OriginConsumer`**. Discover broadcasts.
- `.announced(prefix, filter=None) → AnnounceConsumer` (async iterator); `filter` is a pattern relative to the literal prefix, while each update's `.prefix` stays origin-relative and `.captures` reports wildcard matches
- `.announced_broadcast(path) → AnnouncedBroadcast` (awaitable, waits for a future announcement)
- `.announced_broadcast(path) → AnnouncedBroadcast` (awaitable, waits until something serves the path)
- `.request_broadcast(path) → BroadcastConsumer` (awaitable; announced now or a dynamic fallback, else raises)

### Types
Expand Down
12 changes: 8 additions & 4 deletions py/moq-rs/moq/origin.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,17 +185,21 @@ def announced(self, prefix: str = "", *, filter: str | None = None) -> AnnounceC
return AnnounceConsumer(self._inner.announced(MoqAnnounceConfig(prefix=prefix, filter=filter)))

def announced_broadcast(self, path: str) -> AnnouncedBroadcast:
"""Await a route covering ``path``, then resolve the broadcast there."""
"""Await the broadcast at ``path``, resolving once something can serve it.

Serving and advertising are separate, so a local broadcast at the exact
path resolves without ever being announced.
"""
return AnnouncedBroadcast(self._inner.announced_broadcast(path))

async def request_broadcast(self, path: str) -> BroadcastConsumer:
"""Request a broadcast by path, resolving as soon as it can be served.

Resolution order: a local broadcast at the exact path, then the best
announced route covering the path (served on demand by the session that
announced it), then a dynamic handler on the origin (if any); raises if
nothing can serve it. Unlike `announced_broadcast`, this does not wait
for a future announcement.
announced it), then a dynamic handler on the origin (if any). Unlike
`announced_broadcast`, this answers for what is reachable now and raises
if nothing can serve the path.
"""
return BroadcastConsumer(await self._inner.request_broadcast(path))

Expand Down
18 changes: 9 additions & 9 deletions rs/libmoq/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1518,13 +1518,13 @@ pub extern "C" fn moq_origin_announced_cancel(announced: u32) -> i32 {
})
}

/// Consume a broadcast from an origin by path, waiting until it is announced.
/// Consume a broadcast from an origin by path, waiting until something can serve it.
///
/// Resolves against future announcements: it waits for the announcement to arrive (e.g. over the
/// network) and then delivers the broadcast handle via `on_broadcast`. Use it right after
/// [moq_session_connect] to avoid racing announcement gossip. To resolve against only what is
/// reachable by exact path now (including unannounced broadcasts), use [moq_origin_request]
/// instead.
/// It waits for whatever will serve the path to arrive (e.g. an announcement over the network)
/// and then delivers the broadcast handle via `on_broadcast`. Use it right after
/// [moq_session_connect] to avoid racing announcement gossip. Serving and advertising are
/// separate, so a local broadcast at the exact path resolves without ever being announced. To
/// answer for what is reachable now and fail otherwise, use [moq_origin_request] instead.
///
/// `on_broadcast` is invoked with a positive broadcast handle once announced, then exactly once
/// more with a terminal code: `0` (the wait finished, including after
Expand Down Expand Up @@ -1572,9 +1572,9 @@ pub extern "C" fn moq_origin_announced_broadcast_cancel(task: u32) -> i32 {
/// Request a broadcast from an origin by path, resolving as soon as it can be served.
///
/// Resolves against what is reachable by exact path *now*, where
/// [moq_origin_announced_broadcast] waits indefinitely for a future announcement: it returns an
/// existing broadcast at once, whether announced or not, and fails when none is reachable. It does
/// NOT wait for a later announcement. Serve on-demand paths with [moq_origin_dynamic].
/// [moq_origin_announced_broadcast] waits indefinitely: it returns an existing broadcast at once,
/// whether announced or not, and fails when none is reachable. It does NOT wait for a later
/// announcement. Serve on-demand paths with [moq_origin_dynamic].
///
/// `on_broadcast` is invoked with a positive broadcast handle once served, then exactly once more
/// with a terminal code: `0` (finished, including after [moq_origin_request_cancel]) or a negative
Expand Down
2 changes: 1 addition & 1 deletion rs/libmoq/src/origin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ impl Origin {
path: String,
mut close: oneshot::Receiver<()>,
) -> Result<(), Error> {
// `routed_broadcast` rides out the churn between a route covering the path
// `routed_broadcast` rides out the churn between something covering the path
// and the path actually resolving (failover, an advertise-only announce
// racing its handler). `biased` so a pending close always wins.
let broadcast = tokio::select! {
Expand Down
14 changes: 8 additions & 6 deletions rs/moq-ffi/src/origin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ struct AnnouncedBroadcast {

impl AnnouncedBroadcast {
async fn available(&mut self) -> Result<Arc<MoqBroadcastConsumer>, MoqError> {
// `routed_broadcast` rides out the churn between a route covering the path
// `routed_broadcast` rides out the churn between something covering the path
// and the path actually resolving (failover, an advertise-only announce
// racing its handler).
let broadcast = self.origin.routed_broadcast(&self.path).await?;
Expand Down Expand Up @@ -329,10 +329,12 @@ impl MoqOriginConsumer {
}))
}

/// Wait for a route to cover `path`, then resolve the broadcast there.
/// Resolve the broadcast at `path`, waiting until something can serve it.
///
/// This is how you resolve a path right after connecting: announcements arrive over the
/// session after it opens, so `request_broadcast` on its own races them.
/// session after it opens, so `request_broadcast` on its own races them. Serving and
/// advertising are separate, so a local broadcast at the exact path resolves without
/// ever being announced.
pub fn announced_broadcast(&self, path: String) -> Result<Arc<MoqAnnouncedBroadcast>, MoqError> {
let _guard = crate::ffi::enter();
let path = moq_net::Path::new(&path).to_owned();
Expand All @@ -358,9 +360,9 @@ impl MoqOriginConsumer {
///
/// Resolution order: a local broadcast at the exact path, then the best announced route
/// covering the path (served on demand by the session that announced it), then a dynamic
/// handler on the origin (if any). Errors if nothing can serve it. Unlike
/// `announced_broadcast`, this does *not* wait for a future announcement. Drop the
/// returned future to cancel.
/// handler on the origin (if any). Unlike `announced_broadcast`, this answers for what is
/// reachable *now* and errors if nothing can serve the path. Drop the returned future to
/// cancel.
///
/// Calling this straight after connecting therefore races the session's announcements
/// and can report a live broadcast as unroutable. Await `announced_broadcast` first.
Expand Down
40 changes: 29 additions & 11 deletions rs/moq-ffi/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1287,31 +1287,49 @@ fn audio_rejects_bad_init_bytes() {
);
}

/// Creating a broadcast does not advertise it. `announced_broadcast` waits until
/// `announce` makes the exact path discoverable; `request_broadcast` can still
/// resolve it by exact path in the meantime.
/// Creating a broadcast does not advertise it: nothing crosses the announce cursor
/// until `announce`. It is reachable the whole time, because serving the path and
/// advertising it are separate: both `request_broadcast` and `announced_broadcast`
/// resolve it by exact path.
#[tokio::test]
async fn create_broadcast_does_not_announce() {
let origin = MoqOriginProducer::new(MoqOriginConfig::default());
let consumer = origin.consume();
let broadcast = origin.create_broadcast("live".into()).unwrap();

tokio::time::timeout(TIMEOUT, consumer.request_broadcast("live".into()))
.await
.expect("timed out requesting the unannounced broadcast")
.expect("an unannounced broadcast stays reachable by exact path");
for reached in ["request", "announced"] {
let resolving = async {
match reached {
"request" => consumer.request_broadcast("live".into()).await.map(|_| ()),
_ => consumer
.announced_broadcast("live".into())
.unwrap()
.available()
.await
.map(|_| ()),
}
};
tokio::time::timeout(TIMEOUT, resolving)
.await
.unwrap_or_else(|_| panic!("timed out reaching the unannounced broadcast by {reached}"))
.unwrap_or_else(|err| panic!("an unannounced broadcast stays reachable by {reached}: {err}"));
}

let announced = consumer.announced_broadcast("live".into()).unwrap();
let pending = tokio::spawn(async move { announced.available().await });
// The cursor is the advertisement, so it is what must stay silent.
let announced = consumer.announced(MoqAnnounceConfig::default()).unwrap();
let pending = tokio::spawn(async move { announced.next().await });
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
assert!(!pending.is_finished(), "create_broadcast must not advertise the path");

broadcast.announce(MoqRoute::default()).unwrap();
tokio::time::timeout(TIMEOUT, pending)
let update = tokio::time::timeout(TIMEOUT, pending)
.await
.expect("timed out waiting for announce")
.expect("task")
.expect("announce makes the path discoverable");
.expect("announce reaches the cursor")
.expect("the cursor is still open");
assert_eq!(update.prefix(), "live");
assert!(update.active());
broadcast.finish().unwrap();
}

Expand Down
84 changes: 61 additions & 23 deletions rs/moq-net/src/model/origin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3164,10 +3164,10 @@ impl Consumer {
/// including the exact path itself. Returns `None` if the path is outside this
/// consumer's scope or the consumer is closed first.
///
/// Use this before [`Self::request_broadcast`] whenever the announcement may
/// not have arrived yet, which includes every path you resolve right after
/// connecting: `request_broadcast` answers on the spot, so asking it first
/// races the announcement and reports a covered path as unroutable.
/// To resolve a broadcast rather than inspect the route, use
/// [`Self::routed_broadcast`]: pairing this with [`Self::request_broadcast`]
/// leaves a gap where the covering route can retract, and misses a local
/// broadcast that serves the path without announcing.
pub async fn routed(&self, path: impl AsPath) -> Option<Route> {
let path = path.as_path();

Expand Down Expand Up @@ -3199,17 +3199,19 @@ impl Consumer {
}
}

/// Block until `path` resolves to a broadcast: [`Self::routed`], then
/// [`Self::request_broadcast`], retried when the two race.
/// Block until `path` resolves to a broadcast: [`Self::request_broadcast`],
/// retried whenever the routes covering the path change.
///
/// The wait and the resolution are separate steps, so the covering route can
/// retract between them (failover churn), a route can cover the path while
/// nothing serves it yet (an advertise-only announce racing its handler), and
/// a handler can turn the path down. This rides out the churn by retrying
/// whenever the route table moves, which is what makes it the right call for
/// resolving a path right after connecting. Returns [`Error::Unauthorized`]
/// for a path outside this consumer's scope, [`Error::Closed`] once the origin
/// closes, and any other resolution failure as-is.
/// A request answers for the routes as they stand, so it can miss an
/// announcement that has not arrived yet, lose its covering route to
/// failover churn, find a route that covers the path while nothing serves it
/// yet (an advertise-only announce racing its handler), or be turned down by
/// a handler. This rides all of that out by watching the covering routes
/// and asking again each time they move, which is what makes it the right
/// call for resolving a path right after connecting. Returns
/// [`Error::Unauthorized`] for a path outside this consumer's scope,
/// [`Error::Closed`] once the origin closes, and any other resolution
/// failure as-is.
pub async fn routed_broadcast(&self, path: impl AsPath) -> Result<broadcast::Consumer, Error> {
let path = path.as_path();

Expand All @@ -3219,18 +3221,14 @@ impl Consumer {
return Err(Error::Unauthorized);
}
loop {
if self.routed(&path).await.is_none() {
return Err(Error::Closed);
}
// `Unroutable` is a verdict of the routes covering the path as they
// stood when the request was made: nothing covered it, the serving
// route retracted under the request, or its handler declined.
// Re-asking the same routes would spin, so watch them before asking
// and wait for them to move (an identical standby swapping in
// counts, even though no announce update reports it, and so does a
// stood when the request was made. Re-asking the same routes would
// spin, so watch them before asking and wait for them to move (a
// route arriving or retracting, an identical standby swapping in, a
// local broadcast attaching at the path), then try again. A change
// between the ask and the wait bumps the watch first, so that retry
// is immediate.
// is immediate; the teardown pokes every watch, so a closed origin
// is observed on the next pass.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let (watch, seen) = {
let mut table = self.shared.lock();
if table.closed {
Expand All @@ -3245,6 +3243,9 @@ impl Consumer {
Err(Error::Unroutable) => {
kio::wait(|waiter| watch.poll_changed(waiter, seen)).await;
}
// Teardown parks a pending request with `Dropped`; the contract is
// `Closed` once the origin is gone.
Err(Error::Dropped) if self.shared.lock().closed => return Err(Error::Closed),
Err(err) => return Err(err),
}
}
Expand Down Expand Up @@ -4454,6 +4455,43 @@ mod tests {
resolving.await.expect("resolves");
}

/// A local broadcast serves its path without announcing it, so there is no
/// route to wait for: the request resolves on the first pass.
#[tokio::test]
async fn routed_broadcast_resolves_an_unannounced_local_broadcast() {
let producer = origin(1).produce();
let consumer = producer.consume();

let _local = producer.create_broadcast("room/alice").unwrap();
let resolved = tokio::time::timeout(Duration::from_secs(5), consumer.routed_broadcast("room/alice"))
.await
.expect("resolves without an announce")
.expect("resolves locally");
assert_eq!(resolved.info().path.as_str(), "room/alice");
}

/// Teardown rejects a parked request with `Dropped`, but a destroyed origin
/// is `Closed` to `routed_broadcast`'s callers.
#[tokio::test]
async fn routed_broadcast_reports_teardown_as_closed() {
let (producer, driver) = Producer::new(Config::new(origin(1)));
let consumer = producer.consume();
let _server = producer.dynamic("room", Route::default()).unwrap();

// Park on the covering route, past the loop's closed check.
let mut resolving = Box::pin(consumer.routed_broadcast("room/alice"));
assert!((&mut resolving).now_or_never().is_none());

drop(driver);

let err = tokio::time::timeout(Duration::from_secs(5), resolving)
.await
.expect("teardown resolves the wait")
.err()
.unwrap();
assert!(matches!(err, Error::Closed), "unexpected end: {err}");
}

/// A local broadcast appearing at the exact path is a table change too: a
/// requester parked on a handler's rejection resolves to it.
#[tokio::test]
Expand Down
Loading