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 Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions dart/moq/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
11 changes: 11 additions & 0 deletions dart/moq/lib/src/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> drain() async {
try {
await session.drain();
} finally {
_client.cancel();
}
}
}
2 changes: 1 addition & 1 deletion dart/moq/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
23 changes: 23 additions & 0 deletions dart/moq_ffi/lib/src/moq.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7946,6 +7946,7 @@ abstract class MoqSessionInterface {
void cancel({required int code});
Future<void> closed();
MoqOriginConsumer consume();
Future<void> drain();
int epoch();
MoqOriginProducer publish();
void shutdown();
Expand Down Expand Up @@ -8019,6 +8020,17 @@ class MoqSession implements MoqSessionInterface {
);
}

Future<void> 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(
Expand Down Expand Up @@ -11502,6 +11514,11 @@ external Pointer<Void> uniffi_moq_ffi_fn_method_moqsession_consume(
Pointer<RustCallStatus> uniffiStatus,
);

@Native<Pointer<Void> Function(Pointer<Void>)>(assetId: _uniffiAssetId)
external Pointer<Void> uniffi_moq_ffi_fn_method_moqsession_drain(
Pointer<Void> ptr,
);

@Native<Uint64 Function(Pointer<Void>, Pointer<RustCallStatus>)>(
assetId: _uniffiAssetId,
)
Expand Down Expand Up @@ -12430,6 +12447,9 @@ external int uniffi_moq_ffi_checksum_method_moqsession_closed();
@Native<Uint16 Function()>(assetId: _uniffiAssetId)
external int uniffi_moq_ffi_checksum_method_moqsession_consume();

@Native<Uint16 Function()>(assetId: _uniffiAssetId)
external int uniffi_moq_ffi_checksum_method_moqsession_drain();

@Native<Uint16 Function()>(assetId: _uniffiAssetId)
external int uniffi_moq_ffi_checksum_method_moqsession_epoch();

Expand Down Expand Up @@ -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");
}
Expand Down
2 changes: 2 additions & 0 deletions doc/lib/dart/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions doc/lib/go/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions doc/lib/kt/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions doc/lib/py/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions doc/lib/swift/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions go/wrapper/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion kt/gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
1 change: 1 addition & 0 deletions py/moq-rs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions py/moq-rs/moq/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion py/moq-rs/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
22 changes: 22 additions & 0 deletions py/moq-rs/tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 6 additions & 0 deletions rs/moq-ffi/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<moq_net::Version>) -> Result<(), MoqError> {
self.configure_listen(|state| state.config.version = version)
}
}

#[uniffi::export]
Expand Down
26 changes: 26 additions & 0 deletions rs/moq-ffi/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<moq_net::Version>) -> Result<(), MoqError> {
self.configure(|state| state.config.version = version)
}
}

#[cfg(target_arch = "wasm32")]
#[uniffi::export]
impl MoqClient {
Expand Down Expand Up @@ -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> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Mirror the new draining operation in the C API

The applicable rs/moq-ffi/AGENTS.md requires every surface change to be mirrored in rs/libmoq in the same PR, but this adds draining only to UniFFI and its wrappers. Searching rs/libmoq, cpp, and doc/lib/c finds no corresponding session drain operation: rs/libmoq/src/session.rs still handles close by ending the task without awaiting Connection::close() or Session::close(). Consequently, C and OBS publishers have no way to obtain the finished-track delivery guarantee introduced here. Add the corresponding C operation and documentation rather than leaving that required surface synchronization to a separate design.

AGENTS.md reference: rs/moq-ffi/AGENTS.md:L5-L9

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining for this PR. On release, libmoq is not a wrapper over moq-ffi's MoqSession. It is a separate C API with its own task-and-callback lifecycle: moq_session_close drops the task and reports a terminal 0. A C drain would mean designing new ABI. For example, moq_session_drain would deliver the drain result through the terminal status callback, which today guarantees 0 after a close. OBS would also have to adopt it. The quest scopes this backport to the moq-ffi bindings (wheel, Swift, Kotlin, plus the other hand-written wrappers) and moq-tokio, and lets the PR say why a binding has none, which the description does. I'll suggest a C drain as a follow-up quest.

(Written by Claude Opus 5.5)

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
Expand Down
Loading
Loading