From fa43da652399cba0b00e1168fac2647beb90f25a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 15 Nov 2026 04:34:24 -0800 Subject: [PATCH 1/2] chore(quest): claim quest/m1/socket-endpoint-end.md Quest-Claim: fe0a14a5949391cf From 38e1af3110ebaf152896094e9186d45cb6700b6e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sun, 15 Nov 2026 06:29:00 -0800 Subject: [PATCH 2/2] fix(net): a socket endpoint's every ending runs its cleanup The endpoint's lifecycle is one State (Open | Closed(Error)), and every ending (close, drop, the server handler ending, a broadcast closing) goes through Shared::end. socket::is_endpoint reaches moq-ffi, moq-c, and every wrapper. Co-Authored-By: Claude Opus 5.5 --- dart/moq/lib/socket.dart | 4 + dart/moq_ffi/lib/src/moq.dart | 25 ++ doc/concept/socket.md | 6 +- go/wrapper/socket/socket.go | 4 + .../kotlin/dev/moq/socket/Socket.kt | 3 + py/moq-rs/moq/socket.py | 8 +- quest/m1/socket-endpoint-end.md | 23 -- rs/moq-c/README.md | 1 + rs/moq-c/src/socket.rs | 16 + rs/moq-c/src/test/parity.rs | 9 + rs/moq-ffi/src/socket.rs | 8 + rs/moq-ffi/src/test.rs | 10 + rs/moq-net/src/model/socket.rs | 293 ++++++++++-------- swift/Sources/Moq/Socket.swift | 5 + 14 files changed, 259 insertions(+), 156 deletions(-) delete mode 100644 quest/m1/socket-endpoint-end.md diff --git a/dart/moq/lib/socket.dart b/dart/moq/lib/socket.dart index 1da2fbe2ae5..a9156056454 100644 --- a/dart/moq/lib/socket.dart +++ b/dart/moq/lib/socket.dart @@ -10,5 +10,9 @@ typedef Endpoint = MoqSocketEndpoint; /// An incoming track dial, consumed by accepting or rejecting it. typedef IncomingTrack = MoqSocketIncomingTrack; +/// Whether [path] is an endpoint's broadcast, which only routes sessions and +/// carries no media. +bool isEndpoint(String path) => moqSocketIsEndpoint(path: path); + /// A track session with producer and reliably subscribed consumer halves. typedef TrackStream = MoqSocketTrackStream; diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index 2c5c866cab9..08745de3811 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -20253,6 +20253,17 @@ List moqVersions() { ); } +bool moqSocketIsEndpoint({required String path}) { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_func_moq_socket_is_endpoint( + FfiConverterString.lower(path), + status, + ), + FfiConverterBool.lift, + moqExceptionErrorHandler, + ); +} + @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -23628,6 +23639,14 @@ external RustBuffer uniffi_moq_ffi_fn_func_moq_versions( Pointer uniffiStatus, ); +@Native)>( + assetId: _uniffiAssetId, +) +external int uniffi_moq_ffi_fn_func_moq_socket_is_endpoint( + RustBuffer path, + Pointer uniffiStatus, +); + @Native< Void Function( Pointer, @@ -23967,6 +23986,9 @@ external int uniffi_moq_ffi_checksum_func_moq_qlog_supported(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_func_moq_versions(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_func_moq_socket_is_endpoint(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqaudioconsumer_cancel(); @@ -24852,6 +24874,9 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_func_moq_versions() != 28954) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_func_moq_socket_is_endpoint() != 51252) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_method_moqaudioconsumer_cancel() != 62285) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } diff --git a/doc/concept/socket.md b/doc/concept/socket.md index 5bb13e11c87..53714a78420 100644 --- a/doc/concept/socket.md +++ b/doc/concept/socket.md @@ -57,7 +57,11 @@ each other. Both role segments start with `.`, so endpoints are The announcements are used only for routing: they are how a relay finds an endpoint. Connections are never announced. An endpoint's broadcasts hold only -session tracks, served on request. +session tracks, served on request. A worker that acts on every announced +broadcast, such as a recorder, skips them: a path whose parent segment is +`.server` or `.client` is an endpoint's. Every library checks it as +`is_endpoint` (`isEndpoint` in JS, Swift, Kotlin, and Dart, `IsEndpoint` in Go, +and `moq_socket_is_endpoint` in C). ## Sessions diff --git a/go/wrapper/socket/socket.go b/go/wrapper/socket/socket.go index 92737e7fef5..4cde271d460 100644 --- a/go/wrapper/socket/socket.go +++ b/go/wrapper/socket/socket.go @@ -8,6 +8,10 @@ import ( "moq.dev/moq/internal/bridge" ) +// IsEndpoint reports whether path is an endpoint's broadcast, which only routes sessions and +// carries no media. +func IsEndpoint(path string) (bool, error) { return ffi.MoqSocketIsEndpoint(path) } + // Endpoint is a server, a client, or both, and dials and accepts track sessions. type Endpoint struct{ inner *ffi.MoqSocketEndpoint } diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/socket/Socket.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/socket/Socket.kt index 674bfad869c..0d8a719aa59 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/socket/Socket.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/socket/Socket.kt @@ -9,5 +9,8 @@ typealias Endpoint = uniffi.moq.MoqSocketEndpoint /** An incoming track dial, consumed by accepting or rejecting it. */ typealias IncomingTrack = uniffi.moq.MoqSocketIncomingTrack +/** Whether [path] is an endpoint's broadcast, which only routes sessions and carries no media. */ +fun isEndpoint(path: String): Boolean = uniffi.moq.moqSocketIsEndpoint(path) + /** A track session with producer and reliably subscribed consumer halves. */ typealias TrackStream = uniffi.moq.MoqSocketTrackStream diff --git a/py/moq-rs/moq/socket.py b/py/moq-rs/moq/socket.py index 484902c6cc7..adf625770c2 100644 --- a/py/moq-rs/moq/socket.py +++ b/py/moq-rs/moq/socket.py @@ -6,6 +6,7 @@ MoqSocketEndpoint, MoqSocketIncomingTrack, MoqSocketTrackStream, + moq_socket_is_endpoint, ) from ._records import _track_info @@ -14,7 +15,12 @@ from .subscribe import TrackConsumer from .types import TrackInfo -__all__ = ["Endpoint", "IncomingTrack", "TrackStream"] +__all__ = ["Endpoint", "IncomingTrack", "TrackStream", "is_endpoint"] + + +def is_endpoint(path: str) -> bool: + """Whether ``path`` is an endpoint's broadcast, which only routes sessions and carries no media.""" + return moq_socket_is_endpoint(path) class Endpoint: diff --git a/quest/m1/socket-endpoint-end.md b/quest/m1/socket-endpoint-end.md deleted file mode 100644 index e000d0080ba..00000000000 --- a/quest/m1/socket-endpoint-end.md +++ /dev/null @@ -1,23 +0,0 @@ -# [S] A socket endpoint's every ending runs its cleanup - -## Goal - -`moq_net::socket::Endpoint` models its lifecycle as one state whose ended -variant carries its error, and every ending, including the route broadcast -closing, goes through `close()`, so track streams already handed out end with -it as they do in JS. `is_endpoint` reaches moq-ffi, every binding, and the -socket guide. - -## Plan - -Found 2026-11-14 by the [feature review](/quest/m3/release/feature-review.md). -In `rs/moq-net/src/model/socket.rs`, `Handler::None` means both "not made -yet" and "ended", with `end: Option` stored beside it, and `poll_end` -returns `Closed` when a route broadcast closes without recording it or running -`close()`: when the origin shuts down, streams already handed out stay open -until the application drops the `Endpoint`. Shape it as REVIEW.md's State -section asks (`Open { .. } | Closed(Error)`). -[moq-dev/moq#8468](https://github.com/moq-dev/moq/pull/8468)'s -`socket::is_endpoint` exists only in Rust and JS. - -Public API: moq-ffi and every binding gain `is_endpoint`. Wire: none. diff --git a/rs/moq-c/README.md b/rs/moq-c/README.md index e38561df8ff..2134f212876 100644 --- a/rs/moq-c/README.md +++ b/rs/moq-c/README.md @@ -195,6 +195,7 @@ int32_t moq_consume_track_cancel(uint32_t track); // Sockets: two-way sessions between endpoints sharing an origin int32_t moq_socket_create(uint32_t origin, const char *prefix, uintptr_t prefix_len, const char *id, uintptr_t id_len); +int32_t moq_socket_is_endpoint(const char *path, uintptr_t path_len); // 1, 0, or a negative code int32_t moq_socket_close(uint32_t endpoint); int32_t moq_socket_dial_track(uint32_t endpoint, const char *peer, uintptr_t peer_len, const moq_track_info *info, moq_status_callback on_stream, void *user_data); int32_t moq_socket_accept_track(uint32_t endpoint, moq_status_callback on_incoming, void *user_data); diff --git a/rs/moq-c/src/socket.rs b/rs/moq-c/src/socket.rs index 159b070f405..a415c3a3d95 100644 --- a/rs/moq-c/src/socket.rs +++ b/rs/moq-c/src/socket.rs @@ -271,6 +271,22 @@ pub unsafe extern "C" fn moq_socket_create( }) } +/// Whether `path` is a socket endpoint's broadcast, which only routes sessions and carries no +/// media, so a worker that acts on every announced broadcast can skip it. +/// +/// Returns 1 if it is, 0 if not, or a negative code for a `path` that is not a valid path. +/// +/// # Safety +/// - `path` must point at `path_len` bytes. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn moq_socket_is_endpoint(path: *const c_char, path_len: usize) -> i32 { + ffi::enter(move || { + let path = unsafe { ffi::parse_str(path, path_len)? }; + let path = moq_net::Path::new(path).map_err(moq_net::Error::from)?; + Ok(i32::from(moq_net::socket::is_endpoint(&path))) + }) +} + /// Close a socket endpoint and release its handle. /// /// Withdraws the endpoint, ends its accept loops with a terminal `0`, fails its pending dials diff --git a/rs/moq-c/src/test/parity.rs b/rs/moq-c/src/test/parity.rs index 2ade15d3d08..da8d9c0b723 100644 --- a/rs/moq-c/src/test/parity.rs +++ b/rs/moq-c/src/test/parity.rs @@ -680,3 +680,12 @@ fn native_surfaces_are_unsupported_off_apple() { MOQ_ERROR_UNSUPPORTED ); } + +#[test] +fn socket_is_endpoint() { + let is_endpoint = |path: &str| unsafe { moq_socket_is_endpoint(path.as_ptr().cast(), path.len()) }; + assert_eq!(is_endpoint("room/.server/a"), 1); + assert_eq!(is_endpoint("room/.client/a"), 1); + assert_eq!(is_endpoint("room/a"), 0); + assert!(is_endpoint("room//a") < 0); +} diff --git a/rs/moq-ffi/src/socket.rs b/rs/moq-ffi/src/socket.rs index 376f0937019..6b3568bcb38 100644 --- a/rs/moq-ffi/src/socket.rs +++ b/rs/moq-ffi/src/socket.rs @@ -9,6 +9,14 @@ use crate::ffi::{Background, OneShot, Polled}; use crate::origin::MoqOriginProducer; use crate::producer::{MoqTrackInfo, MoqTrackProducer}; +/// Whether `path` is a socket endpoint's broadcast, which only routes sessions and carries +/// no media, so a worker that acts on every announced broadcast can skip it. +#[uniffi::export] +pub fn moq_socket_is_endpoint(path: String) -> Result { + let path = moq_net::Path::new(&path).map_err(moq_net::Error::from)?; + Ok(moq_net::socket::is_endpoint(&path)) +} + /// A socket endpoint: its first dial announces it as a client, and its first accept as a /// server. #[derive(uniffi::Object)] diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 3bb602ae61a..06712a49d9d 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -10043,3 +10043,13 @@ async fn group_calls_wake_ready_after_unlocking() { let result = parked.result.lock().unwrap().take(); assert!(matches!(result, Some(Err(MoqError::Closed))), "{result:?}"); } + +/// An endpoint's broadcast is told apart from media by path, and a malformed path fails. +#[test] +fn socket_is_endpoint() { + use crate::socket::moq_socket_is_endpoint; + assert!(moq_socket_is_endpoint("room/.server/a".into()).unwrap()); + assert!(moq_socket_is_endpoint("room/.client/a".into()).unwrap()); + assert!(!moq_socket_is_endpoint("room/a".into()).unwrap()); + assert!(moq_socket_is_endpoint("room//a".into()).is_err()); +} diff --git a/rs/moq-net/src/model/socket.rs b/rs/moq-net/src/model/socket.rs index 4fe146bb3a2..020540f8db4 100644 --- a/rs/moq-net/src/model/socket.rs +++ b/rs/moq-net/src/model/socket.rs @@ -194,8 +194,7 @@ impl TrackStream { /// The client broadcast has none, so it answers a request for a session it does not hold /// with [`Error::NotFound`] at once. enum Handler { - /// Not made yet, until the first accept makes the server broadcast with it, or no - /// longer, once the endpoint ended. + /// Not made yet, until the first accept makes the server broadcast with it. None, /// Waiting for a poller. Idle(super::broadcast::Requests), @@ -204,8 +203,25 @@ enum Handler { Taken(kio::WaiterList), } -/// What the endpoint's pollers share. -struct State { +/// An endpoint's lifecycle. +enum State { + Open(Box), + /// Ended, by [`Endpoint::close`] or one of its broadcasts ending, with why. + Closed(Error), +} + +impl State { + /// The open endpoint, or why it ended. + fn open(&mut self) -> Result<&mut Open, Error> { + match self { + Self::Open(open) => Ok(open), + Self::Closed(err) => Err(err.clone()), + } + } +} + +/// What an open endpoint's pollers share. +struct Open { /// The route of the broadcast this endpoint dials from, from its first dial on. client: Option, /// The route of the broadcast peers dial, from its first accept on. @@ -216,14 +232,23 @@ struct State { dials: VecDeque, /// The accepts waiting for a dial. waiting: kio::WaiterList, - /// This side's half of every session handed out, aborted when the endpoint closes. + /// This side's half of every session handed out, aborted when the endpoint ends. streams: Vec, - /// Why the endpoint stopped, once it did. - end: Option, } -impl State { - /// Keep `producer`'s track, so the endpoint closing ends it. +impl Open { + fn new() -> Self { + Self { + client: None, + server: None, + handler: Handler::None, + dials: VecDeque::new(), + waiting: kio::WaiterList::new(), + streams: Vec::new(), + } + } + + /// Keep `producer`'s track, so the endpoint ending ends it. fn hold(&mut self, producer: &track::Producer) { self.streams.retain(|stream| !stream.is_closed()); self.streams.push(producer.weak()); @@ -242,24 +267,16 @@ impl Shared { /// Made outside the lock, since announcing wakes local consumers, and announced only /// once it is the endpoint's, so a racing dial's spare is never seen. fn client(&self) -> Result { - { - let state = self.state.lock(); - if let Some(err) = &state.end { - return Err(err.clone()); - } - if let Some(route) = &state.client { - return Ok(route.clone()); - } + if let Some(route) = &self.state.lock().open()?.client { + return Ok(route.clone()); } let route = self.create(Role::Client)?; let mut state = self.state.lock(); - if let Some(err) = &state.end { - return Err(err.clone()); - } - if let Some(route) = &state.client { + let open = state.open()?; + if let Some(route) = &open.client { return Ok(route.clone()); } - state.client = Some(route.clone()); + open.client = Some(route.clone()); drop(state); route.announce()?; Ok(route) @@ -272,18 +289,13 @@ impl Shared { let route = self.create(Role::Server)?; // Before announcing, so the first dial finds it. let requests = route.broadcast().requests(); - let mut state = self.state.lock(); - if let Some(err) = &state.end { - return Err(err.clone()); - } - state.server = Some(route.clone()); - drop(state); + self.state.lock().open()?.server = Some(route.clone()); route.announce()?; Ok(requests) } /// Queue every dial on hand and take the next, registering `waiter` for more, and fail - /// with the endpoint's end once it stopped. The first call announces the + /// with the endpoint's end once it ended. The first call announces the /// server broadcast, and fails as [`origin::Producer::route`] does when the origin may /// not publish it. /// @@ -298,13 +310,12 @@ impl Shared { fn poll_dial(&self, waiter: &kio::Waiter) -> Poll> { let taken = { let mut state = self.state.lock(); - if state.end.is_some() { - None - } else if let Handler::Taken(waiting) = &mut state.handler { + let open = state.open()?; + if let Handler::Taken(waiting) = &mut open.handler { waiting.register(waiter); None } else { - match std::mem::replace(&mut state.handler, Handler::Taken(kio::WaiterList::new())) { + match std::mem::replace(&mut open.handler, Handler::Taken(kio::WaiterList::new())) { Handler::Idle(requests) => Some(Some(requests)), // No server broadcast yet: this poller makes it. Handler::None => Some(None), @@ -317,15 +328,15 @@ impl Shared { Ok(requests) => Some(requests), Err(err) => { // Given back for the next accept to try, waking those that found it taken, - // unless the endpoint closed meanwhile and took it. + // unless the endpoint ended meanwhile and took it. let mut state = self.state.lock(); - let waiting = match &mut state.handler { - Handler::Taken(waiting) => Some(waiting.take()), + let waiting = match state.open().map(|open| &mut open.handler) { + Ok(handler @ Handler::Taken(_)) => match std::mem::replace(handler, Handler::None) { + Handler::Taken(waiting) => Some(waiting), + _ => unreachable!("matched above"), + }, _ => None, }; - if waiting.is_some() { - state.handler = Handler::None; - } drop(state); if let Some(mut waiting) = waiting { waiting.wake(); @@ -350,34 +361,47 @@ impl Shared { } } + // The server broadcast ended: so does the endpoint, which wakes the pollers that + // found the handler taken. Dropped after, since `end` closes the server broadcast + // first: dropping the last handler rejects the dials still queued with `Dropped`, + // rather than the close's `Unroutable`. + if let Some(err) = ended { + let err = self.end(err); + drop(requests); + for request in taken { + request.reject(Error::Cancel); + } + return Poll::Ready(Err(err)); + } + let mut resets = Vec::new(); let mut wakes = Vec::new(); - let mut retired = None; let mut state = self.state.lock(); - if let Some(err) = ended { - state.end.get_or_insert(err); - } - // Put the handler back, unless the endpoint ended meanwhile: then it is dropped - // after the lock is released, with the server broadcast if `close` hasn't taken it. - if let Some(handler) = requests.take() { - let next = match state.end { - None => Handler::Idle(handler), - Some(_) => { - retired = Some((handler, state.server.take())); - Handler::None + let open = match state.open() { + Ok(open) => open, + // Ended meanwhile, which took the server broadcast and closed it or will: drop the + // handler, and reset the dials it took like the ones the end found queued. + Err(err) => { + drop(state); + drop(requests); + for request in taken { + request.reject(Error::Cancel); } - }; - if let Handler::Taken(mut waiting) = std::mem::replace(&mut state.handler, next) { - wakes.push(waiting.take()); + return Poll::Ready(Err(err)); } + }; + if let Some(handler) = requests.take() + && let Handler::Taken(mut waiting) = std::mem::replace(&mut open.handler, Handler::Idle(handler)) + { + wakes.push(waiting.take()); } // Dials whose dialer gave up leave the queue before an accept takes one, so it holds // no more than the dials still open, and an accept gets a live one. - if state.dials.iter().any(|request| !request.demand().is_wanted()) { - let (open, abandoned): (VecDeque<_>, VecDeque<_>) = std::mem::take(&mut state.dials) + if open.dials.iter().any(|request| !request.demand().is_wanted()) { + let (live, abandoned): (VecDeque<_>, VecDeque<_>) = std::mem::take(&mut open.dials) .into_iter() .partition(|request| request.demand().is_wanted()); - state.dials = open; + open.dials = live; resets.extend(abandoned.into_iter().map(|request| (request, Error::Cancel))); } for request in taken { @@ -388,35 +412,22 @@ impl Shared { _ => None, }; match target { - // Taken while the endpoint closed: reset like the dials it queued. - _ if state.end.is_some() => resets.push((request, Error::Cancel)), Some(true) => { - state.dials.push_back(request); - wakes.push(state.waiting.take()); + open.dials.push_back(request); + wakes.push(open.waiting.take()); } Some(false) => resets.push((request, Error::Unsupported)), None => resets.push((request, Error::NotFound)), } } - let next = match &state.end { - Some(err) => Poll::Ready(Err(err.clone())), - None => match state.dials.pop_front() { - Some(request) => Poll::Ready(Ok(request)), - None => { - state.waiting.register(waiter); - Poll::Pending - } - }, + let next = match open.dials.pop_front() { + Some(request) => Poll::Ready(Ok(request)), + None => { + open.waiting.register(waiter); + Poll::Pending + } }; drop(state); - if let Some((handler, server)) = retired { - // Closed first, as `close` may not have yet: dropping the last handler rejects - // the dials still queued with `Dropped`, rather than the close's `Unroutable`. - if let Some(server) = &server { - server.broadcast().close(); - } - drop(handler); - } for mut wake in wakes { wake.wake(); } @@ -438,59 +449,65 @@ impl Shared { } } - /// Poll for the endpoint's end, registering `waiter` for it. + /// Poll for the endpoint's end, registering `waiter` for it. Either broadcast ending + /// ends the endpoint. fn poll_end(&self, waiter: &kio::Waiter) -> Result<(), Error> { let routes = { - let state = self.state.lock(); - if let Some(err) = &state.end { - return Err(err.clone()); - } - [state.client.clone(), state.server.clone()] + let mut state = self.state.lock(); + let open = state.open()?; + [open.client.clone(), open.server.clone()] }; for route in routes.iter().flatten() { if route.broadcast().poll_closed(waiter).is_ready() { - return Err(Error::Closed); + return Err(self.end(Error::Closed)); } } Ok(()) } - fn close(&self) { - let mut guard = self.state.lock(); - let state = &mut *guard; - state.end.get_or_insert(Error::Closed); - let mut wakes = Vec::new(); - // A poller holding the handler drops it once it sees the end. - let requests = match std::mem::replace(&mut state.handler, Handler::None) { - Handler::Idle(requests) => Some(requests), - Handler::Taken(mut waiting) => { - wakes.push(waiting.take()); - None + /// End the endpoint with `err`, unless it ended already, and return why it ended. + /// + /// Retracts its broadcasts, resets the dials waiting to be accepted, and resets this + /// side's half of every session it handed out, all outside the lock. + fn end(&self, err: Error) -> Error { + let open = { + let mut state = self.state.lock(); + match &*state { + State::Closed(err) => return err.clone(), + State::Open(_) => match std::mem::replace(&mut *state, State::Closed(err.clone())) { + State::Open(open) => *open, + State::Closed(_) => unreachable!("matched above"), + }, } - Handler::None => None, }; - let queued = std::mem::take(&mut state.dials); - wakes.push(state.waiting.take()); - let streams = std::mem::take(&mut state.streams); - let routes = [state.client.take(), state.server.take()]; - drop(guard); - - // Reset outside the lock, as the session closing, and before retracting the - // broadcasts: a peer reading through a retracted route sees `Unroutable` instead. + let Open { + client, + server, + handler, + dials, + mut waiting, + streams, + } = open; + + // Reset as the session closing, and before retracting the broadcasts: a peer reading + // through a retracted route sees `Unroutable` instead. for stream in streams { stream.abort(Error::Stream(StreamError::Session(SessionError::Cancel))); } + let routes = [client, server]; for route in routes.iter().flatten() { route.broadcast().close(); } - for request in queued { + for request in dials { request.reject(Error::Cancel); } - for mut wake in wakes { - wake.wake(); + waiting.wake(); + // A poller holding the handler drops it once it sees the end. + if let Handler::Taken(mut waiting) = handler { + waiting.wake(); } - drop(requests); drop(routes); + err } } @@ -505,8 +522,9 @@ impl Shared { /// accepted. Until then it has no server broadcast, so a dial to it waits as for a peer /// not online yet. /// -/// Dropping it, or [`Self::close`], retracts its broadcasts, resets the dials waiting to be -/// accepted, and resets this side's half of every session it handed out. The peer's half +/// Dropping it, [`Self::close`], or either of its broadcasts ending, retracts its broadcasts, +/// resets the dials waiting to be accepted, and resets this side's half of every session it +/// handed out. The peer's half /// of a [`TrackStream`] is read through /// its [`TrackStream::consumer`], which the application owns: drop the streams too, which /// releases the subscriptions. @@ -545,15 +563,7 @@ impl Endpoint { publisher: origin.clone(), withheld: consumer.hidden_withheld(), origin: consumer, - state: kio::Lock::new(State { - client: None, - server: None, - handler: Handler::None, - dials: VecDeque::new(), - waiting: kio::WaiterList::new(), - streams: Vec::new(), - end: None, - }), + state: kio::Lock::new(State::Open(Box::new(Open::new()))), }), }) } @@ -630,13 +640,13 @@ impl Endpoint { /// Close the endpoint; see [`Endpoint`]. pub fn close(&self) { - self.shared.close(); + self.shared.end(Error::Closed); } } impl Drop for Endpoint { fn drop(&mut self) { - self.shared.close(); + self.shared.end(Error::Closed); } } @@ -764,14 +774,11 @@ fn open( peer: &Arc, session: &Arc, ) -> Result { - let mut state = shared.state.lock(); - if let Some(err) = state.end.clone() { - drop(state); + let held = shared.state.lock().open().map(|open| open.hold(&producer)); + if let Err(err) = held { let _ = producer.abort(err.clone()); return Err(err); } - state.hold(&producer); - drop(state); Ok(TrackStream { producer, consumer: step.take_subscriber(), @@ -1027,7 +1034,7 @@ mod tests { // The handler is out being polled, so this waits for it. let accept = self.shared.poll_dial(&kio::Waiter::noop()); assert!(accept.is_pending()); - self.shared.close(); + self.shared.end(Error::Closed); self.woken.store(true, Ordering::SeqCst); } } @@ -1040,7 +1047,7 @@ mod tests { // Listening, so the dial queues for the handler. assert!(endpoint.poll_accept_track(&noop).is_pending()); - let server = endpoint.shared.state.lock().server.clone().unwrap(); + let server = endpoint.shared.state.lock().open().unwrap().server.clone().unwrap(); let broadcast = server.broadcast().consume(); let dial = broadcast .track("track/alice/bob/0123456789abcdef0123456789abcdef") @@ -1079,9 +1086,9 @@ mod tests { let noop = kio::Waiter::noop(); assert!(endpoint.poll_accept_track(&noop).is_pending()); - let server = endpoint.shared.state.lock().server.clone().unwrap(); + let server = endpoint.shared.state.lock().open().unwrap().server.clone().unwrap(); let broadcast = server.broadcast().consume(); - let queued = || endpoint.shared.state.lock().dials.len(); + let queued = || endpoint.shared.state.lock().open().unwrap().dials.len(); let dial = |session: u32| { let dial = broadcast .track(&format!("track/alice/bob/{session:032x}")) @@ -1110,6 +1117,30 @@ mod tests { assert_eq!(queued(), 1); } + /// Either broadcast ending ends the endpoint as closing it does: the sessions it handed + /// out are reset, and it dials and accepts no more. + #[kio::test] + #[cfg(feature = "async")] + async fn a_broadcast_ending_ends_the_endpoint() { + let (origin, driver) = origin::Producer::new(origin::Config::new(std::num::NonZeroU64::new(1).unwrap())); + let _driver = kio::clock::sim::spawn(crate::time::run(driver)); + let alice = Endpoint::new(&origin, "room", "alice").unwrap(); + let bob = Endpoint::new(&origin, "room", "bob").unwrap(); + let accept = async { bob.accept_track().await.unwrap().accept(None).await.unwrap() }; + let (dialed, accepted) = + futures::join!(async { alice.dial_track("bob", None).unwrap().await.unwrap() }, accept); + + let server = bob.shared.state.lock().open().unwrap().server.clone().unwrap(); + server.broadcast().close(); + assert!(matches!(bob.accept_track().await, Err(Error::Closed))); + assert!( + accepted.producer.append_group(0).is_err(), + "a handed-out half outlived the end" + ); + assert!(matches!(bob.dial_track("alice", None), Err(Error::Closed))); + drop(dialed); + } + #[test] fn session_ids_are_128_bits() { let (a, b) = (session_id(), session_id()); diff --git a/swift/Sources/Moq/Socket.swift b/swift/Sources/Moq/Socket.swift index 73f5e748ece..bbf0a1e43ee 100644 --- a/swift/Sources/Moq/Socket.swift +++ b/swift/Sources/Moq/Socket.swift @@ -4,6 +4,11 @@ import MoqFFI public enum Socket {} extension Socket { + /// Whether `path` is an endpoint's broadcast, which only routes sessions and carries no media. + public static func isEndpoint(_ path: String) throws -> Bool { + try moqSocketIsEndpoint(path: path) + } + /// A server, a client, or both: dials or accepts track sessions. public final class Endpoint: Sendable { let ffi: MoqSocketEndpoint