diff --git a/Cargo.lock b/Cargo.lock index f98343aff21..c4b0bb3cb2f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6872,9 +6872,9 @@ dependencies = [ [[package]] name = "qmux" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78229d7c17aefedb12668c8e28db3dc648b69fc80c025c4b899e48982671caf8" +checksum = "dad25762c86aa1eaf3ef0b660fd83773fe5c961e8b3c3a7a6815f8c155338061" dependencies = [ "bytes", "futures", diff --git a/Cargo.toml b/Cargo.toml index ec9acc5b531..671d13b42f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -202,7 +202,7 @@ objc2-screen-capture-kit = "0.3.2" object_store = { version = "0.14", default-features = false } percent-encoding = "2" pollster = "1.0" -qmux = { version = "0.5.2", default-features = false } +qmux = { version = "0.5.3", default-features = false } rand = "0.10.1" # default-features off so each consumer picks its own TLS backend and body # features; nothing here wants the default native-tls stack. diff --git a/dart/moq/CHANGELOG.md b/dart/moq/CHANGELOG.md index fbfc8014fa5..ce33aef59b1 100644 --- a/dart/moq/CHANGELOG.md +++ b/dart/moq/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.1.1 + +- `Moq.drain()` delivers finished tracks within one second before closing. + ## 0.1.0 - Initial Dart and Flutter client with connection and announcement helpers. diff --git a/dart/moq/lib/src/client.dart b/dart/moq/lib/src/client.dart index 714fda2829d..ed80b576737 100644 --- a/dart/moq/lib/src/client.dart +++ b/dart/moq/lib/src/client.dart @@ -208,4 +208,15 @@ final class Moq { session.shutdown(); _client.cancel(); } + + /// Drain finished tracks within one second, then close the session and stop + /// the client, failing if the drain does. Finish or abort live tracks first; + /// [close] stays immediate. + Future drain() async { + try { + await session.drain(); + } finally { + _client.cancel(); + } + } } diff --git a/dart/moq/pubspec.yaml b/dart/moq/pubspec.yaml index 015dd85d2fe..c4f83f4bc90 100644 --- a/dart/moq/pubspec.yaml +++ b/dart/moq/pubspec.yaml @@ -1,6 +1,6 @@ name: moq description: Idiomatic Dart and Flutter client for Media over QUIC. -version: 0.1.0 +version: 0.1.1 repository: https://github.com/moq-dev/moq/tree/main/dart/moq issue_tracker: https://github.com/moq-dev/moq/issues topics: diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index b91803e2d79..593ec02faa9 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -7946,6 +7946,7 @@ abstract class MoqSessionInterface { void cancel({required int code}); Future closed(); MoqOriginConsumer consume(); + Future drain(); int epoch(); MoqOriginProducer publish(); void shutdown(); @@ -8019,6 +8020,17 @@ class MoqSession implements MoqSessionInterface { ); } + Future drain() { + return uniffiRustCallAsync( + () => uniffi_moq_ffi_fn_method_moqsession_drain(uniffiClonePointer()), + ffi_moq_ffi_rust_future_poll_void, + ffi_moq_ffi_rust_future_complete_void, + ffi_moq_ffi_rust_future_free_void, + (_) {}, + moqExceptionErrorHandler, + ); + } + int epoch() { return rustCallWithLifter( (status) => uniffi_moq_ffi_fn_method_moqsession_epoch( @@ -11502,6 +11514,11 @@ external Pointer uniffi_moq_ffi_fn_method_moqsession_consume( Pointer uniffiStatus, ); +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqsession_drain( + Pointer ptr, +); + @Native, Pointer)>( assetId: _uniffiAssetId, ) @@ -12430,6 +12447,9 @@ external int uniffi_moq_ffi_checksum_method_moqsession_closed(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_consume(); +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqsession_drain(); + @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_epoch(); @@ -13043,6 +13063,9 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqsession_consume() != 45358) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } + if (uniffi_moq_ffi_checksum_method_moqsession_drain() != 51983) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } if (uniffi_moq_ffi_checksum_method_moqsession_epoch() != 32695) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index feb90f7b5d3..81d086b208d 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -82,6 +82,8 @@ and `backoff:` re-paces the retries. `moq.epoch` counts the connections, 1 on th `session.status()` to log each reconnect; `maxStreams` raises the peer's inbound stream cap for a subscriber to many tracks. +Await `moq.drain()` (or `session.drain()`) to deliver finished tracks before disconnecting. It fails if the drain has not completed within one second. Finish or abort live tracks first; `moq.close()`, `shutdown()`, and `cancel(code:)` stay immediate. The drain waits for the transport to acknowledge the tail, not for the peer to read it; a moq-transport (IETF) session closes without waiting. + The [WebSocket fallback](/concept/transport#websocket-fallback) races QUIC after a 200 ms head start. `websocketEnabled: false` turns it off for a QUIC-only relay, and a `websocketDelay` `Duration` changes the head start. diff --git a/doc/lib/go/index.md b/doc/lib/go/index.md index acaf8ac0674..2fd76326dcc 100644 --- a/doc/lib/go/index.md +++ b/doc/lib/go/index.md @@ -108,6 +108,8 @@ each reconnect by number; `moq.WithBackoff` tunes the pacing, with `moq.RetryForever` as the timeout; and `moq.WithQUICMaxStreams` raises the peer's inbound stream cap for a subscriber to many tracks. +`Session().Drain(ctx)` delivers finished tracks before disconnecting and returns an error if the drain has not completed within one second; cancelling ctx aborts immediately. Finish or abort live tracks first; `Client.Close()`, `Shutdown()`, and `Cancel(code)` stay immediate. The drain waits for the transport to acknowledge the tail, not for the peer to read it; a moq-transport (IETF) session closes without waiting. + The [WebSocket fallback](/concept/transport#websocket-fallback) races QUIC after a 200 ms head start. `moq.WithWebSocketEnabled(false)` turns it off for a QUIC-only relay, and `moq.WithWebSocketDelay` changes the head start. diff --git a/doc/lib/kt/index.md b/doc/lib/kt/index.md index df948961c9b..d42e73be554 100644 --- a/doc/lib/kt/index.md +++ b/doc/lib/kt/index.md @@ -74,6 +74,8 @@ broadcasts. `moq.epoch()` counts the connections, 1 on the first, pairing with pacing (`timeoutUs = 0` retries forever); and `maxStreams` raises the peer's inbound stream cap. +Call suspending `moq.drain()` (or `session.drain()`) to deliver finished tracks before disconnecting. It throws if the drain has not completed within one second. Finish or abort live tracks first; `close()`, `use { }`, `shutdown()`, and `cancel(code)` stay immediate. The drain waits for the transport to acknowledge the tail, not for the peer to read it; a moq-transport (IETF) session closes without waiting. + The [WebSocket fallback](/concept/transport#websocket-fallback) races QUIC after a 200 ms head start. `Moq.connect(websocketEnabled = false)` turns it off for a QUIC-only relay, and a `websocketDelay` `Duration` changes the head start. diff --git a/doc/lib/py/index.md b/doc/lib/py/index.md index 5a597e7e336..320795fda03 100644 --- a/doc/lib/py/index.md +++ b/doc/lib/py/index.md @@ -94,6 +94,8 @@ with `session.status()` to log each reconnect; `moq.Backoff` tunes the pacing (`timeout_us=0` retries forever); and `moq.connect(..., max_streams=...)` raises the peer's inbound stream cap. +Await `session.drain()` to deliver finished tracks before disconnecting. It raises if the drain has not completed within one second. Finish or abort live tracks first; `shutdown()`, `cancel(code)`, and the async context managers stay immediate. The drain waits for the transport to acknowledge the tail, not for the peer to read it; a moq-transport (IETF) session closes without waiting. + The [WebSocket fallback](/concept/transport#websocket-fallback) races QUIC after a 200 ms head start. Pass `websocket_enabled=False` to `moq.connect` for a QUIC-only relay, or a `websocket_delay` `timedelta` to change the head start. diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index 7fc2f410199..ba2739c7037 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -82,6 +82,8 @@ broadcasts. `session.epoch()` counts the connections, 1 on the first, pairing with `session.status()` to log each reconnect; `client.setBackoff` tunes the pacing; and `client.setQuicMaxStreams` raises the peer's inbound stream cap. +Use `try await session.drain()` to deliver finished tracks before disconnecting. It throws if the drain has not completed within one second. Finish or abort live tracks first; `shutdown()` and `cancel(code:)` stay immediate. The drain waits for the transport to acknowledge the tail, not for the peer to read it; a moq-transport (IETF) session closes without waiting. + The [WebSocket fallback](/concept/transport#websocket-fallback) races QUIC after a 200 ms head start. `client.setWebsocketEnabled(false)` turns it off for a QUIC-only relay, and `client.setWebsocketDelay(_:)` changes the head start, in diff --git a/go/wrapper/session.go b/go/wrapper/session.go index d1a594a9d34..f1871d39f48 100644 --- a/go/wrapper/session.go +++ b/go/wrapper/session.go @@ -108,6 +108,13 @@ func (s *Session) Shutdown() { s.inner.Shutdown() } +// Drain delivers finished tracks within one second, then closes the session, +// returning an error if the drain fails. Finish or abort live tracks first. +// Cancelling ctx aborts the session immediately. +func (s *Session) Drain(ctx context.Context) error { + return runErr(ctx, s.inner.Shutdown, s.inner.Drain) +} + // Cancel closes the session abruptly with an application error code. func (s *Session) Cancel(code uint32) { s.inner.Cancel(code) diff --git a/kt/gradle.properties b/kt/gradle.properties index 577121dc662..10524cc6e62 100644 --- a/kt/gradle.properties +++ b/kt/gradle.properties @@ -14,7 +14,7 @@ moqffi.version=0.0.0-dev # Wrapper (`dev.moq:moq`) version. Source of truth, bumped by hand. Independent # of the crate: release-kt-lib.yml publishes a new version only when this # changes. Must stay >= the last published wrapper version. -moq.version=0.5.2 +moq.version=0.5.3 # Publishing is disabled by default. CI flips this when MAVEN_CENTRAL_USERNAME # and SIGNING_KEY secrets are configured. See README.md for setup details. diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt index f3966d10def..09614823b31 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt @@ -74,6 +74,19 @@ class Moq internal constructor( */ fun bandwidth(): Bandwidth = session.bandwidth() + /** + * Drain finished tracks within one second, then close the session and cancel the + * client, throwing if the drain fails. Finish or abort live tracks first; [close] + * stays immediate. + */ + suspend fun drain() { + try { + session.drain() + } finally { + client.cancel() + } + } + /** Gracefully shut down the session and cancel the client, releasing the native handles. */ override fun close() { session.shutdown() diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index 75d2c1ea877..c0ac9750e12 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -142,6 +142,7 @@ client = moq.Client( - **`Session`**. An established connection. Holding it keeps the connection alive; it is also an `async with` context manager that shuts down on exit. - `await .closed()`. Wait until the session closes. - `.cancel(code)`, `.shutdown()`. Close with an error code, or gracefully (code 0). + - `await .drain()`. Deliver finished tracks within one second, then close, raising if the drain fails. - `.publish() → OriginProducer`, `.consume() → OriginConsumer`. The wired origin sides. - `.stats() → ConnectionStats`. Snapshot RTT, bandwidth estimates, and byte/packet counters. - `await .status() → ConnectionStatus`, `.epoch()`. Watch reconnects; the epoch counts connections, 1 on the first. diff --git a/py/moq-rs/moq/session.py b/py/moq-rs/moq/session.py index 3001df09dc6..72c2e7b7895 100644 --- a/py/moq-rs/moq/session.py +++ b/py/moq-rs/moq/session.py @@ -69,6 +69,15 @@ def shutdown(self) -> None: """Graceful shutdown; equivalent to `cancel(0)` (0 means no error).""" self._inner.shutdown() + async def drain(self) -> None: + """Drain finished tracks within one second, then close, raising if the drain fails. + + Finish or abort live tracks first; :meth:`shutdown` and :meth:`cancel` stay + immediate. The drain waits for the transport to acknowledge the tail, not + for the peer to read it; a moq-transport (IETF) session closes without + waiting.""" + await self._inner.drain() + def publish(self) -> OriginProducer: """The publish-side origin: where local broadcasts are advertised to the remote. Either the origin wired before connect/accept, or one diff --git a/py/moq-rs/pyproject.toml b/py/moq-rs/pyproject.toml index d638ca09cca..f8e357189ed 100644 --- a/py/moq-rs/pyproject.toml +++ b/py/moq-rs/pyproject.toml @@ -14,7 +14,7 @@ name = "moq-rs" # isn't already there (no tag needed; the registry is the gate). # Starts at 0.3.0 to open a new line above the old lockstep 0.2.x releases that # bundled the bindings. -version = "0.5.1" +version = "0.5.2" description = "Media over QUIC: real-time pub/sub with built-in caching, fan-out, and prioritization, with a Pythonic API. Import as `moq`." readme = "README.md" license = "MIT OR Apache-2.0" diff --git a/py/moq-rs/tests/test_server.py b/py/moq-rs/tests/test_server.py index 3dd07bc8a91..01239497197 100644 --- a/py/moq-rs/tests/test_server.py +++ b/py/moq-rs/tests/test_server.py @@ -182,6 +182,28 @@ async def reject_loop() -> None: pass +async def test_session_drain_closes_an_idle_session(): + """With nothing left to deliver, drain() closes at once and closed() then returns.""" + async with moq.Server("127.0.0.1:0", tls_generate=["localhost"]) as server: + serve_task = asyncio.create_task(server.serve()) + try: + async with moq.Client( + f"https://{server.local_addr}", + tls_verify=False, + bind="127.0.0.1:0", + ) as client: + session = client.session + assert session is not None + await asyncio.wait_for(session.drain(), timeout=5.0) + await asyncio.wait_for(session.closed(), timeout=5.0) + finally: + serve_task.cancel() + try: + await serve_task + except asyncio.CancelledError: + pass + + async def test_client_websocket_fallback_options(): """The fallback knobs reach the native client, and QUIC alone still connects.""" async with moq.Server("127.0.0.1:0", tls_generate=["localhost"]) as server: diff --git a/rs/moq-ffi/src/server.rs b/rs/moq-ffi/src/server.rs index 401f5149f6f..5658518c722 100644 --- a/rs/moq-ffi/src/server.rs +++ b/rs/moq-ffi/src/server.rs @@ -199,6 +199,12 @@ impl MoqServer { } Ok(f(&mut state)) } + + /// Accept only these versions, for version-specific tests. + #[cfg(test)] + pub(crate) fn set_version(&self, version: Vec) -> Result<(), MoqError> { + self.configure_listen(|state| state.config.version = version) + } } #[uniffi::export] diff --git a/rs/moq-ffi/src/session.rs b/rs/moq-ffi/src/session.rs index 504a6f41ff4..1ded1193e16 100644 --- a/rs/moq-ffi/src/session.rs +++ b/rs/moq-ffi/src/session.rs @@ -386,6 +386,14 @@ impl MoqClient { } } +#[cfg(all(test, not(target_arch = "wasm32")))] +impl MoqClient { + /// Offer only these versions on the next dial, for version-specific tests. + pub(crate) fn set_version(&self, version: Vec) -> Result<(), MoqError> { + self.configure(|state| state.config.version = version) + } +} + #[cfg(target_arch = "wasm32")] #[uniffi::export] impl MoqClient { @@ -883,6 +891,24 @@ impl MoqSession { self.cancel(0); } + /// Drain finished tracks within one second, then close, returning any drain error. + /// + /// Finish or abort live tracks first; [`shutdown`](Self::shutdown) and + /// [`cancel`](Self::cancel) stay immediate. Explicit `moq-lite-07-wip` waits for + /// the peer to receive the tail. Older Lite versions, including the default + /// lite-06, wait only for transport ACKs. moq-transport (IETF) closes without waiting. + pub async fn drain(&self) -> Result<(), MoqError> { + let inner = self.inner.clone(); + crate::ffi::detached(async move { + match inner { + #[cfg(not(target_arch = "wasm32"))] + Inner::Connection(connection) => connection.close().await.map_err(map_closed_error), + Inner::Session(session) => session.close().await.map_err(MoqError::from), + } + }) + .await + } + /// The publish-side origin: where local broadcasts get advertised /// to the remote. Either the producer the caller wired via /// `set_publish` / `set_consume` before connect/accept, or one diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index eb25a59d134..8fee949c3c1 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -4860,3 +4860,135 @@ async fn server_cancel_during_listen_releases_the_port() { std::net::UdpSocket::bind(addr).expect("cancel must release the port before it returns"); drop(listen); } + +/// Real sockets exercise the FFI runtime and both accepted/client session handles. +/// Only lite-07 acknowledges the received tail; default lite-06 closes after transport ACKs. +async fn drain_pair() -> (Arc, Arc, Arc) { + let lite07: moq_net::Version = "moq-lite-07-wip".parse().unwrap(); + let server = MoqServer::new(); + server.set_bind("127.0.0.1:0".into()).unwrap(); + server.set_tls_generate(vec!["localhost".into()]).unwrap(); + server.set_version(vec![lite07]).unwrap(); + let addr = server.listen().await.unwrap(); + let accepting = server.clone(); + let accepted = tokio::spawn(async move { accepting.accept().await.unwrap().unwrap().accept().await.unwrap() }); + let client = MoqClient::new(); + client.set_tls_verify(false).unwrap(); + client.set_bind("127.0.0.1:0".into()).unwrap(); + client.set_reconnect(false).unwrap(); + client.set_version(vec![lite07]).unwrap(); + let connected = client.connect(format!("https://{addr}")).await.unwrap(); + (server, connected, accepted.await.unwrap()) +} + +/// TRACK_INFO holds demand before SUBSCRIBE; receiving a frame proves live delivery started. +async fn drain_ready(track: &MoqTrackProducer, reader: &MoqTrackConsumer) { + let group = track.append_group().unwrap(); + group + .write_frame(MoqFrame { + timestamp_us: 0, + payload: b"ready".to_vec(), + }) + .unwrap(); + group.finish().unwrap(); + let ready = tokio::time::timeout(TIMEOUT, reader.read_frame()) + .await + .expect("subscription ready") + .expect("priming read") + .expect("priming frame"); + assert_eq!(ready.payload, b"ready"); +} + +#[tokio::test] +async fn drain_delivers_the_finished_track() { + for client_publishes in [false, true] { + let (server, client, accepted) = tokio::time::timeout(TIMEOUT, drain_pair()).await.expect("pair"); + let (publisher, subscriber) = if client_publishes { + (&client, &accepted) + } else { + (&accepted, &client) + }; + let broadcast = create_announced(&publisher.publish(), "tail"); + let track = broadcast.publish_track("data".into(), None).unwrap(); + let remote = await_announced(&subscriber.consume(), "tail").await; + let reader = tokio::time::timeout(TIMEOUT, remote.subscribe_track("data".into(), None)) + .await + .expect("subscribe") + .unwrap(); + drain_ready(&track, &reader).await; + let receiving = tokio::spawn(async move { + let frame = reader.read_frame().await?; + let end = reader.read_frame().await?; + Ok::<_, MoqError>((frame, end)) + }); + let closing = publisher.clone(); + tokio::time::timeout( + TIMEOUT, + crate::ffi::detached(async move { + let group = track.append_group()?; + group.write_frame(MoqFrame { + timestamp_us: 0, + payload: b"last".to_vec(), + })?; + group.finish()?; + track.finish()?; + closing.drain().await?; + Ok::<(), MoqError>(()) + }), + ) + .await + .expect("drain") + .unwrap(); + let (frame, end) = tokio::time::timeout(TIMEOUT, receiving) + .await + .expect("read") + .unwrap() + .unwrap_or_else(|err| panic!("client_publishes={client_publishes}: tail/end: {err:?}")); + assert_eq!(frame.unwrap().payload, b"last"); + assert!(end.is_none()); + client.cancel(0); + accepted.cancel(0); + server.cancel(); + } +} + +#[tokio::test] +async fn drain_times_out_on_an_unfinished_track() { + for client_publishes in [false, true] { + let (server, client, accepted) = tokio::time::timeout(TIMEOUT, drain_pair()).await.expect("pair"); + let (publisher, subscriber) = if client_publishes { + (&client, &accepted) + } else { + (&accepted, &client) + }; + let broadcast = create_announced(&publisher.publish(), "live"); + let track = broadcast.publish_track("data".into(), None).unwrap(); + let remote = await_announced(&subscriber.consume(), "live").await; + let reader = tokio::time::timeout(TIMEOUT, remote.subscribe_track("data".into(), None)) + .await + .expect("subscribe") + .unwrap(); + drain_ready(&track, &reader).await; + let receiving = tokio::spawn(async move { reader.read_frame().await }); + let start = std::time::Instant::now(); + let err = tokio::time::timeout(TIMEOUT, publisher.drain()) + .await + .expect("drain") + .expect_err("unfinished track must time out"); + // The FFI runtime owns real sockets and cannot share a paused test clock. + // A lower bound still rejects an immediate bail without depending on scheduler latency. + assert!( + start.elapsed() >= Duration::from_secs(1), + "gave up draining after {:?}", + start.elapsed() + ); + assert!( + matches!(&err, MoqError::Protocol { details } if details.kind == crate::error::MoqProtocolKind::DeliveryTimeout), + "{err:?}" + ); + let _ = tokio::time::timeout(TIMEOUT, receiving).await.unwrap().unwrap(); + client.cancel(0); + accepted.cancel(0); + server.cancel(); + } +} diff --git a/rs/moq-tokio/src/lib.rs b/rs/moq-tokio/src/lib.rs index f520b865657..303091d4bc1 100644 --- a/rs/moq-tokio/src/lib.rs +++ b/rs/moq-tokio/src/lib.rs @@ -66,6 +66,19 @@ pub mod watch; #[cfg(feature = "websocket")] pub mod websocket; +/// Session settings for every qmux transport (WebSocket, `tcp://`, `unix://`). +/// +/// moq-lite holds a stream open per subscription, so a qmux session grants the same +/// stream count as QUIC rather than qmux's default of 100, past which a peer's opens +/// wait on credit forever. +#[cfg(any(feature = "websocket", feature = "tcp"))] +fn qmux_config() -> qmux::Config { + let mut config = qmux::Config::default(); + config.max_streams_bidi = quic::DEFAULT_MAX_STREAMS; + config.max_streams_uni = quic::DEFAULT_MAX_STREAMS; + config +} + // Enumerated rather than globbed, so the root surface is a deliberate list and a // new `pub` item in these modules doesn't silently join it. pub use client::Client; diff --git a/rs/moq-tokio/src/tcp.rs b/rs/moq-tokio/src/tcp.rs index b2753886331..95afb67c69b 100644 --- a/rs/moq-tokio/src/tcp.rs +++ b/rs/moq-tokio/src/tcp.rs @@ -164,6 +164,7 @@ async fn connect_addrs( async move { qmux::tcp::Config::new(WIRE_VERSION) .protocols(protocols.iter().map(String::as_str)) + .session_config(crate::qmux_config()) .connect(addr) .await .map_err(|err| Error::Connect(crate::error::message(err))) @@ -242,7 +243,9 @@ impl Listener { ) -> impl Future> + use<> { let (stream, addr) = self.accept_socket().await; tracing::debug!(%addr, "accepted TCP connection"); - let config = qmux::tcp::Config::new(WIRE_VERSION).protocols(self.protocols.iter().map(String::as_str)); + let config = qmux::tcp::Config::new(WIRE_VERSION) + .protocols(self.protocols.iter().map(String::as_str)) + .session_config(crate::qmux_config()); async move { let session = config .accept(stream) @@ -303,6 +306,39 @@ mod tests { accept.await.expect("accept task panicked"); } + /// moq-lite holds a stream open per subscription, so each end of a session must + /// let its peer hold far more than qmux's default of 100 open at once. + #[tokio::test] + async fn sessions_grant_a_thousand_open_streams() { + use futures::FutureExt as _; + + let listener = Listener::bind("127.0.0.1:0".parse().unwrap()) + .await + .expect("bind listener") + .with_protocols(["moq-test"]); + let addr = listener.local_addr().expect("local addr"); + let accept = tokio::spawn(async move { listener.accept().await.expect("listener gone").expect("accept") }); + let candidates = crate::resolve::Candidates::fixed([addr]); + let client = connect_addrs(candidates, &["moq-test"], Duration::ZERO) + .await + .expect("connect failed"); + let server = accept.await.expect("accept task panicked"); + + // Both handshakes are done, so each end knows its peer's grant, and an open + // with credit left completes without waiting. + for (end, session) in [("client", &client), ("server", &server)] { + let mut held = Vec::new(); + for opened in 0..1_000 { + let bi = session.open_bi().now_or_never(); + let uni = session.open_uni().now_or_never(); + let (Some(bi), Some(uni)) = (bi, uni) else { + panic!("{end} stalled on stream credit after opening {opened} stream pairs"); + }; + held.push((bi.expect("open bi"), uni.expect("open uni"))); + } + } + } + #[tokio::test] async fn connect_addrs_rejects_empty() { let candidates = crate::resolve::Candidates::fixed([]); diff --git a/rs/moq-tokio/src/unix.rs b/rs/moq-tokio/src/unix.rs index 6b857cb051c..1c10499e3a7 100644 --- a/rs/moq-tokio/src/unix.rs +++ b/rs/moq-tokio/src/unix.rs @@ -247,6 +247,7 @@ pub(crate) async fn connect(url: Url, protocols: &[&str]) -> Result impl Future> + use<> { let stream = self.accept_socket().await; - let config = qmux::uds::Config::new(WIRE_VERSION).protocols(self.protocols.iter().map(String::as_str)); + let config = qmux::uds::Config::new(WIRE_VERSION) + .protocols(self.protocols.iter().map(String::as_str)) + .session_config(crate::qmux_config()); async move { let cred = stream.peer_cred()?; let cred = PeerCred { diff --git a/rs/moq-tokio/src/websocket.rs b/rs/moq-tokio/src/websocket.rs index e48d13c9619..d57d49d4644 100644 --- a/rs/moq-tokio/src/websocket.rs +++ b/rs/moq-tokio/src/websocket.rs @@ -352,6 +352,7 @@ pub(crate) async fn connect( .with_protocols(alpns.iter().map(|&a| (a, qmux_versions_for(a)))) .with_connector(connector) .with_keep_alive(qmux::ws::KeepAlive::default()) // 5s ping / 30s deadline; TCP backs off retransmits too far for QUIC's 10s + .with_session_config(crate::qmux_config()) .connect(url.as_str()) .await .map_err(Error::connect)? @@ -410,7 +411,9 @@ async fn connect_tls_override( .headers() .get(http::header::SEC_WEBSOCKET_PROTOCOL) .and_then(|value| value.to_str().ok()); - let upgraded = qmux::ws::Upgraded::new(websocket).with_keep_alive(qmux::ws::KeepAlive::default()); + let upgraded = qmux::ws::Upgraded::new(websocket) + .with_keep_alive(qmux::ws::KeepAlive::default()) + .with_session_config(crate::qmux_config()); Ok(match negotiated { Some(protocol) => upgraded.with_alpn(protocol).connect(), None => upgraded.connect(), @@ -597,7 +600,9 @@ impl Listener { .unwrap() .take() .expect("successful upgrade selected a protocol"); - let upgraded = qmux::ws::Upgraded::new(websocket).with_keep_alive(qmux::ws::KeepAlive::default()); + let upgraded = qmux::ws::Upgraded::new(websocket) + .with_keep_alive(qmux::ws::KeepAlive::default()) + .with_session_config(crate::qmux_config()); let session = match &protocol { Some(protocol) => upgraded.with_alpn(protocol).accept(), None => upgraded.accept(), diff --git a/swift/README.md b/swift/README.md index 3317296c37a..32cf1c96559 100644 --- a/swift/README.md +++ b/swift/README.md @@ -57,7 +57,7 @@ let broadcast = try session.publish.createBroadcast(path: "my-stream") try broadcast.announce() // unannounced broadcasts are invisible ``` -Cancelling the surrounding Swift `Task` propagates through to the underlying `cancel()` calls on each consumer. `session.shutdown()` is an alias for `cancel(code: 0)` (code 0 means "no error"). +Cancelling the surrounding Swift `Task` propagates through to the underlying `cancel()` calls on each consumer. `session.shutdown()` is an alias for `cancel(code: 0)` (code 0 means "no error"). `try await session.drain()` instead drains finished tracks within one second before closing, and throws if the drain fails. A note on enum casing: `MoqError` keeps Rust's PascalCase variants, each carrying `message: String` (e.g. `MoqError.Closed(message: "...")`); plain enums round-trip to lowerCamelCase (`AudioSampleFormat.s16`). Audio codecs are objects with constructors (`AudioCodec.opus()`). diff --git a/swift/Sources/Moq/Client.swift b/swift/Sources/Moq/Client.swift index f77fe17729b..c7c0d5a0e29 100644 --- a/swift/Sources/Moq/Client.swift +++ b/swift/Sources/Moq/Client.swift @@ -173,6 +173,12 @@ public final class Session: Sendable { ffi.shutdown() } + /// Drain finished tracks within one second, then close, throwing if the drain fails. + /// Finish or abort live tracks first; `shutdown()` and `cancel(code:)` stay immediate. + public func drain() async throws { + try await ffi.drain() + } + /// Snapshot the current connection statistics (RTT, bandwidth estimates, /// byte/packet counters). Cheap to call; intended for periodic polling. /// Individual fields are `nil` when the transport backend doesn't report them. diff --git a/swift/VERSION b/swift/VERSION index 4b9fcbec101..cb0c939a936 100644 --- a/swift/VERSION +++ b/swift/VERSION @@ -1 +1 @@ -0.5.1 +0.5.2 diff --git a/uv.lock b/uv.lock index 5cd21997f81..555d08b0549 100644 --- a/uv.lock +++ b/uv.lock @@ -509,7 +509,7 @@ source = { editable = "py/moq-ffi" } [[package]] name = "moq-rs" -version = "0.5.1" +version = "0.5.2" source = { editable = "py/moq-rs" } dependencies = [ { name = "moq-ffi" },