diff --git a/cpp/moq/MIGRATE.md b/cpp/moq/MIGRATE.md index 5fccce97c4c..50c37346b2f 100644 --- a/cpp/moq/MIGRATE.md +++ b/cpp/moq/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Connection state + +`Client::connect` returns a connecting native session. Replace `status()`, `connects()`, and both `failure()` polls with `state()` and `state_changed(state.revision)`. `ConnectionState` carries `phase`, `connects`, `failure`, and `version`; `ConnectionPhase` replaces `ConnectionStatus`. + ### Exact encoder rates and publication options Raw video input framerates are exact numerator/denominator records, not integers. diff --git a/cpp/obs/MIGRATE.md b/cpp/obs/MIGRATE.md index 398682fc872..f69a6a0ad13 100644 --- a/cpp/obs/MIGRATE.md +++ b/cpp/obs/MIGRATE.md @@ -4,6 +4,8 @@ How to update your OBS setup for each breaking change, newest first. ## Unreleased +Connection state and first-dial failures now arrive through one lifecycle watcher. UI reads no longer poll the Client or Session for failure separately. + ### Key logging is opt-in (#5907) `SSLKEYLOGFILE` alone no longer writes TLS session secrets. diff --git a/cpp/obs/src/moq-output.cpp b/cpp/obs/src/moq-output.cpp index b8a780f4677..9b140785e60 100644 --- a/cpp/obs/src/moq-output.cpp +++ b/cpp/obs/src/moq-output.cpp @@ -16,23 +16,6 @@ namespace { -bool LooksGenericOffline(const std::string &reason) -{ - if (reason.empty() || reason == "offline") - return true; - // Case-insensitive contains for "offline" only as a whole-ish token. - for (size_t i = 0; i + 6 < reason.size() + 1; i++) { - char buf[8] = {}; - for (int j = 0; j < 7 && i + j < reason.size(); j++) { - char c = reason[i + j]; - buf[j] = (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; - } - if (std::strncmp(buf, "offline", 7) == 0) - return true; - } - return false; -} - // Dial URL scheme only. https races WebTransport vs WebSocket, and the session // does not report which won, so do not invent a transport name here. std::string DialSchemeLabel(const std::string &url) @@ -240,7 +223,6 @@ bool MoQOutput::Start() std::lock_guard lock(mutex); url = server; epoch = *route.epoch; - dialing = client; } { std::lock_guard lock(media_mutex); @@ -268,19 +250,7 @@ void MoQOutput::OnConnect(const std::shared_ptr ¤t, moq::expected return; } - auto elapsed = std::chrono::steady_clock::now() - current->started; - auto ms = static_cast(std::chrono::duration_cast(elapsed).count()); - const int connects = static_cast((*result)->connects()); - - // OBS and older dock paths treat connect_time_ms == 0 as "never connected". - // Clamp sub-millisecond connects to 1 so that sentinel stays honest. Set before - // the session reads as live, so nothing sees a live session that never connected. - connect_time_ms = ms > 0 ? ms : 1; - current->session = *result; - current->connected = true; - current->live = true; - // Before the session reads as live, so the first frame after can reserve. { std::lock_guard lock(media_mutex); bandwidth = current->session->bandwidth(); @@ -288,65 +258,53 @@ void MoQOutput::OnConnect(const std::shared_ptr ¤t, moq::expected { std::lock_guard lock(mutex); session = current->session; - dialing.reset(); recv_bandwidth = session->recv_bandwidth(); - connected = true; - live = true; - last_failure_code = MoQError::None; - last_failure_reason.clear(); } - - LOG_INFO("MoQ session connected (%d ms, connect %d): %s", ms, connects, MoQRedactUrl(current->url).c_str()); - - WatchStatus(current); + OnState(current, current->session->state()); } -void MoQOutput::WatchStatus(const std::shared_ptr ¤t) +void MoQOutput::WatchState(const std::shared_ptr ¤t) { - // Replacing `pending` from inside its own continuation is fine: that call has - // already completed, so dropping it cancels nothing. - current->pending = current->session->status().then( - worker.Executor(), Current>( - current, [this](const std::shared_ptr ¤t, auto result) { - OnStatus(current, std::move(result)); - })); + current->pending = current->session->state_changed(current->revision) + .then(worker.Executor(), + Current>( + current, [this](const std::shared_ptr ¤t, auto result) { + OnState(current, std::move(result)); + })); } -void MoQOutput::OnStatus(const std::shared_ptr ¤t, moq::expected result) +void MoQOutput::OnState(const std::shared_ptr ¤t, moq::expected result) { - // The status stream ends in an error once reconnecting gives up for good. if (!result) { Fail(current, result.error()); return; } - - switch (*result) { - case moq::ConnectionStatus::kConnected: { - const int connects = static_cast(current->session->connects()); - current->live = true; - { - std::lock_guard lock(mutex); - live = true; + const auto &state = *result; + current->revision = state.revision; + current->live = state.phase == moq::ConnectionPhase::kConnected || + state.phase == moq::ConnectionPhase::kMigrating; + if (state.connects > 0 && !current->connected) { + auto elapsed = std::chrono::steady_clock::now() - current->started; + auto ms = std::chrono::duration_cast(elapsed).count(); + connect_time_ms = ms > 0 ? static_cast(ms) : 1; + current->connected = true; + } + { + std::lock_guard lock(mutex); + connected = current->connected; + live = current->live; + if (state.failure) { + last_failure_code = FailureCode(*state.failure); + last_failure_reason = state.failure->to_string(); + } else if (current->live) { last_failure_code = MoQError::None; last_failure_reason.clear(); } - LOG_INFO("MoQ session reconnected (connect %d): %s", connects, MoQRedactUrl(current->url).c_str()); - break; - } - case moq::ConnectionStatus::kDisconnected: { - current->live = false; - std::lock_guard lock(mutex); - live = false; - LOG_WARNING("MoQ session dropped, reconnecting: %s", MoQRedactUrl(current->url).c_str()); - break; - } - case moq::ConnectionStatus::kMigrating: - // The old session keeps serving while the replacement dials. - LOG_INFO("MoQ session migrating: %s", MoQRedactUrl(current->url).c_str()); - break; } - - WatchStatus(current); + LOG_INFO("MoQ connection state changed (connect %llu): %s", (unsigned long long)state.connects, + MoQRedactUrl(current->url).c_str()); + // A second wait at the terminal revision returns its close reason through Fail. + WatchState(current); } void MoQOutput::Fail(const std::shared_ptr ¤t, const moq::Error &error) @@ -361,7 +319,6 @@ void MoQOutput::Fail(const std::shared_ptr ¤t, const moq::Error & std::lock_guard lock(mutex); recv_bandwidth.reset(); session.reset(); - dialing.reset(); connected = false; live = false; last_failure_code = FailureCode(error); @@ -404,7 +361,6 @@ void MoQOutput::Reset() std::lock_guard lock(mutex); recv_bandwidth.reset(); session.reset(); - dialing.reset(); connected = false; live = false; url.clear(); @@ -489,7 +445,6 @@ bool MoQOutput::TryGetConnectionStats(ConnectionStats *out) } if (!current_live) { - RecordReconnectFailure(current); return false; } @@ -518,46 +473,6 @@ bool MoQOutput::TryGetConnectionStats(ConnectionStats *out) return CommitConnectionStats(current, std::move(snapshot), out); } -void MoQOutput::RecordReconnectFailure(const std::shared_ptr ¤t) -{ - // Read outside the lock: it calls into moq-ffi. - const auto failure = current->failure(); - - std::lock_guard lock(mutex); - // A Stop(), restart, or reconnect while failure() ran made this one stale. - if (session != current || live) - return; - if (failure) { - last_failure_code = FailureCode(*failure); - last_failure_reason = failure->to_string(); - } else if (last_failure_reason.empty() || LooksGenericOffline(last_failure_reason)) { - // Nothing named yet. Keep a more specific prior failure over a generic blip. - last_failure_code = MoQError::Offline; - last_failure_reason = "offline"; - } -} - -void MoQOutput::RecordDialFailure() -{ - std::shared_ptr current; - { - std::lock_guard lock(mutex); - if (!dialing) - return; - current = dialing; - } - - // Read outside the lock: it calls into moq-ffi. - const auto failure = current->failure(); - - std::lock_guard lock(mutex); - // A Stop(), restart, or connect while failure() ran made this one stale. - if (dialing != current || !failure) - return; - last_failure_code = FailureCode(*failure); - last_failure_reason = failure->to_string(); -} - bool MoQOutput::CommitConnectionStats(const std::shared_ptr ¤t, ConnectionStats snapshot, ConnectionStats *out) { @@ -577,9 +492,8 @@ int MoQOutput::GetReconnectCount() std::lock_guard lock(mutex); current = session; } - // Read live rather than tracked from status(), which coalesces a drop that - // reconnects before it is asked again. - const uint64_t connects = current ? current->connects() : 0; + // The cumulative count survives a reconnect that finishes between UI reads. + const uint64_t connects = current ? current->state().connects : 0; return connects > 1 ? static_cast(connects - 1) : 0; } @@ -591,7 +505,6 @@ bool MoQOutput::IsLiveSession() void MoQOutput::CopyLastFailure(int *code, std::string *reason) { - RecordDialFailure(); std::lock_guard lock(mutex); if (code) diff --git a/cpp/obs/src/moq-output.h b/cpp/obs/src/moq-output.h index 230dcbb5d1e..2f6da43221e 100644 --- a/cpp/obs/src/moq-output.h +++ b/cpp/obs/src/moq-output.h @@ -53,7 +53,7 @@ class MoQOutput { }; bool TryGetConnectionStats(ConnectionStats *out); - // Successful (re)connects after the first for this Start(); 0 until connects() >= 2. + // Successful (re)connects after the first for this Start(); 0 until state().connects >= 2. int GetReconnectCount(); // True while the current Start() attempt has an open MoQ session. @@ -88,10 +88,6 @@ class MoQOutput { friend struct MoQOutputStatsTest; bool CommitConnectionStats(const std::shared_ptr ¤t, ConnectionStats snapshot, ConnectionStats *out); - // Between reconnects: name why the session is down, for CopyLastFailure. - void RecordReconnectFailure(const std::shared_ptr ¤t); - // Before the first connect: name why the dial is retrying, for CopyLastFailure. - void RecordDialFailure(); // One Start()'s connection: the client dialing, the session once it connects, // and the pending call whose continuation reports on it. Replaced wholesale by @@ -104,6 +100,7 @@ class MoQOutput { std::chrono::steady_clock::time_point started; // Whether this attempt ever reached the server, which picks between telling // OBS the connection failed and telling it the stream dropped. + uint64_t revision = 0; bool connected = false; // False while the session is between reconnects. bool live = false; @@ -115,8 +112,8 @@ class MoQOutput { }; void OnConnect(const std::shared_ptr &attempt, moq::expected> result); - void OnStatus(const std::shared_ptr &attempt, moq::expected result); - void WatchStatus(const std::shared_ptr &attempt); + void OnState(const std::shared_ptr &attempt, moq::expected result); + void WatchState(const std::shared_ptr &attempt); void Fail(const std::shared_ptr &attempt, const moq::Error &error); // Runs `callback` on the worker if `attempt` is still the current one once it @@ -176,8 +173,6 @@ class MoQOutput { // Guards the group below, which the dock reads from the UI thread. std::mutex mutex; std::shared_ptr session; - // The client while its first connect is pending, so the dock can ask why it retries. - std::shared_ptr dialing; std::shared_ptr recv_bandwidth; bool connected = false; bool live = false; diff --git a/cpp/obs/src/moq-source.cpp b/cpp/obs/src/moq-source.cpp index b0ecaa6e723..dd77081d51b 100644 --- a/cpp/obs/src/moq-source.cpp +++ b/cpp/obs/src/moq-source.cpp @@ -133,6 +133,7 @@ struct Track { // settings change, a terminal failure, or destroy drops it whole, which cancels // every pending call it holds. struct Connection { + uint64_t revision = 0; std::string url; std::string broadcast; @@ -145,7 +146,7 @@ struct Connection { std::shared_ptr consumer; std::shared_ptr catalog; - // The connect, then the session's status transitions. + // The connect, then the session's lifecycle revisions. std::optional session_call; // Waiting for the next publisher instance. std::optional available_call; @@ -201,9 +202,9 @@ static void moq_source_on_broadcast(struct moq_source *ctx, const std::shared_pt moq::expected> result); static void moq_source_on_catalogs(struct moq_source *ctx, const std::shared_ptr &conn, moq::expected> result); -static void moq_source_watch_status(struct moq_source *ctx, const std::shared_ptr &conn); -static void moq_source_on_status(struct moq_source *ctx, const std::shared_ptr &conn, - moq::expected result); +static void moq_source_watch_state(struct moq_source *ctx, const std::shared_ptr &conn); +static void moq_source_on_state(struct moq_source *ctx, const std::shared_ptr &conn, + moq::expected result); static void moq_source_on_catalog(struct moq_source *ctx, const std::shared_ptr &conn, moq::expected> result); static void moq_source_next_catalog(struct moq_source *ctx, const std::shared_ptr &conn); @@ -402,8 +403,9 @@ static void moq_source_on_connect(struct moq_source *ctx, const std::shared_ptr< } conn->session = *result; - LOG_INFO("MoQ session connected (connect %llu)", (unsigned long long)conn->session->connects()); - moq_source_watch_status(ctx, conn); + moq_source_on_state(ctx, conn, conn->session->state()); + if (ctx->connection != conn) + return; // Wait for the broadcast to be announced. Announcements arrive over the session // after it connects, so resolving against only what is announced *now* would race @@ -475,15 +477,16 @@ static void moq_source_on_catalogs(struct moq_source *ctx, const std::shared_ptr } // Follows the session's connect and reconnect transitions until it gives up. -static void moq_source_watch_status(struct moq_source *ctx, const std::shared_ptr &conn) +static void moq_source_watch_state(struct moq_source *ctx, const std::shared_ptr &conn) { - conn->session_call = conn->session->status().then( - ctx->worker.Executor(), - moq_source_current>(ctx, conn, moq_source_on_status)); + conn->session_call = + conn->session->state_changed(conn->revision) + .then(ctx->worker.Executor(), + moq_source_current>(ctx, conn, moq_source_on_state)); } -static void moq_source_on_status(struct moq_source *ctx, const std::shared_ptr &conn, - moq::expected result) +static void moq_source_on_state(struct moq_source *ctx, const std::shared_ptr &conn, + moq::expected result) { if (!result) { // Reconnecting gave up (or the relay refused us). Tear down every @@ -493,19 +496,17 @@ static void moq_source_on_status(struct moq_source *ctx, const std::shared_ptrsession->connects()); - break; - case moq::ConnectionStatus::kDisconnected: - LOG_WARNING("MoQ session dropped, reconnecting"); - break; - case moq::ConnectionStatus::kMigrating: - LOG_INFO("MoQ session migrating"); - break; + conn->revision = result->revision; + if (result->failure) + LOG_WARNING("MoQ connection attempt failed: %s", result->failure->to_string().c_str()); + if (result->phase == moq::ConnectionPhase::kClosed) { + moq_source_fail_locked(ctx); + return; } - moq_source_watch_status(ctx, conn); + if (result->phase == moq::ConnectionPhase::kConnected) + LOG_INFO("MoQ session connected (connect %llu)", (unsigned long long)result->connects); + + moq_source_watch_state(ctx, conn); } static void moq_source_next_catalog(struct moq_source *ctx, const std::shared_ptr &conn) diff --git a/cpp/obs/test/moq-output-test.cpp b/cpp/obs/test/moq-output-test.cpp index 99f7f66ca82..6634e4acbff 100644 --- a/cpp/obs/test/moq-output-test.cpp +++ b/cpp/obs/test/moq-output-test.cpp @@ -402,6 +402,23 @@ struct MoQOutputStatsTest { std::lock_guard lock(output.mutex); output.live = false; } + // A fast first connect and drop can coalesce before the UI observes Connected. + static bool ObserveCoalescedFirstConnect(MoQOutput &output) + { + std::lock_guard signal_lock(output.signal_mutex); + auto current = output.attempt; + if (!current || !current->session) + return false; + current->pending.reset(); + current->connected = false; + output.connect_time_ms = 0; + auto state = current->session->state(); + state.phase = moq::ConnectionPhase::kDisconnected; + state.version.reset(); + output.OnState(current, std::move(state)); + return current->connected && !current->live && output.GetConnectTime() > 0; + } + // Whether every audio and video track holds a reservation. static bool Reserved(MoQOutput &output) { @@ -459,6 +476,17 @@ int main() } printf("each start announces a fresh epoch, reconnect preserves it: ok\n"); + { + TestRelay relay; + reset(relay.Url()); + MoQOutput output(nullptr, OUTPUT); + CHECK(output.Start()); + CHECK(WaitFor([&] { return output.IsLiveSession(); })); + CHECK(MoQOutputStatsTest::ObserveCoalescedFirstConnect(output)); + output.Stop(); + } + printf("a coalesced first connection is remembered while offline: ok\n"); + for (int retirement = 0; retirement < 3; ++retirement) { TestRelay relay; reset(relay.Url()); diff --git a/dart/moq/MIGRATE.md b/dart/moq/MIGRATE.md index ce2c4bab63c..fcae653ce62 100644 --- a/dart/moq/MIGRATE.md +++ b/dart/moq/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Connection state + +`Moq.connect` returns a connecting native session. Replace status, connect-count, and failure polls with `session.state()` and `session.stateChanged(after: state.revision)`. `ConnectionState` carries `phase`, `connects`, `failure`, and `version`; `ConnectionPhase` replaces `ConnectionStatus`. + ### Exact encoder rates and publication options Raw video input framerates are exact numerator/denominator records, not integers. diff --git a/dart/moq/README.md b/dart/moq/README.md index 67e66d10332..e812a8905ca 100644 --- a/dart/moq/README.md +++ b/dart/moq/README.md @@ -36,7 +36,7 @@ final broadcast = server.createBroadcast('live'); broadcast.announce(route: AnnounceRoute()); // unannounced broadcasts are invisible await for (final request in server.requests()) { final session = await request.accept(); - print(session.connects()); + print(session.state().connects); } ``` diff --git a/dart/moq/lib/src/aliases.dart b/dart/moq/lib/src/aliases.dart index be0aecd9f61..a332da8af59 100644 --- a/dart/moq/lib/src/aliases.dart +++ b/dart/moq/lib/src/aliases.dart @@ -160,8 +160,11 @@ typedef AuthToken = MoqAuthToken; /// What the peer lets this side do: publish and subscribe patterns, and an expiry. typedef Grant = MoqGrant; -/// A connection lifecycle transition reported by [Session.status]. -typedef ConnectionStatus = MoqConnectionStatus; +/// A connection lifecycle transition reported by [Session.state]. +typedef ConnectionPhase = MoqConnectionPhase; + +/// One coherent connection lifecycle snapshot. +typedef ConnectionState = MoqConnectionState; /// Retry pacing for the automatic reconnect: initial delay, multiplier, ceiling, and give-up window. typedef Backoff = MoqBackoff; diff --git a/dart/moq/lib/src/client.dart b/dart/moq/lib/src/client.dart index 5ce62677d88..dd15f1e463e 100644 --- a/dart/moq/lib/src/client.dart +++ b/dart/moq/lib/src/client.dart @@ -191,11 +191,11 @@ List versions() => moqVersions(); /// Whether this build can write qlog traces for [ConnectOptions.qlog]. bool qlogSupported() => moqQlogSupported(); -/// A connected MoQ session with publishing and subscription conveniences. +/// A MoQ session with publishing and subscription conveniences. final class Moq { final Client _client; - /// The established raw MoQ session. + /// The connecting or connected raw MoQ session. final Session session; Moq._(this.session, this._client); @@ -244,10 +244,6 @@ final class Moq { Future requestBroadcast(String path) => session.consume().requestBroadcast(path: path); - /// How many times this session has connected: 1 for the connect that built it, one more - /// on each reconnect. A server-accepted session stays at 1. - int get connects => session.connects(); - /// The session's bandwidth allocator. /// /// Every call returns a handle to the same registry. [Bandwidth.reserve] diff --git a/dart/moq_ffi/MIGRATE.md b/dart/moq_ffi/MIGRATE.md index 1bf2de9d5b7..3d827bd5232 100644 --- a/dart/moq_ffi/MIGRATE.md +++ b/dart/moq_ffi/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Connection state + +Generated connection APIs now expose `MoqConnectionState` and `MoqConnectionPhase`, with `state()` and revision-based `state_changed(after)` instead of status, connect-count, and failure polls. Connect returns before its first dial completes. Regenerate bindings from the matching Rust metadata. + ### Exact encoder rates and publication options Encoder configuration is breaking: `MoqVideoEncoderInput.framerate` is now a diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index ee8363d663e..2ed3c6cf6ce 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -3622,6 +3622,113 @@ class FfiConverterMoqClientTls { } } +class MoqConnectionState { + final int revision; + final MoqConnectionPhase phase; + final int connects; + final MoqException? failure; + final String? version; + MoqConnectionState({ + required this.revision, + required this.phase, + required this.connects, + this.failure, + this.version, + }); +} + +class FfiConverterMoqConnectionState { + static MoqConnectionState lift(RustBuffer buf) { + return FfiConverterMoqConnectionState.read(buf.asUint8List()).value; + } + + static LiftRetVal read(Uint8List buf) { + int new_offset = buf.offsetInBytes; + final revision_lifted = FfiConverterUInt64.read( + Uint8List.view(buf.buffer, new_offset), + ); + final revision = revision_lifted.value; + new_offset += revision_lifted.bytesRead; + final phase_lifted = FfiConverterMoqConnectionPhase.read( + Uint8List.view(buf.buffer, new_offset), + ); + final phase = phase_lifted.value; + new_offset += phase_lifted.bytesRead; + final connects_lifted = FfiConverterUInt64.read( + Uint8List.view(buf.buffer, new_offset), + ); + final connects = connects_lifted.value; + new_offset += connects_lifted.bytesRead; + final failure_lifted = FfiConverterOptionalMoqException.read( + Uint8List.view(buf.buffer, new_offset), + ); + final failure = failure_lifted.value; + new_offset += failure_lifted.bytesRead; + final version_lifted = FfiConverterOptionalString.read( + Uint8List.view(buf.buffer, new_offset), + ); + final version = version_lifted.value; + new_offset += version_lifted.bytesRead; + return LiftRetVal( + MoqConnectionState( + revision: revision, + phase: phase, + connects: connects, + failure: failure, + version: version, + ), + new_offset - buf.offsetInBytes, + ); + } + + static RustBuffer lower(MoqConnectionState value) { + final total_length = + FfiConverterUInt64.allocationSize(value.revision) + + FfiConverterMoqConnectionPhase.allocationSize(value.phase) + + FfiConverterUInt64.allocationSize(value.connects) + + FfiConverterOptionalMoqException.allocationSize(value.failure) + + FfiConverterOptionalString.allocationSize(value.version) + + 0; + final buf = Uint8List(total_length); + write(value, buf); + return toRustBuffer(buf); + } + + static int write(MoqConnectionState value, Uint8List buf) { + int new_offset = buf.offsetInBytes; + new_offset += FfiConverterUInt64.write( + value.revision, + Uint8List.view(buf.buffer, new_offset), + ); + new_offset += FfiConverterMoqConnectionPhase.write( + value.phase, + Uint8List.view(buf.buffer, new_offset), + ); + new_offset += FfiConverterUInt64.write( + value.connects, + Uint8List.view(buf.buffer, new_offset), + ); + new_offset += FfiConverterOptionalMoqException.write( + value.failure, + Uint8List.view(buf.buffer, new_offset), + ); + new_offset += FfiConverterOptionalString.write( + value.version, + Uint8List.view(buf.buffer, new_offset), + ); + return new_offset - buf.offsetInBytes; + } + + static int allocationSize(MoqConnectionState value) { + return FfiConverterUInt64.allocationSize(value.revision) + + FfiConverterMoqConnectionPhase.allocationSize(value.phase) + + FfiConverterUInt64.allocationSize(value.connects) + + FfiConverterOptionalMoqException.allocationSize(value.failure) + + FfiConverterOptionalString.allocationSize(value.version) + + 0; + } +} + class MoqConnectionStats { final int? rttUs; final int? estimatedSendRateBps; @@ -7241,18 +7348,28 @@ class FfiConverterMoqCongestionControl { } } -enum MoqConnectionStatus { connected, disconnected, migrating } +enum MoqConnectionPhase { + connecting, + connected, + disconnected, + migrating, + closed, +} -class FfiConverterMoqConnectionStatus { - static LiftRetVal read(Uint8List buf) { +class FfiConverterMoqConnectionPhase { + static LiftRetVal read(Uint8List buf) { final index = buf.buffer.asByteData(buf.offsetInBytes).getInt32(0); switch (index) { case 1: - return LiftRetVal(MoqConnectionStatus.connected, 4); + return LiftRetVal(MoqConnectionPhase.connecting, 4); case 2: - return LiftRetVal(MoqConnectionStatus.disconnected, 4); + return LiftRetVal(MoqConnectionPhase.connected, 4); case 3: - return LiftRetVal(MoqConnectionStatus.migrating, 4); + return LiftRetVal(MoqConnectionPhase.disconnected, 4); + case 4: + return LiftRetVal(MoqConnectionPhase.migrating, 4); + case 5: + return LiftRetVal(MoqConnectionPhase.closed, 4); default: throw UniffiInternalError( UniffiInternalError.unexpectedEnumCase, @@ -7261,19 +7378,19 @@ class FfiConverterMoqConnectionStatus { } } - static MoqConnectionStatus lift(RustBuffer buffer) { - return FfiConverterMoqConnectionStatus.read(buffer.asUint8List()).value; + static MoqConnectionPhase lift(RustBuffer buffer) { + return FfiConverterMoqConnectionPhase.read(buffer.asUint8List()).value; } - static RustBuffer lower(MoqConnectionStatus input) { + static RustBuffer lower(MoqConnectionPhase input) { return toRustBuffer(createUint8ListFromInt(input.index + 1)); } - static int allocationSize(MoqConnectionStatus _value) { + static int allocationSize(MoqConnectionPhase _value) { return 4; } - static int write(MoqConnectionStatus value, Uint8List buf) { + static int write(MoqConnectionPhase value, Uint8List buf) { buf.buffer.asByteData(buf.offsetInBytes).setInt32(0, value.index + 1); return 4; } @@ -12607,7 +12724,6 @@ class FfiConverterMoqServer { abstract class MoqClientInterface { void cancel(); UniffiRustFuture connect({required String url}); - MoqException? failure(); } final _MoqClientFinalizer = Finalizer>((ptr) { @@ -12671,17 +12787,6 @@ class MoqClient implements MoqClientInterface { moqExceptionErrorHandler, ); } - - MoqException? failure() { - return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqclient_failure( - uniffiClonePointer(), - status, - ), - FfiConverterOptionalMoqException.lift, - null, - ); - } } class FfiConverterMoqClient { @@ -12715,14 +12820,13 @@ abstract class MoqSessionInterface { MoqBandwidth bandwidth(); void cancel({required int code}); UniffiRustFuture closed(); - int connects(); MoqOriginConsumer consume(); - MoqException? failure(); MoqOriginProducer publish(); MoqBandwidthConsumer? recvBandwidth(); UniffiRustFuture shutdown(); + MoqConnectionState state(); + UniffiRustFuture stateChanged({required int after}); MoqConnectionStats stats(); - UniffiRustFuture status(); } final _MoqSessionFinalizer = Finalizer>((ptr) { @@ -12800,17 +12904,6 @@ class MoqSession implements MoqSessionInterface { ); } - int connects() { - return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqsession_connects( - uniffiClonePointer(), - status, - ), - FfiConverterUInt64.lift, - null, - ); - } - MoqOriginConsumer consume() { return rustCallWithLifter( (status) => uniffi_moq_ffi_fn_method_moqsession_consume( @@ -12822,17 +12915,6 @@ class MoqSession implements MoqSessionInterface { ); } - MoqException? failure() { - return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqsession_failure( - uniffiClonePointer(), - status, - ), - FfiConverterOptionalMoqException.lift, - null, - ); - } - MoqOriginProducer publish() { return rustCallWithLifter( (status) => uniffi_moq_ffi_fn_method_moqsession_publish( @@ -12867,28 +12949,42 @@ class MoqSession implements MoqSessionInterface { ); } - MoqConnectionStats stats() { + MoqConnectionState state() { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqsession_stats( + (status) => uniffi_moq_ffi_fn_method_moqsession_state( uniffiClonePointer(), status, ), - FfiConverterMoqConnectionStats.lift, + FfiConverterMoqConnectionState.lift, null, ); } - UniffiRustFuture status() { + UniffiRustFuture stateChanged({required int after}) { return uniffiRustCallAsync( - () => uniffi_moq_ffi_fn_method_moqsession_status(uniffiClonePointer()), + () => uniffi_moq_ffi_fn_method_moqsession_state_changed( + uniffiClonePointer(), + FfiConverterUInt64.lower(after), + ), ffi_moq_ffi_rust_future_poll_rust_buffer, ffi_moq_ffi_rust_future_complete_rust_buffer, ffi_moq_ffi_rust_future_cancel_rust_buffer, ffi_moq_ffi_rust_future_free_rust_buffer, - FfiConverterMoqConnectionStatus.lift, + FfiConverterMoqConnectionState.lift, moqExceptionErrorHandler, ); } + + MoqConnectionStats stats() { + return rustCallWithLifter( + (status) => uniffi_moq_ffi_fn_method_moqsession_stats( + uniffiClonePointer(), + status, + ), + FfiConverterMoqConnectionStats.lift, + null, + ); + } } class FfiConverterMoqSession { @@ -17960,14 +18056,6 @@ external Pointer uniffi_moq_ffi_fn_method_moqclient_connect( RustBuffer url, ); -@Native, Pointer)>( - assetId: _uniffiAssetId, -) -external RustBuffer uniffi_moq_ffi_fn_method_moqclient_failure( - Pointer ptr, - Pointer uniffiStatus, -); - @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -18014,10 +18102,10 @@ external Pointer uniffi_moq_ffi_fn_method_moqsession_closed( Pointer ptr, ); -@Native, Pointer)>( +@Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external int uniffi_moq_ffi_fn_method_moqsession_connects( +external Pointer uniffi_moq_ffi_fn_method_moqsession_consume( Pointer ptr, Pointer uniffiStatus, ); @@ -18025,7 +18113,7 @@ external int uniffi_moq_ffi_fn_method_moqsession_connects( @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_method_moqsession_consume( +external Pointer uniffi_moq_ffi_fn_method_moqsession_publish( Pointer ptr, Pointer uniffiStatus, ); @@ -18033,30 +18121,28 @@ external Pointer uniffi_moq_ffi_fn_method_moqsession_consume( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqsession_failure( +external RustBuffer uniffi_moq_ffi_fn_method_moqsession_recv_bandwidth( Pointer ptr, Pointer uniffiStatus, ); -@Native Function(Pointer, Pointer)>( - assetId: _uniffiAssetId, -) -external Pointer uniffi_moq_ffi_fn_method_moqsession_publish( +@Native Function(Pointer)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqsession_shutdown( Pointer ptr, - Pointer uniffiStatus, ); @Native, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqsession_recv_bandwidth( +external RustBuffer uniffi_moq_ffi_fn_method_moqsession_state( Pointer ptr, Pointer uniffiStatus, ); -@Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqsession_shutdown( +@Native Function(Pointer, Uint64)>(assetId: _uniffiAssetId) +external Pointer uniffi_moq_ffi_fn_method_moqsession_state_changed( Pointer ptr, + int after, ); @Native, Pointer)>( @@ -18067,11 +18153,6 @@ external RustBuffer uniffi_moq_ffi_fn_method_moqsession_stats( Pointer uniffiStatus, ); -@Native Function(Pointer)>(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqsession_status( - Pointer ptr, -); - @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) @@ -19156,9 +19237,6 @@ external int uniffi_moq_ffi_checksum_method_moqclient_cancel(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqclient_connect(); -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqclient_failure(); - @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_auth(); @@ -19171,15 +19249,9 @@ external int uniffi_moq_ffi_checksum_method_moqsession_cancel(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_closed(); -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqsession_connects(); - @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_consume(); -@Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqsession_failure(); - @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_publish(); @@ -19190,10 +19262,13 @@ external int uniffi_moq_ffi_checksum_method_moqsession_recv_bandwidth(); external int uniffi_moq_ffi_checksum_method_moqsession_shutdown(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqsession_stats(); +external int uniffi_moq_ffi_checksum_method_moqsession_state(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqsession_status(); +external int uniffi_moq_ffi_checksum_method_moqsession_state_changed(); + +@Native(assetId: _uniffiAssetId) +external int uniffi_moq_ffi_checksum_method_moqsession_stats(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqvideoconsumer_cancel(); @@ -19847,10 +19922,7 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqclient_cancel() != 29949) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqclient_connect() != 14263) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } - if (uniffi_moq_ffi_checksum_method_moqclient_failure() != 29341) { + if (uniffi_moq_ffi_checksum_method_moqclient_connect() != 5016) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqsession_auth() != 1680) { @@ -19862,18 +19934,12 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqsession_cancel() != 39476) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqsession_closed() != 7901) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } - if (uniffi_moq_ffi_checksum_method_moqsession_connects() != 18791) { + if (uniffi_moq_ffi_checksum_method_moqsession_closed() != 8167) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqsession_consume() != 57909) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqsession_failure() != 39419) { - throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); - } if (uniffi_moq_ffi_checksum_method_moqsession_publish() != 15240) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } @@ -19883,10 +19949,13 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqsession_shutdown() != 1301) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqsession_stats() != 36396) { + if (uniffi_moq_ffi_checksum_method_moqsession_state() != 32292) { + throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); + } + if (uniffi_moq_ffi_checksum_method_moqsession_state_changed() != 59452) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqsession_status() != 49725) { + if (uniffi_moq_ffi_checksum_method_moqsession_stats() != 36396) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqvideoconsumer_cancel() != 21122) { diff --git a/doc/lib/c/index.md b/doc/lib/c/index.md index fe8cd94eb16..2c292d6edad 100644 --- a/doc/lib/c/index.md +++ b/doc/lib/c/index.md @@ -46,7 +46,7 @@ moq_string fp = { hex_sha256, strlen(hex_sha256) }; config.tls_fingerprints = &fp; // trust one self-signed relay config.tls_fingerprints_len = 1; -int session = moq_session_connect(url, url_len, &config, origin, 0, on_status, user_data); +int session = moq_session_connect(url, url_len, &config, origin, 0, on_state, user_data); if (session < 0) return fail(moq_error()); ``` @@ -60,7 +60,7 @@ here, from media publish and consume to raw pixels and PCM with the codec inside. The header is the reference: each function carries a doc comment. [Layers](/lib/layers) maps each wrapped Rust layer to its function prefixes. -- **Handles and callbacks.** Every object is an integer handle, and every async result arrives on a `moq_status_callback` with your `void *user_data`. A status `> 0` is a live result, `0` a clean close, and `< 0` an error. The last two are terminal: moq-c never touches `user_data` again, so free it there. `*_close` and `*_cancel` only request shutdown; the terminal callback still fires. +- **Handles and callbacks.** Every object is an integer handle, and every async result arrives on a `moq_status_callback` with your `void *user_data`. A status `> 0` is a live result, `0` a clean close, and `< 0` an error. The last two are terminal: moq-c never touches `user_data` again, so free it there. `*_close` and `*_cancel` only request shutdown; the terminal callback still fires. A session reports on a `moq_state_callback` instead: each `moq_connection_state` carries its `phase`, `connects`, the negative `failure` of the latest attempt, and the live `protocol`, and the `MOQ_CONNECTION_PHASE_CLOSED` snapshot is terminal, delivered after the handle is released. - **Errors.** Negative return codes are named by `MOQ_ERROR_*`, and `moq_error()` gives the reason on the calling thread. Auth rejections have their own codes so you don't retry them. For the peer's protocol code use `moq_error_protocol()`; do not parse `moq_error()`. A panic in a binding background task reports `MOQ_ERROR_PANIC` through its terminal callback; unrelated objects keep running. A session closed because its credential expired has kind `MOQ_PROTOCOL_KIND_EXPIRED`, and a request refused for an expired token returns `MOQ_ERROR_EXPIRED`; refresh the token before retrying. A catalog that needs a newer moq-hang draft than this build reads returns `MOQ_ERROR_UNSUPPORTED_CATALOG`; upgrade the library to read it. A request-cap closure has kind `MOQ_PROTOCOL_KIND_TOO_MANY_REQUESTS`; reduce the workload or adjust the relay's [session limits](/bin/relay/config#session-and-peer) before reconnecting. - **Threading.** Call any function from any thread. Raw publish calls block until the codec takes the frame, which paces a publisher. - **Zeroed config is the default.** A zeroed `moq_client_config` means the default for every field, so new fields don't break callers. A field whose default isn't zero has a `has_*` flag: `backoff_timeout_us = 0` means "retry forever" only with `has_backoff_timeout = true`. @@ -71,7 +71,7 @@ inside. The header is the reference: each function carries a doc comment. - **Live encoder timing.** After writing a frame you encoded yourself, call `moq_publish_media_flush` with the same timestamp so the catalog advertises your jitter. Skip it for file and network imports. On a seek or pause, call `moq_publish_media_discontinuity`, then keep timestamps moving forward and resume video on a keyframe. - **JSON values.** `moq_consume_json_value` fills `moq_json_value` with the document and its frame's `timestamp_us`, rounded down to a whole microsecond; `timestamp_present` is false on an untimed track. A snapshot consumer's callback fires for each state in order, but a group superseded before it is read is skipped. - **Decoded frames hold decoder buffers.** Free each frame id with `moq_decode_video_frame_free` promptly, or the decoder stalls. -- **Stats.** `moq_session_stats()` fills `moq_connection_stats` with `rtt_us`, `estimated_send_rate_bps`, and the byte and packet counters (`bytes_sent`, `bytes_received`, `bytes_lost`, `packets_sent`, `packets_received`, `packets_lost`). Each has a `_valid` flag, false when the transport does not report it, which is not the same as zero. `moq_session_snapshot()` adds the negotiated `protocol`, and while a session reconnects `moq_session_failure()` returns why, with the reason in `moq_error()`. Hold the handle returned by `moq_session_recv_bandwidth()` to request receive estimates. `moq_bandwidth_consumer_peek()` reads the estimate and `moq_bandwidth_consumer_changed()` waits for a change. `moq_bandwidth_consumer_close()` releases demand; the last consumer stops PROBE. Stats snapshots do not request it. +- **Stats.** `moq_session_stats()` fills `moq_connection_stats` with `rtt_us`, `estimated_send_rate_bps`, and the byte and packet counters (`bytes_sent`, `bytes_received`, `bytes_lost`, `packets_sent`, `packets_received`, `packets_lost`). Each has a `_valid` flag, false when the transport does not report it, which is not the same as zero. `moq_session_snapshot()` adds the negotiated `protocol`. A failed dial or dropped connection reaches the session's `on_state` with its `failure` code, and `moq_error()` gives the reason during that callback. Hold the handle returned by `moq_session_recv_bandwidth()` to request receive estimates. `moq_bandwidth_consumer_peek()` reads the estimate and `moq_bandwidth_consumer_changed()` waits for a change. `moq_bandwidth_consumer_close()` releases demand; the last consumer stops PROBE. Stats snapshots do not request it. - **Demand.** A watcher from `moq_publish_track_demand()` (or the media, video, and audio variants) calls back `MOQ_DEMAND_USED` or `MOQ_DEMAND_UNUSED`, again whenever the wanted group moves. `moq_publish_demand_wanted()` reads that group: start a new one once it passes your largest. Set `refresh` in `moq_track_info` to have a joining subscriber ask for a new group once the newest has grown past `refresh` times its first frame. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. Among the video renditions you can decode, prefer the highest `preference`; `0` is the default and `-1` marks a compatibility transcode. diff --git a/doc/lib/cpp/index.md b/doc/lib/cpp/index.md index 6105ca2bf26..73b1dbcbca7 100644 --- a/doc/lib/cpp/index.md +++ b/doc/lib/cpp/index.md @@ -209,7 +209,7 @@ On `moq-lite-07-wip` (opt in with `ClientConfig::versions`) and on moq-transport ## Stats -`session->stats()` reports the transport counters, each a `std::optional` that is empty when the transport does not report it, plus the negotiated protocol in `version`. While a client session reconnects, `session->failure()` returns why as a `moq::Error`, and while its first `connect` is still retrying, `client->failure()` does. +`session->stats()` reports the transport counters, each a `std::optional` that is empty when the transport does not report it, plus the negotiated protocol in `version`. Connect returns a connecting session. Read `session->state()` and wait with `state_changed(state.revision)` to observe its first-dial failures and reconnects; independent watchers keep their own revisions. ## Shutdown diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index 5a270a128aa..87da0c36b5e 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -143,7 +143,7 @@ shows which module holds each. - **Decoded frames hold decoder buffers.** `dispose()` each frame from a `video.Consumer` promptly rather than waiting for the garbage collector, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `await moq.close()` or `session.shutdown()` drains for up to one second and reports any error. `session.cancel(code: 0)` closes at once. Finish or abort live tracks first. Awaiting cancellation of an announcement, grant, or request subscription releases its pending native read. Announcements also release their cursor; authorization and server listeners leave their shared owner usable. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()`. The returned `BroadcastFinish` keeps the broadcast announced and serving the finished tracks for `linger`, their longest max age, so a subscriber still catching up can drain them. `await finish.wait()` completes once the linger passes, and `finish.close()` closes the broadcast at once, completing the wait. `broadcast.close()` stays the abrupt end. An unreferenced `BroadcastFinish` closes the broadcast only when the garbage collector reclaims it, possibly long after, so wait on or close it rather than dropping it. -- **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol, and while a client session reconnects `session.failure()` says why. Before the first connect, `client.failure()` says why the dial is retrying. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. +- **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `ConnectOptions(versions: ...)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), listen to `moq.auth().grants()` for the `Grant` the relay sent back, `null` until it answers and while a client session reconnects. `await auth().add(token: ...)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. Among the video renditions you can decode, prefer the highest `preference`; `0` is the default and `-1` marks a compatibility transcode. diff --git a/doc/lib/go/index.md b/doc/lib/go/index.md index 9a27afed102..64305e23b90 100644 --- a/doc/lib/go/index.md +++ b/doc/lib/go/index.md @@ -131,7 +131,7 @@ shows which module holds each. - **Decoded frames hold decoder buffers.** `Close` each `VideoDecodedFrame` promptly, or the decoder stalls. `Resize` is best effort, so read each frame's `Width()` and `Height()`. - **Closing.** `client.Close()` drains for up to one second and returns an error on failure. `session.Shutdown(ctx)` does the same, and `session.Cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **Ending cleanly.** When the input ends, finish every track, then call `broadcast.Finish()`. The returned `*BroadcastFinish` keeps the broadcast announced and serving the finished tracks for `Linger()`, their longest max age, so a subscriber still catching up can drain them. `finish.Wait(ctx)` returns once the linger passes; ending `ctx`, or `finish.Close()`, closes the broadcast at once. `broadcast.Close()` stays the abrupt end. An unreferenced `*BroadcastFinish` closes the broadcast only when the garbage collector reclaims it, possibly long after, so wait on or close it rather than dropping it. -- **Stats.** `Session().Stats()` reports `RTT`, `EstimatedSendRateBps`, and the byte and packet counters (`BytesSent`, `BytesReceived`, `BytesLost`, `PacketsSent`, `PacketsReceived`, `PacketsLost`). A field is nil when the transport does not report it, which is not the same as zero. `Version` names the negotiated protocol, and while a client session reconnects `Session().Failure()` says why. Hold the owned `BandwidthConsumer` returned by `Session().RecvBandwidth()` to receive bandwidth estimates. `Rate()` reads the current estimate in bits per second and `RateChanged(ctx)` waits for a new one. Calling `Close()` on the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. +- **Stats.** `Session().Stats()` reports `RTT`, `EstimatedSendRateBps`, and the byte and packet counters (`BytesSent`, `BytesReceived`, `BytesLost`, `PacketsSent`, `PacketsReceived`, `PacketsLost`). A field is nil when the transport does not report it, which is not the same as zero. `Version` names the negotiated protocol. `Dial` returns a connecting session; read `Session().State()` and wait with `StateChanged(ctx, state.Revision)` to observe first-dial failures and reconnects. Hold the owned `BandwidthConsumer` returned by `Session().RecvBandwidth()` to receive bandwidth estimates. `Rate()` reads the current estimate in bits per second and `RateChanged(ctx)` waits for a new one. Calling `Close()` on the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `moq.WithVersions`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `Session().Auth().Grant()` is the `Grant` the relay sent back, nil until it answers and while a client session reconnects; `GrantChanged(ctx)` waits for the next one. `Add(ctx, token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `Close()`, and is presented again on every reconnect. A refusal returns the relay's code. - **Errors.** Read diagnostic payloads from `Reason` and structured protocol failures from `Details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. Among the video renditions you can decode, prefer the highest `Preference`; `0` is the default and `-1` marks a compatibility transcode. diff --git a/doc/lib/kt/index.md b/doc/lib/kt/index.md index babbf925f76..f34a154df27 100644 --- a/doc/lib/kt/index.md +++ b/doc/lib/kt/index.md @@ -102,7 +102,7 @@ shows which module holds each. - **Decoded frames hold decoder buffers.** `close()` each frame from a `dev.moq.video.Consumer` promptly (or `use { }` it), or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** Suspending `moq.shutdown()` drains for up to one second and throws on failure. `Moq.close()`, and so `use { }`, cancels at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()`. The returned `BroadcastFinish` keeps the broadcast announced and serving the finished tracks for `linger`, their longest max age, so a subscriber still catching up can drain them. Suspending `finish.wait()` returns once the linger passes; cancelling its coroutine, or `finish.end()`, closes the broadcast at once. `broadcast.end()` stays the abrupt end. An unreferenced `BroadcastFinish` closes the broadcast only when the garbage collector reclaims it, possibly long after, so wait on or close it rather than dropping it. -- **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol, and while a client session reconnects `session.failure()` says why. Before the first connect, `client.failure()` says why the dial is retrying. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. +- **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `BandwidthConsumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `ClientConfig(versions = ...)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), collect `moq.auth().grants()` for the `Grant` the relay sent back, `null` until it answers and while a client session reconnects. Suspending `auth().add(token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. Among the video renditions you can decode, prefer the highest `preference`; `0` is the default and `-1` marks a compatibility transcode. diff --git a/doc/lib/py/index.md b/doc/lib/py/index.md index ff8613d1b38..d6492a0af1b 100644 --- a/doc/lib/py/index.md +++ b/doc/lib/py/index.md @@ -117,7 +117,7 @@ shows which module holds each. - **Decoded frames hold decoder buffers.** Drop each frame from a `moq.video.Consumer` promptly, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `await session.shutdown()` drains for up to one second and raises on failure. `cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **Ending cleanly.** When the input ends, finish every track, then call `broadcast.finish()`. The returned `BroadcastFinish` keeps the broadcast announced and serving the finished tracks for `linger`, their longest max age, so a subscriber still catching up can drain them. `await finish.wait()` returns once the linger passes; cancelling it, or `finish.close()`, closes the broadcast at once. `broadcast.close()` stays the abrupt end. -- **Stats.** `session.stats()` reports `rtt`, `estimated_send_rate_bps`, and the byte and packet counters (`bytes_sent`, `bytes_received`, `bytes_lost`, `packets_sent`, `packets_received`, `packets_lost`). A field is `None` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol, and while a client session reconnects `session.failure()` says why. Before the first connect, `client.failure()` says why the dial is retrying. Hold the owned `Bandwidth.Consumer` returned by `session.recv_bandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rate_changed()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. +- **Stats.** `session.stats()` reports `rtt`, `estimated_send_rate_bps`, and the byte and packet counters (`bytes_sent`, `bytes_received`, `bytes_lost`, `packets_sent`, `packets_received`, `packets_lost`). A field is `None` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `Bandwidth.Consumer` returned by `session.recv_bandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rate_changed()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `versions=`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth().grant()` is the `Grant` the relay sent back, `None` until it answers and while a client session reconnects; `await auth.grant_changed()` waits for the next one. `await auth.add(token)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal raises with the relay's code. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. Among the video renditions you can decode, prefer the highest `preference`; `0` is the default and `-1` marks a compatibility transcode. diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index c50aaea06e3..87678487a21 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -102,7 +102,7 @@ shows which module holds each. - **Decoded frames hold decoder buffers.** Release each frame from a `Video.Consumer` promptly, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. - **Closing.** `try await session.shutdown()` drains for up to one second and throws on failure. `session.cancel(code:)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **Ending cleanly.** When the input ends, finish every track, then call `try broadcast.finish()`. The returned `BroadcastFinish` keeps the broadcast announced and serving the finished tracks for `lingerUs`, their longest max age, so a subscriber still catching up can drain them. `try await finish.wait()` returns once the linger passes; cancelling its task, or `finish.close()`, closes the broadcast at once. `broadcast.close()` stays the abrupt end. -- **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `nil` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol, and while a client session reconnects `session.failure()` says why. Before the first connect, `client.failure()` says why the dial is retrying. Hold the owned `Bandwidth.Consumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. +- **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `nil` when the transport does not report it, which is not the same as zero. `version` names the negotiated protocol. Connect returns a connecting session; read its coherent `state()` snapshot and wait with that snapshot's revision to observe first-dial failures and reconnects. Each watcher keeps its own revision. Hold the owned `Bandwidth.Consumer` returned by `session.recvBandwidth()` to receive bandwidth estimates. `rate()` reads the current estimate in bits per second and `rateChanged()` waits for a new one. Release the consumer or call `cancel()` when finished; releasing the last consumer stops PROBE; the session and stats snapshots do not request it. Client consumers survive reconnects and report no estimate while disconnected. - **Authorization.** On `moq-lite-07-wip` (opt in with `Client(versions:)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth().grant()` is the `Grant` the relay sent back, `nil` until it answers and while a client session reconnects; `try await auth.grantChanged()` waits for the next one. `try await auth.add(token:)` presents a fresh token without reconnecting, returns an `AuthToken` whose grant joins the union until `cancel()`, and is presented again on every reconnect. A refusal throws with the relay's code. - **Errors.** Diagnostic cases use the `reason:` argument label; match their associated value to inspect it. Protocol errors carry `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. Among the video renditions you can decode, prefer the highest `preference`; `0` is the default and `-1` marks a compatibility transcode. diff --git a/go/ffi/MIGRATE.md b/go/ffi/MIGRATE.md index e47ab8791b1..a9d2c9beff3 100644 --- a/go/ffi/MIGRATE.md +++ b/go/ffi/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Connection state + +Generated connection APIs now expose `MoqConnectionState` and `MoqConnectionPhase`, with `state()` and revision-based `state_changed(after)` instead of status, connect-count, and failure polls. Connect returns before its first dial completes. Regenerate bindings from the matching Rust metadata. + ### Exact encoder rates and publication options Encoder configuration is breaking: `MoqVideoEncoderInput.framerate` is now a diff --git a/go/wrapper/MIGRATE.md b/go/wrapper/MIGRATE.md index 6e9708b5fc3..68bab16c90b 100644 --- a/go/wrapper/MIGRATE.md +++ b/go/wrapper/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Connection state + +`Dial` returns a connecting native client. Replace `Session.Status`, `Connects`, and `Failure` with `State()` and `StateChanged(ctx, state.Revision)`. `ConnectionState` carries `Phase`, `Connects`, `Failure`, and `Version`; `ConnectionPhase` replaces `ConnectionStatus`. Cancelling a state wait only cancels that wait. Cancel the session itself to stop its dial. + ### Exact encoder rates and publication options Raw video input framerates are exact numerator/denominator records, not integers. diff --git a/go/wrapper/bandwidth_test.go b/go/wrapper/bandwidth_test.go index c1c1c85d634..8c28f9d724f 100644 --- a/go/wrapper/bandwidth_test.go +++ b/go/wrapper/bandwidth_test.go @@ -22,6 +22,8 @@ func TestReservationUpdateReleasesSubscribedTrack(t *testing.T) { t.Fatal(err) } defer client.Close() + // Dial returns while connecting; the grants need the live session's estimate. + waitConnects(t, ctx, client.Session(), 1) // Grant assertions use a live QUIC estimate, but need no traffic or probing. bandwidth := client.Session().Bandwidth() broadcast, err := moq.NewBroadcastProducer() diff --git a/go/wrapper/client.go b/go/wrapper/client.go index 050107de43d..15733de285c 100644 --- a/go/wrapper/client.go +++ b/go/wrapper/client.go @@ -328,7 +328,7 @@ type Client struct { closeErr error } -// Dial connects to a MoQ server and returns the established client. Cancel ctx +// Dial starts a MoQ connection and returns without waiting for its first native dial to succeed. Cancel ctx // to abort an in-flight connect. func Dial(ctx context.Context, url string, opts ...ClientOption) (*Client, error) { var cfg clientConfig diff --git a/go/wrapper/reconnect_test.go b/go/wrapper/reconnect_test.go index 03678a46c80..be145666e16 100644 --- a/go/wrapper/reconnect_test.go +++ b/go/wrapper/reconnect_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "net" "sync" "testing" "time" @@ -96,11 +97,12 @@ func dialWorker(t *testing.T, ctx context.Context, url string) *moq.Client { func waitConnects(t *testing.T, ctx context.Context, session *moq.Session, want uint64) { t.Helper() - for session.Connects() < want { - select { - case <-ctx.Done(): - t.Fatalf("connects = %d, want >= %d", session.Connects(), want) - case <-time.After(10 * time.Millisecond): + state := session.State() + for state.Connects < want { + var err error + state, err = session.StateChanged(ctx, state.Revision) + if err != nil { + t.Fatalf("wait connects: %v", err) } } } @@ -235,7 +237,7 @@ func TestReconnectAcrossRelayRestart(t *testing.T) { if frame, err := trackConsumer.ReadFrame(ctx); err != nil || frame == nil { t.Fatalf("frame before restart: frame=%+v err=%v", frame, err) } - if err := subscriber.Session().Failure(); err != nil { + if err := subscriber.Session().State().Failure; err != nil { t.Fatalf("failure before any drop: %v", err) } if version := subscriber.Session().Stats().Version; version == nil || *version == "" { @@ -251,7 +253,7 @@ func TestReconnectAcrossRelayRestart(t *testing.T) { waitConnects(t, ctx, publisher.Session(), 2) waitConnects(t, ctx, subscriber.Session(), 2) // The connect that advanced the count also cleared the drop's reason. - if err := subscriber.Session().Failure(); err != nil { + if err := subscriber.Session().State().Failure; err != nil { t.Fatalf("failure after reconnect: %v", err) } @@ -344,3 +346,46 @@ func TestDialConnectionOptions(t *testing.T) { t.Fatal("negative idle timeout dialed") } } + +// A public wrapper owns its first dial through Session and observes repeated failures. +func TestFirstDialState(t *testing.T) { + silent, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer silent.Close() + ctx, cancel := context.WithTimeout(context.Background(), reconnectTimeout) + defer cancel() + client, err := moq.Dial(ctx, "https://"+silent.LocalAddr().String(), + moq.WithTLSVerify(false), moq.WithBind("127.0.0.1:0"), + moq.WithWebSocketEnabled(false), moq.WithConnectTimeout(100*time.Millisecond), + moq.WithBackoff(moq.Backoff{Initial: 50 * time.Millisecond, Max: 50 * time.Millisecond, Timeout: moq.RetryForever}), + ) + if err != nil { + t.Fatal(err) + } + session := client.Session() + defer session.Cancel(0) + state := session.State() + if state.Phase != moq.ConnectionPhaseConnecting || state.Connects != 0 { + t.Fatalf("initial state: %+v", state) + } + for i := 0; i < 2; i++ { + state, err = session.StateChanged(ctx, state.Revision) + if err != nil { + t.Fatal(err) + } + if state.Failure == nil || state.Connects != 0 || state.Version != nil { + t.Fatalf("failed dial state: %+v", state) + } + } + // A canceled waiter must leave both the session and another observer live. + canceled, stop := context.WithCancel(ctx) + stop() + if _, err := session.StateChanged(canceled, state.Revision); !errors.Is(err, context.Canceled) { + t.Fatalf("canceled waiter: %v", err) + } + if _, err := session.StateChanged(ctx, state.Revision); err != nil { + t.Fatalf("independent waiter: %v", err) + } +} diff --git a/go/wrapper/session.go b/go/wrapper/session.go index 80053038451..16a1c248241 100644 --- a/go/wrapper/session.go +++ b/go/wrapper/session.go @@ -7,7 +7,7 @@ import ( "moq.dev/moq/internal/bridge" ) -// Session is an established MoQ connection. Hold it (or the Client/Server that +// Session is a MoQ connection, including its initial native dial. Hold it (or the Client/Server that // produced it) to keep the connection alive; once every handle is dropped the // connection closes. type Session struct { @@ -22,42 +22,38 @@ func (s *Session) Closed(ctx context.Context) error { return bridge.CallErr(ctx, s.abort, s.inner.Closed) } -// Status blocks until the connection status differs from the one this session -// last reported. A client session reports ConnectionStatusConnected first (the connect it -// was built from), then follows the reconnect loop: ConnectionStatusDisconnected while -// redialing, ConnectionStatusMigrating during a GOAWAY handover. It returns an error once -// the connection stops for good. A server-accepted session's only transition is -// terminal, so Status waits for the close and returns its reason. Cancelling ctx -// gives up waiting and shuts the session down. -// -// This reports the current status rather than every edge: a drop that reconnects -// before the next call is coalesced away, so the outages it hides are the ones -// that already healed. Don't count outages with it. -func (s *Session) Status(ctx context.Context) (ConnectionStatus, error) { - return bridge.Call(ctx, s.abort, s.inner.Status) +// ConnectionState is one coherent lifecycle snapshot. +type ConnectionState struct { + // Revision is the opaque token for the next StateChanged wait. + Revision uint64 + // Phase says whether the connection is dialing, serving, replacing, or closed. + Phase ConnectionPhase + // Connects counts successful sessions, including replacements. + Connects uint64 + // Failure is the latest failed attempt or terminal cause, cleared by a successful connect. + Failure error + // Version names the live protocol, or nil while offline. + Version *string +} + +func connectionStateFromFFI(state ffi.MoqConnectionState) ConnectionState { + var failure error + if state.Failure != nil { + failure = *state.Failure + } + return ConnectionState{Revision: state.Revision, Phase: state.Phase, Connects: state.Connects, Failure: failure, Version: state.Version} } -// Connects counts how many times this session has connected: 1 for the connect that built it, one -// more on each reconnect. A server-accepted session stays at 1. -// -// Pair it with Status to log each reconnect by number: a ConnectionStatusConnected whose -// count grew is a reconnect. Like Status, it reports the current state, so a -// drop that reconnects between reads is coalesced away. -func (s *Session) Connects() uint64 { - return s.inner.Connects() -} - -// Failure reports why a client session is reconnecting: the error that ended -// the last connection or failed the latest redial, or nil once a connection -// lands. A redial that keeps failing never changes Status, so poll this while it -// reports ConnectionStatusDisconnected to show the reason. Giving up for good -// returns from Closed instead. A server-accepted session always returns nil. -func (s *Session) Failure() error { - failure := s.inner.Failure() - if failure == nil || *failure == nil { - return nil - } - return *failure +// State reads the lifecycle fields together without advancing a watcher. +func (s *Session) State() ConnectionState { return connectionStateFromFFI(s.inner.State()) } + +// StateChanged waits for a revision different from after, without sharing a watcher cursor. +// Cancelling ctx only cancels this wait; it leaves the connection and other watchers running. +func (s *Session) StateChanged(ctx context.Context, after uint64) (ConnectionState, error) { + state, err := bridge.Call(ctx, nil, func(ctx context.Context) (ffi.MoqConnectionState, error) { + return s.inner.StateChanged(ctx, after) + }) + return connectionStateFromFFI(state), err } // Stats snapshots the current connection statistics. diff --git a/go/wrapper/types.go b/go/wrapper/types.go index 6432feb2510..7d5fc8f1744 100644 --- a/go/wrapper/types.go +++ b/go/wrapper/types.go @@ -23,8 +23,8 @@ type ( AudioSampleFormat = ffi.MoqAudioSampleFormat // AudioFrame is one audio frame: PCM payload plus a presentation timestamp in microseconds. AudioFrame = ffi.MoqAudioFrame - // ConnectionStatus is a connection lifecycle transition reported by Session.Status. - ConnectionStatus = ffi.MoqConnectionStatus + // ConnectionPhase is a connection lifecycle transition reported by Session.State. + ConnectionPhase = ffi.MoqConnectionPhase // CongestionControl is the congestion control family for a QUIC connection. CongestionControl = ffi.MoqCongestionControl // ErrorScope is whether a protocol code is from the session or stream registry. @@ -159,14 +159,18 @@ const ( OrderDescending = ffi.MoqOrderDescending ) -// ConnectionStatus values: the lifecycle of a client session's connection. +// ConnectionPhase values: the lifecycle of a client session's connection. const ( - // ConnectionStatusConnected means a session connected (the first connect, or a reconnect after a drop). - ConnectionStatusConnected = ffi.MoqConnectionStatusConnected - // ConnectionStatusDisconnected means the session dropped; a reconnect attempt follows. - ConnectionStatusDisconnected = ffi.MoqConnectionStatusDisconnected - // ConnectionStatusMigrating means the peer sent a GOAWAY; the replacement is being dialed while the old session keeps serving. - ConnectionStatusMigrating = ffi.MoqConnectionStatusMigrating + // ConnectionPhaseConnecting means no session has connected yet. + ConnectionPhaseConnecting = ffi.MoqConnectionPhaseConnecting + // ConnectionPhaseClosed means the connection has stopped for good. + ConnectionPhaseClosed = ffi.MoqConnectionPhaseClosed + // ConnectionPhaseConnected means a session connected (the first connect, or a reconnect after a drop). + ConnectionPhaseConnected = ffi.MoqConnectionPhaseConnected + // ConnectionPhaseDisconnected means the session dropped; a reconnect attempt follows. + ConnectionPhaseDisconnected = ffi.MoqConnectionPhaseDisconnected + // ConnectionPhaseMigrating means the peer sent a GOAWAY; the replacement is being dialed while the old session keeps serving. + ConnectionPhaseMigrating = ffi.MoqConnectionPhaseMigrating ) // CongestionControl values. diff --git a/kt/moq-ffi/MIGRATE.md b/kt/moq-ffi/MIGRATE.md index f1116dea043..81fb99c14cd 100644 --- a/kt/moq-ffi/MIGRATE.md +++ b/kt/moq-ffi/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Connection state + +Generated connection APIs now expose `MoqConnectionState` and `MoqConnectionPhase`, with `state()` and revision-based `state_changed(after)` instead of status, connect-count, and failure polls. Connect returns before its first dial completes. Regenerate bindings from the matching Rust metadata. + ### Exact encoder rates and publication options Encoder configuration is breaking: `MoqVideoEncoderInput.framerate` is now a diff --git a/kt/moq/MIGRATE.md b/kt/moq/MIGRATE.md index 98e9ddd24fb..f15d69691be 100644 --- a/kt/moq/MIGRATE.md +++ b/kt/moq/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Connection state + +`Moq.connect` returns a connecting native session. Replace `status()`, `connects()`, and failure polls with `session.state()` and `session.stateChanged(state.revision)`. `ConnectionState` carries `phase`, `connects`, `failure`, and `version`; `ConnectionPhase` replaces `ConnectionStatus`. + ### Exact encoder rates and publication options Raw video input framerates are exact numerator/denominator records, not integers. diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index 7157e7ac0b7..eb38b34963b 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -163,8 +163,11 @@ typealias Auth = uniffi.moq.MoqAuth typealias AuthToken = uniffi.moq.MoqAuthToken /** What the peer lets this side do: publish and subscribe patterns, and an expiry. */ typealias Grant = uniffi.moq.MoqGrant -/** A connection lifecycle transition reported by [Session.status]. */ -typealias ConnectionStatus = uniffi.moq.MoqConnectionStatus +/** A connection lifecycle transition reported by [Session.state]. */ +typealias ConnectionPhase = uniffi.moq.MoqConnectionPhase + +/** One coherent connection lifecycle snapshot. */ +typealias ConnectionState = uniffi.moq.MoqConnectionState /** Retry pacing for the automatic reconnect: initial delay, multiplier, ceiling, and give-up window. */ typealias Backoff = uniffi.moq.MoqBackoff /** Whether a protocol code is from the session or stream registry. */ diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt index 22af44a7a77..1dc8addd5f6 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt @@ -1,7 +1,7 @@ package dev.moq /** - * A connected MoQ session with publish/subscribe conveniences. + * A MoQ session with publish/subscribe conveniences. * * Build one with [Moq.connect]. The underlying [session] always exposes a * publisher and a subscriber (wired from the origins in its [ClientConfig], or @@ -12,7 +12,7 @@ package dev.moq * disposal through `use { ... }` or [close] cancels immediately. */ class Moq internal constructor( - /** The established session. Use it for [Session.closed]/[Session.shutdown]. */ + /** The connecting or connected session. Use it for [Session.closed]/[Session.shutdown]. */ val session: Session, private val client: Client, ) : AutoCloseable { @@ -51,14 +51,6 @@ class Moq internal constructor( */ suspend fun requestBroadcast(path: String): BroadcastConsumer = session.consume().requestBroadcast(path) - /** - * How many times this session has connected: 1 for the connect that built it, one more on - * each reconnect. A server-accepted session stays at 1. - * - * Pair it with [Session.status] to log each reconnect by number. - */ - fun connects(): ULong = session.connects() - /** * The session's bandwidth allocator. * @@ -98,7 +90,7 @@ class Moq internal constructor( companion object { /** - * Connect to a relay at [url] and return the live [Moq] connection. + * Connect to a relay at [url] and return a connecting [Moq] connection. * * [config] carries the TLS trust, bind address, protocol versions, QUIC and * WebSocket tuning, reconnect pacing, and origins; every field has a default. diff --git a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt index 64477c639ae..a5efa97a4ef 100644 --- a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt +++ b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt @@ -107,7 +107,7 @@ class SmokeTest { /** * Exercises the [Moq.connect] facade end to end without a network: a bogus - * URL fails fast, and the failure surfaces as a [MoqException]. Also proves + * dial failure reaches the returned session through [Session.closed]. Also proves * the native lib loads through the transitive `moq-ffi` dependency. * One-shot mode, since the default reconnect would retry the dial with * backoff instead of failing. @@ -115,7 +115,9 @@ class SmokeTest { @Test fun `connect fails fast and surfaces a MoqException`() = runTest { val ex = assertFailsWith { - Moq.connect("https://localhost:0/test", ClientConfig(tls = ClientTls(insecure = true), once = true)) + Moq.connect("https://localhost:0/test", ClientConfig(tls = ClientTls(insecure = true), once = true)).use { moq -> + moq.session.closed() + } } assertTrue( ex.isShutdown || ex is MoqException.Connect || ex is MoqException.Url, @@ -138,7 +140,7 @@ class SmokeTest { once = true, websocket = WebSocketConfig(enabled = false, delayUs = 0uL), ), - ) + ).use { moq -> moq.session.closed() } } assertFailsWith { Moq.connect("https://localhost:0/test", ClientConfig(versions = listOf("moq-lite-99"))) @@ -199,14 +201,14 @@ class SmokeTest { val server: ServerConfig = ServerConfig(tls = ServerTls(generate = listOf("localhost"))) assertEquals(4096uL, client.quic.maxStreams) assertEquals(listOf("localhost"), server.tls.generate) - val status: ConnectionStatus = ConnectionStatus.CONNECTED + val status: ConnectionPhase = ConnectionPhase.CONNECTED assertEquals(4_000_000uL, hint.bitrate) assertEquals(true, snapshot.deltas) assertEquals(false, stream.compression) assertNull(properties.display) assertNull(properties.flip) assertEquals(500_000uL, backoff.initialUs) - assertEquals(ConnectionStatus.CONNECTED, status) + assertEquals(ConnectionPhase.CONNECTED, status) } @Test @@ -675,24 +677,17 @@ class SmokeTest { } } - /** - * Cancelling the client aborts a connect parked on a server that never - * accepts, and the connect reports it as [MoqException.Cancelled]. - */ + /** The returned Session owns its pending dial even after Client cancellation. */ @Test - fun `client cancel aborts a pending connect`() = runTest { + fun `session owns and cancels its first dial`() = runTest { Server.listen(ServerConfig(bind = "127.0.0.1:0", tls = ServerTls(generate = listOf("localhost")))).use { server -> - // A reconnecting client would redial instead of failing the connect. val client = Client(ClientConfig(bind = "127.0.0.1:0", tls = ClientTls(insecure = true), once = true)) - - // runCatching, because a failed `async` would cancel the test scope - // before `await` ever reported it. - val connect = async { runCatching { client.connect("https://${server.localAddr}") } } - yield() + val session = client.connect("https://${server.localAddr}") client.cancel() - - val connected = connect.await().exceptionOrNull() - assertTrue(connected is MoqException.Cancelled, "expected a cancelled connect, got: $connected") + assertEquals(0uL, session.state().connects) + session.cancel(0u) + session.closed() + assertEquals(ConnectionPhase.CLOSED, session.state().phase) } } diff --git a/py/moq-ffi/MIGRATE.md b/py/moq-ffi/MIGRATE.md index 93fd7764871..a71e2fe9f9b 100644 --- a/py/moq-ffi/MIGRATE.md +++ b/py/moq-ffi/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Connection state + +Generated connection APIs now expose `MoqConnectionState` and `MoqConnectionPhase`, with `state()` and revision-based `state_changed(after)` instead of status, connect-count, and failure polls. Connect returns before its first dial completes. Regenerate bindings from the matching Rust metadata. + ### Exact encoder rates and publication options Encoder configuration is breaking: `MoqVideoEncoderInput.framerate` is now a diff --git a/py/moq-rs/MIGRATE.md b/py/moq-rs/MIGRATE.md index 918ce9cb84c..cb060da1319 100644 --- a/py/moq-rs/MIGRATE.md +++ b/py/moq-rs/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Connection state + +Client entry returns a connecting native session. Replace `Session.status()`, `connects()`, and both `failure()` polls with `state()` and `await state_changed(state.revision)`. The `ConnectionState` fields include `phase`, `connects`, `failure`, and `version`; `ConnectionPhase` replaces `ConnectionStatus`. Wait for `CONNECTED` when work requires an established transport, or await `closed()` for the terminal result. + ### Exact encoder rates and publication options Raw video input framerates are exact numerator/denominator records, not integers. diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index 781284a93ec..13c50cb7bd2 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -140,7 +140,7 @@ client = moq.Client( - `versions`. Protocol versions to offer, most preferred first (e.g. `"moq-lite-03"`); empty offers all, which `versions()` lists. - `timeout`, `race`, `resolution_delay`. Bound one connect attempt and pace Happy Eyeballs. - `reconnect`, `backoff`. Redial with a `Backoff` when the transport drops; `reconnect=False` dials once. - - `.session`. The established `Session` (or `None` before connecting / after exit). + - `.session`. The connecting or connected `Session` (or `None` before entering / after exit). - **`Server(bind="[::]:443", *, tls_cert=(), tls_key=(), tls_generate=(), versions=(), max_streams=None, keylog=False, publish=None, consume=None)`**. Async context manager + async iterator of incoming `Request`s. - `keylog`. Write TLS session secrets to the file `SSLKEYLOGFILE` names, for decrypting a capture; without `SSLKEYLOGFILE` entering the server fails. - `.local_addr`. The bound address (useful when binding to port `0`). @@ -151,12 +151,12 @@ client = moq.Client( - `await .accept(*, publish=None, consume=None) → Session`. Origins are captured when accept starts; None inherits the server default and a supplied origin replaces it. Pass fresh origins for isolation, or the same origin on both sides to share it. A second response raises `AlreadyResponded`; calls after cancel raise `Cancelled`. Complete the handshake (hold the result to keep the connection alive). - `await .reject(code)`. Reject with an application error code; 401 and 403 map to unauthorized. - `.cancel()`. Cancel an in-flight `accept()`/`reject()` call. -- **`Session`**. An established connection. Holding it keeps the connection alive; it is also an `async with` context manager that drains on a clean exit and cancels on an error. +- **`Session`**. A connection, connecting or connected. Holding it keeps the connection alive; it is also an `async with` context manager that drains on a clean exit and cancels on an error. - `await .closed()`. Wait until the session closes. - `.cancel(code)`, `await session.shutdown()`. Cancel immediately, or drain within one second, raising on failure. Explicit `moq-lite-07-wip` waits for the peer to receive finished tails; older Lite versions, including default lite-06, wait only for transport ACKs. IETF also waits for transport ACKs. - `.publish() → OriginProducer`, `.consume() → OriginConsumer`. The wired origin sides. - `.stats() → ConnectionStats`. Snapshot RTT, bandwidth estimates, and byte/packet counters. - - `await .status() → ConnectionStatus`, `.connects()`, `.failure()`. Watch reconnects; `connects()` counts connections, 1 on the first, and `failure()` says why a reconnect is under way. Before the first connect, `Client.failure()` says why the dial is retrying. + - `.state()` and `await .state_changed(after)`. Read one lifecycle snapshot and wait with its revision; first-dial failures and reconnects share the same session. - `.bandwidth() → Bandwidth`. Divide the send estimate between encoders and app-owned tracks. - `.auth() → Auth`. On `moq-lite-07-wip` and on moq-transport draft-17+ with the MoQ Auth extension, `.grant()` reads the peer's `Grant` and `await .add(token) → AuthToken` presents a fresh token without reconnecting. diff --git a/py/moq-rs/moq/__init__.py b/py/moq-rs/moq/__init__.py index 883f1554055..ce0f868d6f3 100644 --- a/py/moq-rs/moq/__init__.py +++ b/py/moq-rs/moq/__init__.py @@ -55,8 +55,9 @@ AudioEncoderInput, AudioSampleFormat, Backoff, + ConnectionPhase, + ConnectionState, ConnectionStats, - ConnectionStatus, Datagram, ErrorScope, FetchGroupOptions, @@ -104,7 +105,8 @@ "Client", "CongestionControl", "ConnectionStats", - "ConnectionStatus", + "ConnectionPhase", + "ConnectionState", "Datagram", "Error", "ErrorScope", diff --git a/py/moq-rs/moq/client.py b/py/moq-rs/moq/client.py index 2fc83120bdc..ed7c2a77c8b 100644 --- a/py/moq-rs/moq/client.py +++ b/py/moq-rs/moq/client.py @@ -10,7 +10,6 @@ MoqClientConfig, MoqClientTls, MoqCongestionControl, - MoqError, MoqQuicConfig, MoqWebSocketConfig, moq_qlog_supported, @@ -64,7 +63,7 @@ class Client: The session automatically reconnects with backoff when the transport drops, and broadcasts consumed through it ride out the gap. Pass ``reconnect=False`` for a one-shot dial, or a :class:`Backoff` to tune the retry pacing; watch - :meth:`Session.status` for the connect/disconnect transitions. + :meth:`Session.state_changed` for the connect/disconnect transitions. ``versions`` restricts the protocol versions offered, most preferred first, spelled like ``"moq-lite-03"``; empty offers every supported version, which :func:`versions` lists. @@ -225,19 +224,9 @@ def _require_consumer(self) -> OriginConsumer: @property def session(self) -> Session | None: - """The established session, or `None` before connecting / after exit.""" + """The connecting or connected session, or `None` before connecting / after exit.""" return self._session - def failure(self) -> MoqError | None: - """Why entering the client is still dialing: the error that failed its latest - attempt, or ``None`` while nothing has failed or no connect is pending. - - A first dial that keeps failing and retrying never finishes ``async with``, so - poll this from another task to show the reason. Giving up for good raises from - ``async with`` instead. Once connected, :meth:`Session.failure` reports the - reconnects.""" - return None if self._inner is None else self._inner.failure() - def connect( url: str, diff --git a/py/moq-rs/moq/session.py b/py/moq-rs/moq/session.py index d3e3f86d602..6ffe9dda56a 100644 --- a/py/moq-rs/moq/session.py +++ b/py/moq-rs/moq/session.py @@ -1,16 +1,16 @@ -"""Session wrapper for an established MoQ connection.""" +"""Session wrapper for a MoQ connection, including its initial native dial.""" from __future__ import annotations -from moq_ffi import MoqAuth, MoqAuthToken, MoqBandwidth, MoqBandwidthConsumer, MoqError, MoqReservation, MoqSession +from moq_ffi import MoqAuth, MoqAuthToken, MoqBandwidth, MoqBandwidthConsumer, MoqReservation, MoqSession from .origin import OriginConsumer, OriginProducer from .publish import TrackDemand -from .types import ConnectionStats, ConnectionStatus, Grant +from .types import ConnectionState, ConnectionStats, Grant class Session: - """An established MoQ connection, returned by `Client` and `Request.accept()`. + """A MoQ connection, returned by `Client` and `Request.accept()`. Hold the session to keep the connection alive; dropping it closes the connection. As an async context manager it drains on a clean exit and @@ -41,40 +41,22 @@ async def closed(self) -> None: A client session resolves when its connection stops for good: it raises the terminal error when the connection gave up, and returns normally after a local :meth:`shutdown`/:meth:`cancel`. Transient drops the reconnect loop rides out - do not resolve this; watch :meth:`status` for those. A server-accepted session + do not resolve this; watch :meth:`state_changed` for those. A server-accepted session raises the session's close reason.""" await self._inner.closed() - async def status(self) -> ConnectionStatus: - """Wait for the connection status to differ from the one last reported. + def state(self) -> ConnectionState: + """Read the lifecycle phase, connect count, failure, version, and revision together.""" + return self._inner.state() - A client session reports ``CONNECTED`` first (the connect it was built from), - then follows the reconnect loop: ``DISCONNECTED`` while redialing, - ``CONNECTED`` again on success, ``MIGRATING`` during a GOAWAY handover. It - raises once the connection stops for good. A server-accepted session's only - transition is terminal: this waits for the close and raises its reason. + async def state_changed(self, after: int) -> ConnectionState: + """Wait for a revision different from ``after`` without sharing a watcher cursor. - This is the current status, not a queue of every edge: a drop that - reconnects before you ask again is coalesced away, so the outages it hides - are the ones that already healed. Do not count outages with it.""" - return await self._inner.status() - - def connects(self) -> int: - """How many times this session has connected: 1 for the connect that built it, one more - on each reconnect. A server-accepted session stays at 1. - - Pair it with :meth:`status` to log each reconnect by number; a - ``CONNECTED`` status whose count grew is a reconnect.""" - return self._inner.connects() - - def failure(self) -> MoqError | None: - """Why a client session is reconnecting: the error that ended the last - connection or failed the latest redial, or ``None`` once a connection lands. - - A redial that keeps failing never changes :meth:`status`, so poll this while - it reports ``DISCONNECTED`` to show the reason. Giving up for good raises from - :meth:`closed` instead. A server-accepted session always returns ``None``.""" - return self._inner.failure() + Pass the revision from this session's last snapshot. Changes between the read + and wait return immediately. The final snapshot reports ``CLOSED``; waiting + again at that revision raises the close reason. + """ + return await self._inner.state_changed(after) def cancel(self, code: int) -> None: """Close the session with the given error code.""" diff --git a/py/moq-rs/moq/types.py b/py/moq-rs/moq/types.py index 9c7333ea9a6..e774cbaee40 100644 --- a/py/moq-rs/moq/types.py +++ b/py/moq-rs/moq/types.py @@ -22,7 +22,10 @@ MoqAudioSampleFormat as AudioSampleFormat, ) from moq_ffi import ( - MoqConnectionStatus as ConnectionStatus, + MoqConnectionPhase as ConnectionPhase, +) +from moq_ffi import ( + MoqConnectionState as ConnectionState, ) from moq_ffi import ( MoqErrorScope as ErrorScope, @@ -78,7 +81,8 @@ "AudioSampleFormat", "Backoff", "ConnectionStats", - "ConnectionStatus", + "ConnectionPhase", + "ConnectionState", "Datagram", "ErrorScope", "Frame", diff --git a/py/moq-rs/tests/test_server.py b/py/moq-rs/tests/test_server.py index 1606ad3c44a..0319fc4f97f 100644 --- a/py/moq-rs/tests/test_server.py +++ b/py/moq-rs/tests/test_server.py @@ -32,6 +32,13 @@ def opus_head() -> bytes: ) +async def wait_phase(session: moq.Session, phase: moq.ConnectionPhase) -> moq.ConnectionState: + state = session.state() + while state.phase != phase: + state = await asyncio.wait_for(session.state_changed(state.revision), timeout=10) + return state + + async def test_server_client_roundtrip(): """Server publishes a broadcast; a client connects and receives a frame.""" async with moq.Server("127.0.0.1:0", tls_generate=["localhost"]) as server: @@ -125,8 +132,9 @@ async def accept_loop() -> None: ) as client: session = client.session assert session is not None - assert await session.status() == moq.ConnectionStatus.CONNECTED - assert session.failure() is None + state = await wait_phase(session, moq.ConnectionPhase.CONNECTED) + assert state.connects == 1 + assert session.state().failure is None assert session.stats().version is not None # Kill the transport under the client, like a relay restart. @@ -135,16 +143,16 @@ async def accept_loop() -> None: # Nothing accepts the redial until the gate opens, so DISCONNECTED # is still the current status when we ask for it. - assert await asyncio.wait_for(session.status(), timeout=10) == moq.ConnectionStatus.DISCONNECTED + state = await wait_phase(session, moq.ConnectionPhase.DISCONNECTED) # The drop's reason is recorded before the status moves. - assert session.failure() is not None + assert session.state().failure is not None assert session.stats().version is None # The client redials on its own; the accept loop serves it. regate.set() - while await asyncio.wait_for(session.status(), timeout=10) != moq.ConnectionStatus.CONNECTED: - pass - assert session.failure() is None + state = await wait_phase(session, moq.ConnectionPhase.CONNECTED) + assert state.connects == 2 + assert session.state().failure is None # A broadcast published only after the reconnect still arrives. broadcast = server.create_broadcast("after-reconnect") @@ -161,9 +169,8 @@ async def accept_loop() -> None: pass -async def test_client_failure_names_a_failing_first_dial(): - """A first dial that keeps failing never finishes ``async with``, so - ``Client.failure`` is the only place its reason shows while it retries.""" +async def test_session_state_names_a_failing_first_dial(): + """A first dial returns a session whose state reports each failed attempt.""" import socket # A socket that never answers holds the port, so each dial times out. @@ -183,24 +190,17 @@ async def test_client_failure_names_a_failing_first_dial(): timeout=timedelta(0), ), ) - assert client.failure() is None - - enter = asyncio.create_task(client.__aenter__()) - try: - - async def failure() -> moq.Error: - while (err := client.failure()) is None: - await asyncio.sleep(0.01) - return err - - err = await asyncio.wait_for(failure(), timeout=10) - assert isinstance(err, moq.Error.Connect) # type: ignore[attr-defined] - assert not enter.done() - finally: - enter.cancel() - with pytest.raises(asyncio.CancelledError): - await enter - assert client.failure() is None + async with client: + session = client.session + assert session is not None + state = session.state() + assert state.phase == moq.ConnectionPhase.CONNECTING + assert state.connects == 0 + for _ in range(2): + state = await asyncio.wait_for(session.state_changed(state.revision), timeout=10) + assert isinstance(state.failure, moq.Error.Connect) # type: ignore[attr-defined] + assert state.connects == 0 + session.cancel(0) async def test_server_close_releases_port(): @@ -233,17 +233,13 @@ async def reject_loop() -> None: once=True, ) ) - # The rejection races the optimistic connect: it surfaces either as a - # connect error or as the session's terminal close. MoqError is an - # Exception subclass at runtime; UniFFI's generated code rebinds the - # name so the static checker doesn't see it. - try: - session = await asyncio.wait_for(client.connect(f"https://{server.local_addr}"), timeout=5.0) - except moq_ffi.MoqError: # type: ignore[misc] - pass - else: - with pytest.raises(moq_ffi.MoqError): # type: ignore[arg-type] - await asyncio.wait_for(session.closed(), timeout=5.0) + # Network rejection belongs to the immediately returned session. + session = await asyncio.wait_for(client.connect(f"https://{server.local_addr}"), timeout=5.0) + with pytest.raises(moq_ffi.MoqError): # type: ignore[arg-type] + await asyncio.wait_for(session.closed(), timeout=5.0) + state = session.state() + assert state.phase == moq_ffi.MoqConnectionPhase.CLOSED + assert state.failure is not None finally: reject_task.cancel() try: diff --git a/quest/m1/api-audit/README.md b/quest/m1/api-audit/README.md index 078f474cba4..9d39287b0e7 100644 --- a/quest/m1/api-audit/README.md +++ b/quest/m1/api-audit/README.md @@ -72,7 +72,6 @@ Rejected in planning: - [The origin announces](/quest/m1/api-audit/announce-owner.md) - a broadcast producer cannot announce; the origin hands out the announcement, so `Prepared` and standalone broadcasts lose methods that always fail - [Unpublish what nothing uses](/quest/m1/api-audit/unpublish.md) - packages, features, and listeners with no consumer stop shipping or stop being on by default - [Container formats name inputs](/quest/m1/api-audit/container-format.md) - `ContainerFormat` names what is parsed, never how it is packaged; `ContainerStream` and TS passthrough internals are gone -- [Binding connection state](/quest/m1/api-audit/binding-state.md) - one `state()` snapshot and `state_changed()` replace `status`, `connects`, and both `failure` polls - [moq-net exports with a consumer](/quest/m1/api-audit/net-exports.md) - Rust and JS model exports without a consumer go private, wrong ones are deleted, and JS names mirror Rust - [One clean close](/quest/m1/api-audit/clean-close.md) - a clean session close has one spelling and failures are recorded inside moq-net - [Session limits only where needed](/quest/m1/api-audit/session-limits.md) - `session::Limits` keeps only bounds that nothing else enforces, and its documented example compiles diff --git a/quest/m1/api-audit/binding-state.md b/quest/m1/api-audit/binding-state.md deleted file mode 100644 index 7c5221d14b5..00000000000 --- a/quest/m1/api-audit/binding-state.md +++ /dev/null @@ -1,30 +0,0 @@ -# [M] Binding connection state - -## Goal - -A binding caller watches one connection state instead of combining a -blocking status watcher, a polling loop, a reconnect counter, and terminal -closure. `MoqSession::state()` returns a snapshot (presence, connect count, -last failure, version) and `state_changed()` waits for the next one, -mirroring moq-tokio's `Monitor::snapshot`. `status()`, `connects()`, and both -`failure()` polls are gone. - -## Plan - -Decided 2026-10-22 (API audit). `rs/moq-ffi/src/session.rs` has -`MoqClient::failure` (#6131) and `MoqSession::failure` (#5723), both new and -polled because successive failures do not change `status()`. OBS combines -all of them (`cpp/obs/src/moq-output.cpp`, `moq-source.cpp`). Kotlin, Dart, -and Go hide the `Client`, so the first-dial failure is unreachable there. - -- `MoqClient::connect` returns the session at once in a connecting presence, - so the pre-session failure is part of the same state and - `MoqClient::failure` goes away. -- Name fields after moq-tokio's `Monitor` (`presence`, not `status`). -- Update every wrapper, OBS, and `doc/lib/*`. - -Public API: moq-ffi, moq-c, every wrapper, OBS breaking. Wire: none. - -## Related - -- [Go first-dial failure](/quest/m2/go-first-dial-failure.md) - becomes unnecessary once the state carries the first failure; delete it when this lands diff --git a/quest/m1/auth/bindings-polish.md b/quest/m1/auth/bindings-polish.md index d3ded2a22a6..e6b4850df42 100644 --- a/quest/m1/auth/bindings-polish.md +++ b/quest/m1/auth/bindings-polish.md @@ -30,7 +30,3 @@ Public API: Swift additive. Wire: none. - [Auth outlives its session](/quest/m1/auth/issuer.md) - one handle per connection, which the enum collapse needs - [Token in band](/quest/m1/auth/token-in-band.md) - tokens that ride SETUP, which the OBS reconnect needs - -## Related - -- [First dial failures in Go](/quest/m2/go-first-dial-failure.md) - the m2 half of this binding cleanup diff --git a/quest/m1/c/package.md b/quest/m1/c/package.md index bf934d9f4da..90e7ae3c921 100644 --- a/quest/m1/c/package.md +++ b/quest/m1/c/package.md @@ -32,6 +32,7 @@ under the same names. target of `rs/moq-ffi` changes, and its `moq.h` C ABI) point at the generated package instead; update `AGENTS.md` in this quest. -The hand-written `moq_session_failure` names a retrying first dial; the -generated package must keep that, through the moq-ffi report added in -[moq-dev/moq#6131](https://github.com/moq-dev/moq/pull/6131). +The hand-written session callback delivers a `moq_connection_state` +snapshot naming a retrying first dial, ending with a terminal closed +snapshot; the generated package must keep both, through moq-ffi's `state()` +and `state_changed()`. diff --git a/quest/m2/README.md b/quest/m2/README.md index e13ab37eb74..d87f044812f 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -100,7 +100,6 @@ lite-07; bitrate enforcement is not part of this release. - [Rust releases publish through OIDC](/quest/m2/release-rs-oidc.md) - release-plz publishes with trusted publishing and `CARGO_REGISTRY_TOKEN` is revoked - [Go module proxy](/quest/m2/go-module-proxy.md) - `moq.dev/moq-ffi` ships from a static GOPROXY we host, so its staticlibs stop growing git history by ~61 MiB per release - [Go per-platform lib modules](/quest/m2/go-ffi-platform-modules.md) - a Go build downloads only the host's staticlib, and `go mod vendor` works -- [Go first dial failure](/quest/m2/go-first-dial-failure.md) - Go reports why a first dial fails, and the Kotlin and Dart docs name `client.failure()` correctly - [Dart on iOS](/quest/m2/dart-ios.md) - prove the shipped iOS native asset actually loads on a device, which no CI can - [Mobile completion](/quest/m2/mobile-completion.md) - verify the Swift and Kotlin bindings over Rust-owned capture - [Browser publishing paths under test](/quest/m2/publish-firefox.md) - the media harness publishes from Firefox too, covering the worker capture and video-element fallback Chromium never takes diff --git a/quest/m2/audit-docs.md b/quest/m2/audit-docs.md index 54ef0e1bec7..6dca30e50b1 100644 --- a/quest/m2/audit-docs.md +++ b/quest/m2/audit-docs.md @@ -60,10 +60,10 @@ freshest. Baselines: `gst-inspect-1.0` of a debug `moq-gst` build lists every element and pad property `doc/bin/gstreamer.md` names. - Cross-Package Sync: walked from `9b90cdd569` through `7d2a91fe66`. Walk the - next run from there. Go has no `Client` failure accessor because `Dial` - returns only once connected. The newer 2026-10-21 maintainer decision - plans that gap in [Go first-dial failure](/quest/m2/go-first-dial-failure.md); - verify its accessor and the Kotlin/Dart wording when that quest lands. + next run from there. At that baseline, Go could not observe first-dial + failures because `Dial` returned only once connected. Every binding now + returns a connecting session with one coherent `state()` snapshot; verify + first-dial failure observation and Kotlin/Dart wording against that API. ## Required diff --git a/quest/m2/go-first-dial-failure.md b/quest/m2/go-first-dial-failure.md deleted file mode 100644 index 721071f788c..00000000000 --- a/quest/m2/go-first-dial-failure.md +++ /dev/null @@ -1,20 +0,0 @@ -# [XS] Go reports why a first dial fails - -## Goal - -The Go wrapper reports why a client's first dial is failing, as Python, -Swift, Kotlin, and Dart do since -[moq-dev/moq#6131](https://github.com/moq-dev/moq/pull/6131), and the Kotlin -and Dart docs describe `client.failure()` on the object that actually has it. - -## Plan - -Decided 2026-10-21 with the maintainer: m2. #6131 left Go without a `Client` -failure accessor; add it the way the other wrappers expose it. - -[moq-dev/moq#6170](https://github.com/moq-dev/moq/pull/6170) found that -`doc/lib/kt/index.md` and `doc/lib/dart/index.md` say `client.failure()` -while their examples only use `Moq.connect`, which never hands back a -`Client` before connecting. Align that wording. - -Public API: Go additive. Wire: none. diff --git a/rs/moq-c/MIGRATE.md b/rs/moq-c/MIGRATE.md index 11fafe9439f..2139f8017c6 100644 --- a/rs/moq-c/MIGRATE.md +++ b/rs/moq-c/MIGRATE.md @@ -4,6 +4,13 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Sessions report a lifecycle snapshot + +`moq_session_connect` and `moq_session_request_accept` take a `moq_state_callback` instead of a `moq_status_callback`: `void on_state(void *user_data, const moq_connection_state *state)`. +Each change delivers a `moq_connection_state` with `phase`, `connects`, `failure`, and the live `protocol`; copy what you keep, since it is valid only during the callback. +Read `state->connects` where you read a positive status code. A failed dial or dropped connection now fires the callback with a negative `failure`, so drop your `moq_session_failure` polling; `moq_error()` describes it during the callback. +The terminal call has phase `MOQ_CONNECTION_PHASE_CLOSED`, with `failure` zero after a requested close or the error that ended the session, where the terminal status code used to be. Release `user_data` there, as before. + ### Exact encoder rates and publication options `moq_video_encoder_input.framerate` is now `moq_video_frame_rate { numerator, diff --git a/rs/moq-c/README.md b/rs/moq-c/README.md index 43d5ee36ff4..ced910f6830 100644 --- a/rs/moq-c/README.md +++ b/rs/moq-c/README.md @@ -30,7 +30,7 @@ The library exposes the following C functions, see [api.rs](src/api.rs) for full int32_t moq_log_level(const char *level, uintptr_t level_len); // Session -int32_t moq_session_connect(const char *url, uintptr_t url_len, const moq_client_config *config, uint32_t origin_publish, uint32_t origin_consume, moq_status_callback on_status, void *user_data); +int32_t moq_session_connect(const char *url, uintptr_t url_len, const moq_client_config *config, uint32_t origin_publish, uint32_t origin_consume, moq_state_callback on_state, void *user_data); moq_client_config moq_client_defaults(void); int32_t moq_session_close(uint32_t session); int32_t moq_session_bandwidth(uint32_t session); @@ -47,7 +47,7 @@ int32_t moq_server_fingerprints(uint32_t server, moq_string *dst, uintptr_t coun int32_t moq_server_close(uint32_t server); int32_t moq_session_request_path(uint32_t request, moq_string *dst); int32_t moq_session_request_query(uint32_t request, moq_string *dst); -int32_t moq_session_request_accept(uint32_t request, uint32_t origin_publish, uint32_t origin_consume, moq_status_callback on_status, void *user_data); +int32_t moq_session_request_accept(uint32_t request, uint32_t origin_publish, uint32_t origin_consume, moq_state_callback on_state, void *user_data); int32_t moq_session_request_reject(uint32_t request, uint16_t code); int32_t moq_session_request_free(uint32_t request); diff --git a/rs/moq-c/c-tests/doc-samples.h b/rs/moq-c/c-tests/doc-samples.h index 2e28c8ffa3f..1cabb56e77e 100644 --- a/rs/moq-c/c-tests/doc-samples.h +++ b/rs/moq-c/c-tests/doc-samples.h @@ -13,9 +13,9 @@ static size_t url_len; static uint32_t origin; static void *user_data; -static void on_status(void *user_data, int32_t code) { +static void on_state(void *user_data, const moq_connection_state *state) { (void)user_data; - (void)code; + (void)state; } static int fail(const char *reason) { diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index ee7c75f0f4b..cc7a47a03ce 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -857,6 +857,40 @@ pub struct moq_announce_event { pub kind: moq_announce_kind, } +/// Where a session is in its lifecycle, reported by [moq_connection_state]. +#[repr(C)] +#[expect(non_camel_case_types, reason = "C ABI type names match moq.h")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum moq_connection_phase { + /// No connection has been established yet. + MOQ_CONNECTION_PHASE_CONNECTING = 0, + /// A connection is serving. + MOQ_CONNECTION_PHASE_CONNECTED = 1, + /// No connection is serving while the session redials. + MOQ_CONNECTION_PHASE_DISCONNECTED = 2, + /// The old connection serves while its replacement dials. + MOQ_CONNECTION_PHASE_MIGRATING = 3, + /// The session has stopped for good: the terminal snapshot. + MOQ_CONNECTION_PHASE_CLOSED = 4, +} + +/// One coherent snapshot of a session's lifecycle, delivered to its `moq_state_callback`. +/// +/// The struct and its `protocol` are valid only during the callback, so copy what you keep. +#[repr(C)] +pub struct moq_connection_state { + /// The lifecycle phase. + pub phase: moq_connection_phase, + /// How many connections have been established, including reconnects. + pub connects: u64, + /// Zero, or the negative code of the latest failed dial, dropped connection, or terminal + /// error, which [moq_error] and [moq_error_protocol] describe during the callback. A + /// connect clears it; a terminal zero is a clean close. + pub failure: i32, + /// The live connection's negotiated draft name, or empty while none is serving. + pub protocol: moq_string, +} + /// Statistics and protocol sampled from the same connection by [moq_session_snapshot]. #[repr(C)] pub struct moq_connection_snapshot { @@ -1292,7 +1326,7 @@ unsafe fn connect_session( config: *const moq_client_config, origin_publish: u32, origin_consume: u32, - on_status: ffi::moq_status_callback, + on_state: ffi::moq_state_callback, user_data: *mut c_void, ) -> Result { let url = ffi::parse_url(url, url_len)?; @@ -1310,7 +1344,7 @@ unsafe fn connect_session( (publish, consume) }; - let callback = unsafe { ffi::OnStatus::new(user_data, on_status)? }; + let callback = unsafe { ffi::OnState::new(user_data, on_state)? }; let request = Connect { config, url, @@ -1345,18 +1379,15 @@ unsafe fn connect_session( /// Published broadcasts are re-announced and consumers re-subscribed on each reconnect, /// since the origins outlive the underlying connection. /// -/// `on_status` reports the session lifecycle through its status code: -/// - `> 0` on every (re)connect, carrying the connect count (`1` = first connect, -/// `2` = first reconnect, and so on), so a reconnect is distinguishable from the -/// initial connect. May fire repeatedly. Transient disconnects are not reported. -/// - `0` when the session is closed cleanly via [moq_session_close] (terminal). -/// - a negative error code if reconnection permanently gives up, e.g. the backoff -/// timeout is exceeded (terminal). +/// `on_state` receives a [moq_connection_state] whenever the lifecycle changes: each +/// connect, drop, migration, and failed dial, carrying the phase, the connect count, and +/// why the latest attempt failed. Changes that land together arrive as one snapshot. /// -/// After a terminal (`<= 0`) status, `on_status` is never called again and `user_data` -/// is never touched again, so that final callback is the point to release `user_data`. -/// The terminal `0` fires even after [moq_session_close], so do not free `user_data` on -/// the close call itself. +/// The last call has phase `MOQ_CONNECTION_PHASE_CLOSED`, with `failure` zero after +/// [moq_session_close] or the negative code that made reconnecting give up. By then the +/// session handle is already released, and `on_state` and `user_data` are never touched +/// again, so that terminal snapshot is the point to release `user_data`. It fires even +/// after [moq_session_close], so do not free `user_data` on the close call itself. /// /// # Safety /// - The caller must ensure that url is a valid pointer to url_len bytes of data. @@ -1364,7 +1395,7 @@ unsafe fn connect_session( /// non-NULL pointer inside it must be valid for its paired length, and all of /// them must stay alive for the duration of this call: the config is read /// here, not copied by whoever filled it in. -/// - The caller must keep `user_data` valid until the terminal (`<= 0`) `on_status` callback. +/// - The caller must keep `user_data` valid until the terminal `on_state` callback. #[unsafe(no_mangle)] pub unsafe extern "C" fn moq_session_connect( url: *const c_char, @@ -1372,7 +1403,7 @@ pub unsafe extern "C" fn moq_session_connect( config: *const moq_client_config, origin_publish: u32, origin_consume: u32, - on_status: ffi::moq_status_callback, + on_state: ffi::moq_state_callback, user_data: *mut c_void, ) -> i32 { ffi::enter(move || unsafe { @@ -1382,7 +1413,7 @@ pub unsafe extern "C" fn moq_session_connect( config, origin_publish, origin_consume, - on_status, + on_state, user_data, ) }) @@ -1391,12 +1422,11 @@ pub unsafe extern "C" fn moq_session_connect( /// Request that a session shut down. /// /// Returns immediately: zero on success, or a negative code if the session is -/// unknown or already closing. Does NOT free `user_data`. The -/// [moq_session_connect] `on_status` callback still fires once more with a -/// terminal `0` (or a negative error) once the close has reached the peer, after -/// at most a second of draining, and that final callback is where `user_data` -/// should be released. Safe to call from any thread, including from -/// within `on_status`. +/// unknown or already closing. Does NOT free `user_data`. The session's +/// `on_state` callback still fires once more with its terminal snapshot once the +/// close has reached the peer, after at most a second of draining, and that final +/// callback is where `user_data` should be released. Safe to call from any thread, +/// including from within `on_state`. #[unsafe(no_mangle)] pub extern "C" fn moq_session_close(session: u32) -> i32 { ffi::enter(move || { @@ -1454,28 +1484,6 @@ pub unsafe extern "C" fn moq_session_snapshot(session: u32, dst: *mut moq_connec }) } -/// Why a dialed session is reconnecting. -/// -/// Returns zero while nothing has failed since the last connect, including for a -/// server-accepted session, which never reconnects. Otherwise returns the negative code -/// of the error that ended the last connection or failed the latest dial, recorded like -/// any failed call so [moq_error] and [moq_error_protocol] describe it. Also negative -/// when the handle is unknown. -/// -/// A dial that keeps failing never fires `on_status`, so poll this while -/// [moq_session_snapshot] reports the session offline. Giving up for good arrives -/// through `on_status` instead. -#[unsafe(no_mangle)] -pub extern "C" fn moq_session_failure(session: u32) -> i32 { - ffi::enter(move || { - let session = ffi::parse_id(session)?; - match State::lock().session.failure(session)? { - Some(err) => Err(err), - None => Ok(()), - } - }) -} - /// Settings for [moq_server_listen]. /// /// Zero it and set only what you need; new settings are appended, and a zeroed @@ -1667,28 +1675,27 @@ pub unsafe extern "C" fn moq_session_request_query(request: u32, dst: *mut moq_s /// negative code on failure (leaving the request unanswered). The session works with every /// `moq_session_*` call; stats and bandwidth report offline until the handshake completes. /// -/// `on_status` reports the session lifecycle: -/// - `1` once the handshake completes. An accepted session is a single connection, so it -/// never reconnects and never reports more. -/// - `0` when closed via [moq_session_close] (terminal). -/// - a negative error code if the handshake fails or the peer closes the session; read -/// [moq_error_protocol] for the peer's close code (terminal). +/// `on_state` reports the lifecycle like [moq_session_connect]'s: one connected snapshot +/// once the handshake completes, since an accepted session is a single connection that +/// never reconnects, then the terminal closed snapshot. Its `failure` is zero only after +/// [moq_session_close], and otherwise the negative code of a failed handshake or the +/// peer's close; read [moq_error_protocol] during the callback for the peer's close code. /// /// # Safety -/// - The caller must keep `user_data` valid until the terminal (`<= 0`) `on_status` callback. +/// - The caller must keep `user_data` valid until the terminal `on_state` callback. #[unsafe(no_mangle)] pub unsafe extern "C" fn moq_session_request_accept( request: u32, origin_publish: u32, origin_consume: u32, - on_status: ffi::moq_status_callback, + on_state: ffi::moq_state_callback, user_data: *mut c_void, ) -> i32 { ffi::enter(move || { let request = ffi::parse_id(request)?; let origin_publish = ffi::parse_id_optional(origin_publish)?; let origin_consume = ffi::parse_id_optional(origin_consume)?; - let callback = unsafe { ffi::OnStatus::new(user_data, on_status)? }; + let callback = unsafe { ffi::OnState::new(user_data, on_state)? }; let mut state = State::lock(); let publish = origin_publish.map(|id| state.origin.get(id)).transpose()?.cloned(); diff --git a/rs/moq-c/src/ffi.rs b/rs/moq-c/src/ffi.rs index bd0f63ab4cb..c942f85bb34 100644 --- a/rs/moq-c/src/ffi.rs +++ b/rs/moq-c/src/ffi.rs @@ -12,6 +12,10 @@ use crate::{Error, Id, moq_protocol_error}; #[expect(non_camel_case_types, reason = "C ABI type names match moq.h")] pub type moq_status_callback = Option; +/// A callback receiving each session lifecycle change; the `MOQ_CONNECTION_PHASE_CLOSED` one is terminal. +#[expect(non_camel_case_types, reason = "C ABI type names match moq.h")] +pub type moq_state_callback = Option; + pub static RUNTIME: LazyLock = LazyLock::new(|| { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() @@ -225,6 +229,37 @@ impl OnStatus { unsafe impl Send for OnStatus {} +/// A [moq_state_callback] and its user data. +#[derive(Clone, Copy)] +pub struct OnState { + user_data: *mut c_void, + on_state: extern "C" fn(user_data: *mut c_void, state: *const crate::moq_connection_state), +} + +impl OnState { + /// Wrap a C state callback. + /// + /// # Safety + /// - The caller must keep `user_data` valid until the terminal callback. + pub unsafe fn new(user_data: *mut c_void, on_state: moq_state_callback) -> Result { + Ok(Self { + user_data, + on_state: on_state.ok_or(Error::InvalidPointer)?, + }) + } + + /// Deliver one snapshot, recording its failure first so the callback can read `moq_error()`. + pub fn call(&self, state: &crate::session::Lifecycle) { + if let Some(failure) = &state.failure { + record(failure); + } + let state = state.to_c(); + (self.on_state)(self.user_data, &state); + } +} + +unsafe impl Send for OnState {} + /// Types that can be converted to C-compatible return codes. pub trait ReturnCode { /// Convert to an i32 status code. @@ -332,7 +367,12 @@ thread_local! { /// Called at the FFI boundary (sync return and callback dispatch) right before /// the numeric code is produced, so the conversion in `code()` stays pure. fn record_error(ret: &C) { - let Some(err) = ret.error() else { return }; + if let Some(err) = ret.error() { + record(err); + } +} + +fn record(err: &Error) { // CString::new fails only on an interior NUL, which our messages never // contain; skip storing rather than truncating if it ever happens. if let Ok(msg) = CString::new(err.to_string()) { diff --git a/rs/moq-c/src/lib.rs b/rs/moq-c/src/lib.rs index 9ddd1b4b9bc..fc4c6d8e66c 100644 --- a/rs/moq-c/src/lib.rs +++ b/rs/moq-c/src/lib.rs @@ -38,7 +38,7 @@ pub use api::*; pub use audio::*; pub use bandwidth::*; pub use error::*; -pub use ffi::moq_status_callback; +pub use ffi::{moq_state_callback, moq_status_callback}; pub use id::*; pub use video::*; diff --git a/rs/moq-c/src/session.rs b/rs/moq-c/src/session.rs index df02aa46a63..eef6651fd1c 100644 --- a/rs/moq-c/src/session.rs +++ b/rs/moq-c/src/session.rs @@ -1,17 +1,65 @@ use std::sync::Arc; -use anyhow::Context; +use moq_tokio::connection::Phase; use url::Url; use crate::task::Task; -use crate::{Error, Id, NonZeroSlab, State, ffi}; +use crate::{Error, Id, NonZeroSlab, State, ffi, moq_connection_phase, moq_connection_state, moq_string}; /// A session task and the connection backing its handle. struct TaskEntry { - task: Task, + task: Task, link: Link, } +/// One lifecycle snapshot, converted to a [`moq_connection_state`] for the callback. +pub(crate) struct Lifecycle { + phase: moq_connection_phase, + connects: u64, + pub failure: Option, + version: Option, +} + +impl Lifecycle { + fn observed(state: moq_tokio::connection::Observation) -> Self { + Self { + phase: match state.phase { + Phase::Connecting => moq_connection_phase::MOQ_CONNECTION_PHASE_CONNECTING, + Phase::Connected => moq_connection_phase::MOQ_CONNECTION_PHASE_CONNECTED, + Phase::Disconnected => moq_connection_phase::MOQ_CONNECTION_PHASE_DISCONNECTED, + Phase::Migrating => moq_connection_phase::MOQ_CONNECTION_PHASE_MIGRATING, + Phase::Closed => moq_connection_phase::MOQ_CONNECTION_PHASE_CLOSED, + }, + connects: state.connects, + failure: state.failure.map(map_connect_error), + version: state.version, + } + } + + /// The terminal snapshot: `res` is the session's final result. + fn closed(connects: u64, res: Result<(), Error>) -> Self { + Self { + phase: moq_connection_phase::MOQ_CONNECTION_PHASE_CLOSED, + connects, + failure: res.err(), + version: None, + } + } + + pub fn to_c(&self) -> moq_connection_state { + let protocol = self.version.map_or("", |version| version.as_str()); + moq_connection_state { + phase: self.phase, + connects: self.connects, + failure: self.failure.as_ref().map_or(0, ffi::ReturnCode::code), + protocol: moq_string { + data: protocol.as_ptr().cast(), + len: protocol.len(), + }, + } + } +} + /// What backs a session handle. enum Link { /// A dialed connection: a loop that redials, so it is offline between connections. @@ -35,7 +83,7 @@ pub(crate) struct Connect { pub url: Url, pub publish: Option, pub consume: Option, - pub callback: ffi::OnStatus, + pub callback: ffi::OnState, } impl Connect { @@ -70,7 +118,7 @@ pub(crate) struct PreparedConnect { url: Url, publish: Option, consume: Option, - callback: ffi::OnStatus, + callback: ffi::OnState, } #[derive(Default)] @@ -92,9 +140,10 @@ impl Session { // Build the reconnect loop up front so we can grab a monitor for it // before moving it into the spawned task. let reconnect = client.connect(url); + let monitor = reconnect.monitor(); let link = Link::Dialed { connection: reconnect.clone(), - monitor: reconnect.monitor(), + monitor: monitor.clone(), }; let (task, closed) = Task::new(callback); @@ -113,7 +162,7 @@ impl Session { tokio::select! { // close() requested: drain what the session queued, then close it. _ = closed => reconnect.clone().close().await.map_err(map_connect_error), - res = Self::report(callback, reconnect.clone()) => res, + res = Self::report(callback, &reconnect, &monitor) => res, } }))) .await; @@ -127,25 +176,29 @@ impl Session { }) .await; - // Deliver one final terminal callback (0 = closed, < 0 = error), then - // drop the entry. Pull it out from under the lock so the callback never + // Deliver the terminal snapshot after dropping the entry, so the handle is gone + // once the caller sees it. Pulled out from under the lock so the callback never // runs while held. let entry = State::lock().session.task.remove(id); if let Some(entry) = entry { - entry.task.callback.call(res); + let connects = match &entry.link { + Link::Dialed { monitor, .. } => monitor.state().connects, + Link::Accepted(_) => unreachable!("a dialed entry"), + }; + entry.task.callback.call(&Lifecycle::closed(connects, res)); } }); Ok(id) } - /// Complete SETUP for an incoming session, reporting `1` once established. + /// Complete SETUP for an incoming session, reporting it connected once established. pub fn accept( &mut self, request: moq_tokio::server::Request, publish: Option, consume: Option, - callback: ffi::OnStatus, + callback: ffi::OnState, ) -> Result { let mut request = request; if let Some(publish) = &publish { @@ -179,6 +232,10 @@ impl Session { let entry = State::lock().session.task.remove(id); if let Some(entry) = entry { + let connects = match &entry.link { + Link::Accepted(accepted) => u64::from(accepted.is_some()), + Link::Dialed { .. } => unreachable!("an accepted entry"), + }; // Close the transport now rather than whenever the last clone drops. if let Link::Accepted(Some(accepted)) = &entry.link && let Err(error) = ffi::run(async { @@ -190,7 +247,7 @@ impl Session { res = Err(error); } let res = publish_driver.check().and_then(|()| consume_driver.check()).and(res); - entry.task.callback.call(res); + entry.task.callback.call(&Lifecycle::closed(connects, res)); } }); @@ -198,7 +255,7 @@ impl Session { } /// Establish an accepted session, publish it to the entry, and wait for it to close. - async fn serve(id: Id, callback: ffi::OnStatus, request: moq_tokio::server::Request) -> Result<(), Error> { + async fn serve(id: Id, callback: ffi::OnState, request: moq_tokio::server::Request) -> Result<(), Error> { let (session, driver) = request.ok().await.map_err(map_connect_error)?; let driver = ffi::Background::new(async move { match driver.await { @@ -216,7 +273,12 @@ impl Session { } // A server-accepted session is a single transport, so it only ever connects once. - callback.call(1); + callback.call(&Lifecycle { + phase: moq_connection_phase::MOQ_CONNECTION_PHASE_CONNECTED, + connects: 1, + failure: None, + version: Some(session.version()), + }); driver.finished().await?; Err(session.closed().await.into()) } @@ -269,35 +331,31 @@ impl Session { } } - /// Why a dialed session is reconnecting, or `None` while nothing has failed since the - /// last connect. A server-accepted session never reconnects, so it is always `None`. + /// Deliver each lifecycle change until the connection stops, then return its result. /// - /// Errors with [`Error::SessionNotFound`] if the handle is unknown. - pub fn failure(&self, id: Id) -> Result, Error> { - Ok(match self.link(id)? { - Link::Dialed { monitor, .. } => monitor.failure().map(map_connect_error), - Link::Accepted(_) => None, - }) - } - - /// Forward connect counts to the status callback until the reconnect loop stops. - /// - /// Returns the terminal error via `?`. Disconnects aren't reported: status 0 is reserved for a - /// clean close (delivered as the terminal callback once the task ends). - async fn report(callback: ffi::OnStatus, mut reconnect: moq_tokio::Connection) -> Result<(), Error> { - let mut connects: u64 = 0; - loop { - if let moq_tokio::Status::Connected = reconnect.status().await.map_err(map_connect_error)? { - connects += 1; - // Positive status carries the connect count, so callers can tell a - // reconnect (>1) from the first connect (1). No lock is held, so the C - // callback is free to re-enter moq-c. - let code = i32::try_from(connects) - .context("connect count exceeded i32::MAX") - .map_err(|err| Error::Connect(Arc::new(err)))?; - callback.call(code); + /// Changes coalesce: a snapshot is the state when the callback runs, not every step + /// between. No lock is held, so the C callback is free to re-enter moq-c. + async fn report( + callback: ffi::OnState, + connection: &moq_tokio::Connection, + monitor: &moq_tokio::connection::Monitor, + ) -> Result<(), Error> { + // The loop may have moved before we got here; the untouched initial state says nothing. + let mut state = monitor.state(); + let initial = state.phase == Phase::Connecting && state.connects == 0 && state.failure.is_none(); + if !initial && state.phase != Phase::Closed { + callback.call(&Lifecycle::observed(state.clone())); + } + while state.phase != Phase::Closed { + let Ok(next) = monitor.state_changed(state.revision).await else { + break; + }; + state = next; + if state.phase != Phase::Closed { + callback.call(&Lifecycle::observed(state.clone())); } } + connection.closed().await.map_err(map_connect_error) } pub fn close(&mut self, id: Id) -> Result<(), Error> { diff --git a/rs/moq-c/src/task.rs b/rs/moq-c/src/task.rs index 2e41f6bb531..58fde665388 100644 --- a/rs/moq-c/src/task.rs +++ b/rs/moq-c/src/task.rs @@ -10,14 +10,14 @@ use crate::{Error, Id, NonZeroSlab, State}; /// `close` is an `Option` so closing can drop just the sender without removing the /// entry or revoking the callback. The task delivers one final terminal callback and /// then removes itself, so `user_data` stays valid until that callback fires. -pub(crate) struct Task { +pub(crate) struct Task { close: Option>, - pub callback: OnStatus, + pub callback: C, } -impl Task { +impl Task { /// An entry, plus the receiver its task watches for [`Self::close`]. - pub fn new(callback: OnStatus) -> (Self, oneshot::Receiver<()>) { + pub fn new(callback: C) -> (Self, oneshot::Receiver<()>) { let (close, closed) = oneshot::channel(); let task = Self { close: Some(close), diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index 0f058150559..a07199245b5 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -171,6 +171,85 @@ extern "C" fn channel_callback(user_data: *mut c_void, code: i32) { /// FFI callback for tests that only inspect the registrar's immediate return code. extern "C" fn ignore_callback(_user_data: *mut c_void, _code: i32) {} +/// A [moq_connection_state] copied out of an `on_state` callback. +#[derive(Debug)] +struct Seen { + phase: moq_connection_phase, + connects: u64, + failure: i32, + /// What `moq_error` said about `failure` during the callback. + error: Option, + /// What `moq_error_protocol` said about `failure` during the callback. + protocol: Option, + version: String, +} + +/// Collects every snapshot a session's `on_state` delivers. +struct States { + rx: mpsc::Receiver, + ptr: *mut c_void, +} + +impl States { + fn new() -> Self { + let (tx, rx) = mpsc::channel(); + let ptr = Box::into_raw(Box::new(tx)) as *mut c_void; + Self { rx, ptr } + } + + fn recv(&self) -> Seen { + self.rx.recv_timeout(TIMEOUT).expect("state callback timed out") + } + + /// Skip to the terminal snapshot, which must be the last one. + fn recv_terminal(&self) -> Seen { + loop { + let seen = self.recv(); + if seen.phase == moq_connection_phase::MOQ_CONNECTION_PHASE_CLOSED { + assert!( + self.rx.recv_timeout(Duration::from_millis(50)).is_err(), + "a snapshot followed the terminal one" + ); + return seen; + } + } + } +} + +impl Drop for States { + fn drop(&mut self) { + unsafe { drop(Box::from_raw(self.ptr as *mut mpsc::Sender)) }; + } +} + +extern "C" fn state_callback(user_data: *mut c_void, state: *const moq_connection_state) { + let tx = unsafe { &*(user_data as *const mpsc::Sender) }; + let state = unsafe { &*state }; + let mut protocol = moq_protocol_error { + scope: 0, + code: 0, + kind: 0, + }; + let failed = state.failure < 0; + let error = failed.then(|| { + unsafe { std::ffi::CStr::from_ptr(moq_error()) } + .to_string_lossy() + .into_owned() + }); + let protocol = (failed && unsafe { moq_error_protocol(&mut protocol) } == 0).then_some(protocol); + let _ = tx.send(Seen { + phase: state.phase, + connects: state.connects, + failure: state.failure, + error, + protocol, + version: borrowed_string(state.protocol.data, state.protocol.len).unwrap_or_default(), + }); +} + +/// FFI state callback for tests that only inspect the immediate return code. +extern "C" fn ignore_state(_user_data: *mut c_void, _state: *const moq_connection_state) {} + /// Build a valid OpusHead init buffer (RFC 7845 §5.1). fn opus_head() -> Vec { let mut head = Vec::with_capacity(19); @@ -4928,7 +5007,7 @@ fn session_connect_invalid_url() { #[test] fn session_connect_and_close() { - let cb = Callback::new(); + let cb = States::new(); let url = b"moqt://localhost:1"; let session = id(unsafe { moq_session_connect( @@ -4937,22 +5016,25 @@ fn session_connect_and_close() { std::ptr::null(), 0, 0, - Some(channel_callback), + Some(state_callback), cb.ptr, ) }); - // close() requests shutdown; the task still delivers exactly one terminal - // callback (0 = clean close, or a negative connect error), after which - // user_data is safe to free. + // close() requests shutdown; the task still delivers exactly one terminal snapshot, after + // which user_data is safe to free and the handle is already gone. assert_eq!(moq_session_close(session), 0); - assert!(cb.recv() <= 0, "session close delivers a terminal code"); + let terminal = cb.recv_terminal(); + assert_eq!(terminal.failure, 0, "a requested close is clean: {terminal:?}"); + assert!( + moq_session_close(session) < 0, + "the terminal snapshot released the handle" + ); } -/// A dial that keeps failing never fires `on_status`, so `moq_session_failure` is the only -/// place its reason shows while the loop retries. +/// Every failed dial reaches `on_state` while the loop retries, before any connect. #[test] -fn session_failure_names_a_failing_dial() { +fn a_failing_dial_reports_its_failure() { // Hang up on every connection, so a WebSocket dial fails fast. Holding the listener // keeps a parallel test from taking the port. let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); @@ -4963,7 +5045,7 @@ fn session_failure_names_a_failing_dial() { } }); let url = format!("ws://127.0.0.1:{port}/"); - let cb = Callback::new(); + let cb = States::new(); let session = id(unsafe { moq_session_connect( url.as_ptr() as *const c_char, @@ -4971,34 +5053,25 @@ fn session_failure_names_a_failing_dial() { std::ptr::null(), 0, 0, - Some(channel_callback), + Some(state_callback), cb.ptr, ) }); - let deadline = std::time::Instant::now() + TIMEOUT; - let code = loop { - let code = moq_session_failure(session); - if code != 0 { - break code; - } - assert!( - std::time::Instant::now() < deadline, - "the refused dial never reported a failure" - ); - std::thread::sleep(Duration::from_millis(10)); - }; - assert_ne!( - code, - Error::SessionNotFound.code(), - "the session ended instead of retrying: {:?}", - cb.rx.try_recv() + let failed = cb.recv(); + assert_eq!(failed.phase, moq_connection_phase::MOQ_CONNECTION_PHASE_CONNECTING); + assert_eq!(failed.connects, 0); + assert!(failed.failure < 0, "the refused dial reports why: {failed:?}"); + assert!( + failed.error.is_some_and(|error| !error.is_empty()), + "moq_error describes the failure during the callback" ); - assert!(!moq_error().is_null(), "the failure is recorded like a failed call"); - assert!(cb.rx.try_recv().is_err(), "a failed dial fires no status"); + assert!(failed.version.is_empty(), "nothing is serving"); assert_eq!(moq_session_close(session), 0); - assert!(cb.recv() <= 0, "session close delivers a terminal code"); + let terminal = cb.recv_terminal(); + assert_eq!(terminal.failure, 0, "a requested close is clean: {terminal:?}"); + assert_eq!(terminal.connects, 0); } /// Borrow a `&str` as the `moq_string` the list setters take. @@ -5025,7 +5098,7 @@ fn dial(config: Option<&moq_client_config>) -> i32 { config.map_or(std::ptr::null(), |c| c as *const _), 0, 0, - Some(ignore_callback), + Some(ignore_state), std::ptr::null_mut(), ) } @@ -5375,7 +5448,7 @@ fn dial_applies_the_config() { config.connect_timeout_us = 100_000; config.has_connect_timeout = true; - let cb = Callback::new(); + let cb = States::new(); let url = b"moqt://localhost:1"; let session = id(unsafe { moq_session_connect( @@ -5384,13 +5457,13 @@ fn dial_applies_the_config() { &config, 0, 0, - Some(channel_callback), + Some(state_callback), cb.ptr, ) }); assert_eq!(moq_session_close(session), 0); - assert!(cb.recv() <= 0, "session close delivers a terminal code"); + cb.recv_terminal(); } fn test_allocator() -> (u32, moq_net::bandwidth::Producer) { @@ -5609,13 +5682,7 @@ fn listen(cb: &Callback) -> (u32, String, String) { } /// Dial `url`, pinning `fingerprint`, with `consume` receiving the peer's broadcasts. -fn dial_pinned( - url: &str, - fingerprint: &str, - consume: u32, - on_status: extern "C" fn(*mut c_void, i32), - user_data: *mut c_void, -) -> u32 { +fn dial_pinned(url: &str, fingerprint: &str, consume: u32, user_data: *mut c_void) -> u32 { let fingerprints = [moq_str(fingerprint)]; let mut config = client_config(); config.tls_fingerprints = fingerprints.as_ptr(); @@ -5629,7 +5696,7 @@ fn dial_pinned( &config, 0, consume, - Some(on_status), + Some(state_callback), user_data, ) }) @@ -5644,12 +5711,11 @@ fn server_accepts_a_session() { let (server, addr, fingerprint) = listen(&server_cb); let received = id(moq_origin_create()); - let client_cb = Callback::new(); + let client_cb = States::new(); let client = dial_pinned( &format!("https://{addr}/room?jwt=abc"), &fingerprint, received, - channel_callback, client_cb.ptr, ); @@ -5662,16 +5728,21 @@ fn server_accepts_a_session() { assert_eq!(unsafe { moq_session_request_query(request, &mut query) }, 0); assert_eq!(borrowed_string(query.data, query.len).as_deref(), Some("jwt=abc")); - let session_cb = Callback::new(); - let session = id(unsafe { moq_session_request_accept(request, served, 0, Some(channel_callback), session_cb.ptr) }); + let session_cb = States::new(); + let session = id(unsafe { moq_session_request_accept(request, served, 0, Some(state_callback), session_cb.ptr) }); assert!( unsafe { moq_session_request_path(request, &mut path) } < 0, "accept consumes the request" ); - // Both sides report the first (and, for the server, only) connect. - assert_eq!(session_cb.recv(), 1); - assert_eq!(client_cb.recv(), 1); + // Both sides report the first (and, for the server, only) connect, with its protocol. + for cb in [&session_cb, &client_cb] { + let connected = cb.recv(); + assert_eq!(connected.phase, moq_connection_phase::MOQ_CONNECTION_PHASE_CONNECTED); + assert_eq!(connected.connects, 1); + assert_eq!(connected.failure, 0); + assert!(!connected.version.is_empty(), "a live session names its protocol"); + } let mut stats: moq_connection_stats = unsafe { std::mem::zeroed() }; assert_eq!(unsafe { moq_session_stats(session, &mut stats) }, 0); @@ -5698,7 +5769,8 @@ fn server_accepts_a_session() { // Closing the accepted session is a clean terminal close. assert_eq!(moq_session_close(session), 0); - assert_eq!(session_cb.recv_terminal(), 0); + let terminal = session_cb.recv_terminal(); + assert_eq!((terminal.failure, terminal.connects), (0, 1)); assert_eq!(moq_session_close(client), 0); client_cb.recv_terminal(); @@ -5720,14 +5792,8 @@ fn server_rejects_a_session() { let server_cb = Callback::new(); let (server, addr, fingerprint) = listen(&server_cb); - let client_cb = ProtocolCallback::new(); - let client = dial_pinned( - &format!("https://{addr}/"), - &fingerprint, - 0, - protocol_callback, - client_cb.ptr, - ); + let client_cb = States::new(); + let client = dial_pinned(&format!("https://{addr}/"), &fingerprint, 0, client_cb.ptr); let request = id(server_cb.recv()); let mut path = moq_str("x"); @@ -5742,13 +5808,9 @@ fn server_rejects_a_session() { // The rejection closes a session the transport already established, so the client // may see it connect first. It then gives up on the auth rejection rather than redialing. - let mut status = client_cb.recv(); - if status.0 == 1 { - status = client_cb.recv(); - } - let (code, protocol) = status; - assert_eq!(code, MOQ_ERROR_MOQ); - let protocol = protocol.expect("the rejection carries a protocol close"); + let terminal = client_cb.recv_terminal(); + assert_eq!(terminal.failure, MOQ_ERROR_MOQ); + let protocol = terminal.protocol.expect("the rejection carries a protocol close"); assert_eq!(protocol.scope, moq_error_scope::MOQ_ERROR_SCOPE_SESSION as u32); assert_eq!(protocol.kind, moq_protocol_kind::MOQ_PROTOCOL_KIND_UNAUTHORIZED as u32); assert!(moq_session_close(client) < 0, "the client session already ended"); diff --git a/rs/moq-ffi/MIGRATE.md b/rs/moq-ffi/MIGRATE.md index f56edf65041..970199b6486 100644 --- a/rs/moq-ffi/MIGRATE.md +++ b/rs/moq-ffi/MIGRATE.md @@ -5,6 +5,10 @@ These are the UniFFI names; each language wrapper has its own `MIGRATE.md` in it ## Unreleased +### Connection state + +`MoqClient::connect` returns a connecting session without waiting for its first dial to succeed, natively and in the browser. Read `MoqSession::state()` and pass its `revision` to `state_changed(after)` to observe first-dial failures and reconnects. `MoqConnectionState` carries `phase`, `connects`, `failure`, and `version` together. These replace `status()`, `connects()`, and both `failure()` polls. Cancel the returned session to stop dialing; cancelling or releasing the client does not close it. + ### Exact encoder rates and publication options Encoder configuration is breaking: `MoqVideoEncoderInput.framerate` is now a diff --git a/rs/moq-ffi/src/auth.rs b/rs/moq-ffi/src/auth.rs index f191e07e853..d828ce6ff67 100644 --- a/rs/moq-ffi/src/auth.rs +++ b/rs/moq-ffi/src/auth.rs @@ -32,13 +32,16 @@ impl From for MoqGrant { } } -/// Where a session's tokens live: on the session itself, or on a connection that presents -/// them again on every reconnect. +/// Where a session's tokens live: on the session itself, on a connection that presents +/// them again on every reconnect, or on a browser session once its dial completes. #[derive(Clone)] pub(crate) enum Handle { Session(moq_net::auth::Handle), #[cfg(not(target_arch = "wasm32"))] Connection(moq_tokio::connection::auth::Handle), + /// A browser session still dialing when the handle was taken. + #[cfg(target_arch = "wasm32")] + Dial(crate::session::Dial), } impl Handle { @@ -47,30 +50,46 @@ impl Handle { Self::Session(handle) => Watch::Session(handle.grant()), #[cfg(not(target_arch = "wasm32"))] Self::Connection(handle) => Watch::Connection(handle.grant()), + #[cfg(target_arch = "wasm32")] + Self::Dial(dial) => match dial.session() { + Some(session) => Watch::Session(session.auth().grant()), + None => Watch::Dial { + dial: dial.clone(), + watch: None, + }, + }, } } async fn add(self, token: String) -> Result { match self { - Self::Session(handle) => { - let auth = handle.add(token).await?; - // A token the peer accepted carries a grant until it ends. Without AUTH, - // moq-transport accepts one at once for the requests that name it, but nothing - // here can name one, so it would never be sent. One already revoked is left for - // `closed` to report. moq-tokio refuses the same for a client's connection. - if auth.grant().peek().is_none() && poll_now(auth.closed()).is_pending() { - return Err(MoqError::Unsupported); - } - Ok(Token::Session(auth)) - } + Self::Session(handle) => add(handle, token).await, #[cfg(not(target_arch = "wasm32"))] Self::Connection(handle) => Ok(Token::Connection( handle.add(token).await.map_err(crate::session::map_closed_error)?, )), + // The token waits for the handshake; a dial that ends first refuses it. + #[cfg(target_arch = "wasm32")] + Self::Dial(dial) => match dial.established().await? { + Some(session) => add(session.auth(), token).await, + None => Err(MoqError::Closed), + }, } } } +async fn add(handle: moq_net::auth::Handle, token: String) -> Result { + let auth = handle.add(token).await?; + // A token the peer accepted carries a grant until it ends. Without AUTH, + // moq-transport accepts one at once for the requests that name it, but nothing + // here can name one, so it would never be sent. One already revoked is left for + // `closed` to report. moq-tokio refuses the same for a client's connection. + if auth.grant().peek().is_none() && poll_now(auth.closed()).is_pending() { + return Err(MoqError::Unsupported); + } + Ok(Token::Session(auth)) +} + /// Poll `future` once without waiting. fn poll_now(future: F) -> std::task::Poll { let future = std::pin::pin!(future); @@ -81,6 +100,12 @@ enum Watch { Session(moq_net::auth::Watch), #[cfg(not(target_arch = "wasm32"))] Connection(moq_tokio::connection::auth::Watch), + /// A browser session still dialing, which has no grant until its session's watch exists. + #[cfg(target_arch = "wasm32")] + Dial { + dial: crate::session::Dial, + watch: Option, + }, } impl Watch { @@ -89,6 +114,11 @@ impl Watch { Self::Session(watch) => watch.peek(), #[cfg(not(target_arch = "wasm32"))] Self::Connection(watch) => watch.peek(), + #[cfg(target_arch = "wasm32")] + Self::Dial { dial, watch } => match watch { + Some(watch) => watch.peek(), + None => dial.session().and_then(|session| session.auth().grant().peek()), + }, } .map(Into::into) } @@ -98,6 +128,22 @@ impl Watch { Self::Session(watch) => watch.changed().await?, #[cfg(not(target_arch = "wasm32"))] Self::Connection(watch) => watch.changed().await.map_err(crate::session::map_closed_error)?, + #[cfg(target_arch = "wasm32")] + Self::Dial { dial, watch } => { + let watch = match watch { + Some(watch) => watch, + None => { + let session = dial.established().await?.ok_or(MoqError::Closed)?; + let fresh = watch.insert(session.auth().grant()); + // Dialing reported no grant, so one the session already holds is the change. + if let Some(grant) = fresh.peek() { + return Ok(Some(grant.into())); + } + fresh + } + }; + watch.changed().await? + } }; Ok(grant.map(Into::into)) } diff --git a/rs/moq-ffi/src/session.rs b/rs/moq-ffi/src/session.rs index 660c67ee6e2..06a688d13f5 100644 --- a/rs/moq-ffi/src/session.rs +++ b/rs/moq-ffi/src/session.rs @@ -10,6 +10,11 @@ use crate::error::MoqError; use crate::ffi::Task; use crate::origin::{MoqOriginConsumer, MoqOriginProducer}; +#[cfg(target_arch = "wasm32")] +mod dial; +#[cfg(target_arch = "wasm32")] +pub(crate) use dial::Dial; + /// Configuration for [`MoqClient::new`], mirroring moq-tokio's client config. /// /// Every field has a default, so set only what you need; [`moq_client_defaults`] reports @@ -280,30 +285,12 @@ pub(crate) fn parse_versions(versions: &[String]) -> Result>>; - /// Native QUIC/WebTransport client state: the configured endpoint and the wired origins. #[cfg(not(target_arch = "wasm32"))] struct Client { client: moq_tokio::Client, publish: Option>, consume: Option>, - dialing: Dialing, -} - -/// Empties the [`Dialing`] slot when its `connect` resolves or is dropped. -#[cfg(not(target_arch = "wasm32"))] -struct DialingGuard<'a>(&'a Dialing); - -#[cfg(not(target_arch = "wasm32"))] -impl Drop for DialingGuard<'_> { - fn drop(&mut self) { - self.0.lock().unwrap().take(); - } } #[cfg(not(target_arch = "wasm32"))] @@ -365,7 +352,6 @@ impl Client { client, publish: config.publish, consume: config.consume, - dialing: Default::default(), }) } @@ -381,53 +367,21 @@ impl Client { .with_subscriber(subscribe.inner.clone()) .connect(url); - *self.dialing.lock().unwrap() = Some(connection.monitor()); - let _dialing = DialingGuard(&self.dialing); - - // Wait for the first session so auth errors surface here; later drops are the - // connection's to ride out. `MoqClient::cancel` unblocks a dial stuck retrying. - // `established` hands the connection back, which is what keeps it reconnecting. - let connection = publish - .driver - .watch( - subscribe - .driver - .watch(async { connection.established().await.map_err(map_connect_error) }), - ) - .await?; - Ok(Arc::new(MoqSession::connected(connection, publish, subscribe))) } } -#[cfg(not(target_arch = "wasm32"))] -fn map_connect_error(err: moq_tokio::Error) -> MoqError { - match err { - moq_tokio::Error::MoqNet(err) => err.into(), - moq_tokio::Error::Panic => MoqError::Task { - reason: "background task panicked".into(), - }, - err => match err.connect_error() { - Some(moq_tokio::ConnectError::Unauthorized) => MoqError::Unauthorized, - Some(moq_tokio::ConnectError::Forbidden) => MoqError::Forbidden, - _ => MoqError::Connect { - reason: format!("{err}"), - }, - }, - } -} - /// The terminal error of a connection that had already established a session. /// -/// Same auth rejections as [`map_connect_error`], but a session that ended carries +/// A session that ended carries /// a [`moq_net::Error`], and stringifying that into `Connect` would both lose the /// variant a caller can match on and claim the dial failed when it had succeeded. /// A server-accepted session reports its close the same way. /// /// A local stop is not a failure at all, so it maps to `Closed`, which is what the -/// bindings' `is_shutdown` recognizes. `status()` reaches this path whenever +/// bindings' `is_shutdown` recognizes. `state_changed()` reaches this path whenever /// another handle shuts the connection down underneath it, and reporting that as a -/// connect error would make every status watcher treat an expected teardown as a +/// connect error would make every lifecycle watcher treat an expected teardown as a /// broken connection. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn map_closed_error(err: moq_tokio::Error) -> MoqError { @@ -505,11 +459,11 @@ mod tests { #[test] fn maps_native_auth_connect_errors() { assert!(matches!( - map_connect_error(moq_tokio::ConnectError::Unauthorized.into()), + map_closed_error(moq_tokio::ConnectError::Unauthorized.into()), MoqError::Unauthorized )); assert!(matches!( - map_connect_error(moq_tokio::ConnectError::Forbidden.into()), + map_closed_error(moq_tokio::ConnectError::Forbidden.into()), MoqError::Forbidden )); } @@ -678,29 +632,24 @@ impl Client { async fn connect(&self, url: Url) -> Result, MoqError> { let (publish, subscribe) = crate::origin::resolve_pair(self.publish.as_ref(), self.consume.as_ref()); - let transport = match self.fingerprints.is_empty() { - true => crate::transport::connect(url, &self.versions).await, - false => crate::transport::connect_with_hashes(url, &self.versions, self.fingerprints.clone()).await, - } - .map_err(|err| MoqError::Connect { - reason: format!("{err}"), - })?; - - // Run the driver on the microtask queue. The driver - // holds no session clone, so dropping the last handle still closes the - // transport and ends that task. - let (session, driver) = moq_net::Client::new() + let versions = self.versions.clone(); + let fingerprints = self.fingerprints.clone(); + let transport = async move { + match fingerprints.is_empty() { + true => crate::transport::connect(url, &versions).await, + false => crate::transport::connect_with_hashes(url, &versions, fingerprints).await, + } + }; + let client = moq_net::Client::new() .with_versions(self.versions.clone()) .with_publisher(&publish.inner) - .with_subscriber(subscribe.inner.clone()) - .connect(moq_clock::now(), transport) - .await?; + .with_subscriber(subscribe.inner.clone()); - crate::ffi::spawn(async move { - moq_net::time::run(driver).await; - }); - - Ok(Arc::new(MoqSession::accepted(session, publish, subscribe))) + Ok(Arc::new(MoqSession::build( + Inner::Dial(Dial::start(client, transport)), + publish, + subscribe, + ))) } } @@ -752,9 +701,6 @@ fn decode_hex(hex: &str) -> Result, MoqError> { #[derive(uniffi::Object)] pub struct MoqClient { task: Task, - /// Shared with the state, which the `connect` in flight holds locked. - #[cfg(not(target_arch = "wasm32"))] - dialing: Dialing, } #[uniffi::export] @@ -764,25 +710,22 @@ impl MoqClient { pub fn new(config: MoqClientConfig) -> Result, MoqError> { let client = Client::new(config)?; Ok(Arc::new(Self { - #[cfg(not(target_arch = "wasm32"))] - dialing: client.dialing.clone(), task: Task::new(client), })) } - /// Connect to a MoQ server and wait for the session to be established. + /// Start a connection without waiting for its first dial to succeed. /// /// A native session automatically reconnects with backoff when the transport drops /// (unless [`MoqClientConfig::once`] is set), and broadcasts consumed through it ride out - /// the gap. Watch [`MoqSession::status`] for the connect/disconnect transitions, - /// [`MoqSession::connects`] for the reconnect count, and [`MoqSession::closed`] for the - /// connection giving up for good. + /// the gap. A browser session dials once and never reconnects. Read [`MoqSession::state`] + /// and wait with [`MoqSession::state_changed`] for first-dial failures and reconnects; + /// [`MoqSession::closed`] waits for the terminal result. /// /// Both origin sides are always accessible via [`MoqSession::publish`] and /// [`MoqSession::consume`], without the caller constructing a [`MoqOriginProducer`]. /// - /// Can be cancelled by calling `cancel()`, including while the initial dial is retrying; - /// [`failure`](Self::failure) says why it is. + /// Cancel the returned session to stop its dial; cancelling the client stops future calls. pub async fn connect(&self, url: String) -> Result, MoqError> { let url = Url::parse(&url)?; self.task.run(|state| async move { state.connect(url).await }).await @@ -795,27 +738,6 @@ impl MoqClient { pub fn cancel(&self) { self.task.cancel(); } - - /// Why the pending [`connect`](Self::connect) is still dialing: the error that failed - /// its latest attempt, or `None` while nothing has failed or no connect is pending. - /// - /// A first dial that keeps failing and retrying never resolves `connect`, so poll this - /// to show the reason, such as a refused dial. Giving up for good is `connect`'s error - /// instead. Once it returns, [`MoqSession::failure`] reports the session's reconnects. A - /// browser client dials once, so it is always `None`. - pub fn failure(&self) -> Option { - #[cfg(not(target_arch = "wasm32"))] - { - // A cancelled connect may not be dropped yet, but it no longer dials. - if self.task.is_cancelled() { - return None; - } - self.dialing.lock().unwrap().as_ref()?.failure().map(map_closed_error) - } - - #[cfg(target_arch = "wasm32")] - None - } } /// A snapshot of connection statistics for a [`MoqSession`]. @@ -865,39 +787,67 @@ impl MoqConnectionStats { } } -/// A connection lifecycle transition reported by [`MoqSession::status`]. +/// The current lifecycle phase, distinct from cumulative statistics presence. #[derive(Clone, Copy, Debug, PartialEq, Eq, uniffi::Enum)] -pub enum MoqConnectionStatus { - /// A session connected (the first connect, or a reconnect after a drop). +pub enum MoqConnectionPhase { + /// No session has connected yet. + Connecting, + /// A session is serving. Connected, - /// The session dropped; a reconnect attempt follows. + /// No session is serving while a native connection redials. Disconnected, - /// The peer sent a GOAWAY; the replacement is being dialed while the old - /// session keeps serving. + /// The old session serves while its replacement dials. Migrating, + /// The connection has stopped for good. + Closed, +} + +/// One coherent connection lifecycle observation. +#[derive(Debug, uniffi::Record)] +pub struct MoqConnectionState { + /// An opaque revision to pass back to `state_changed` on this session. + pub revision: u64, + /// The current lifecycle phase. + pub phase: MoqConnectionPhase, + /// How many sessions have connected, including replacements. + pub connects: u64, + /// The latest failed attempt or terminal failure, cleared by a successful connect. + pub failure: Option, + /// The live session's negotiated protocol, or none while offline. + pub version: Option, } #[cfg(not(target_arch = "wasm32"))] -impl From for MoqConnectionStatus { - fn from(status: moq_tokio::Status) -> Self { - match status { - moq_tokio::Status::Connected => Self::Connected, - moq_tokio::Status::Disconnected => Self::Disconnected, - // A future unknown status means the loop is between the known states; - // Migrating is the "still served, in flux" bucket. - _ => Self::Migrating, +impl From for MoqConnectionState { + fn from(state: moq_tokio::connection::Observation) -> Self { + use moq_tokio::connection::Phase; + Self { + revision: state.revision, + phase: match state.phase { + Phase::Connecting => MoqConnectionPhase::Connecting, + Phase::Connected => MoqConnectionPhase::Connected, + Phase::Disconnected => MoqConnectionPhase::Disconnected, + Phase::Migrating => MoqConnectionPhase::Migrating, + Phase::Closed => MoqConnectionPhase::Closed, + }, + connects: state.connects, + failure: state.failure.map(map_closed_error), + version: state.version.map(|v| v.to_string()), } } } -/// What backs a [`MoqSession`]: a client connection (a loop that may redial) or +/// What backs a [`MoqSession`]: a native client connection (a loop that may redial), /// a server-accepted session (one transport; the peer redialing yields a fresh -/// `accept()`). +/// `accept()`), or a browser dial (one attempt, then its session). #[derive(Clone)] enum Inner { #[cfg(not(target_arch = "wasm32"))] Connection(moq_tokio::Connection), + #[cfg(not(target_arch = "wasm32"))] Session(Accepted), + #[cfg(target_arch = "wasm32")] + Dial(Dial), } #[derive(Clone)] @@ -914,6 +864,25 @@ impl std::ops::Deref for Accepted { } impl Accepted { + fn state(&self) -> MoqConnectionState { + let mut closed = std::pin::pin!(self.closed::<()>()); + let result = std::future::Future::poll( + closed.as_mut(), + &mut std::task::Context::from_waker(std::task::Waker::noop()), + ); + let (phase, failure, revision) = match result { + std::task::Poll::Pending => (MoqConnectionPhase::Connected, None, 0), + std::task::Poll::Ready(result) => (MoqConnectionPhase::Closed, result.err(), 1), + }; + MoqConnectionState { + revision, + phase, + connects: 1, + failure, + version: (phase == MoqConnectionPhase::Connected).then(|| self.session.version().to_string()), + } + } + async fn closed(&self) -> Result { self.driver.check()?; #[cfg(not(target_arch = "wasm32"))] @@ -937,8 +906,6 @@ pub struct MoqSession { /// Serializes `closed()` calls onto the FFI runtime; holds its own `Inner` clone /// so a parked `closed()` doesn't block the rest of the surface. closed: Task, - /// Serializes `status()` calls, which need `&mut` for per-handle change tracking. - status: Task, publisher: Arc, consumer: Arc, /// One allocator for the session. Every [`bandwidth`](Self::bandwidth) handle @@ -958,13 +925,13 @@ impl MoqSession { } /// Wrap a server-accepted session (see `MoqServer::accept`). + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn accepted( session: moq_net::Session, publish: crate::origin::Origin, subscribe: crate::origin::Origin, - #[cfg(not(target_arch = "wasm32"))] driver: tokio::task::JoinHandle>, + driver: tokio::task::JoinHandle>, ) -> Self { - #[cfg(not(target_arch = "wasm32"))] let driver = crate::ffi::Background::new(async move { match driver.await { Ok(result) => result, @@ -972,8 +939,6 @@ impl MoqSession { Err(_) => Err(moq_tokio::Error::Panic), } }); - #[cfg(target_arch = "wasm32")] - let driver = crate::ffi::Background::default(); Self::build(Inner::Session(Accepted { session, driver }), publish, subscribe) } @@ -983,7 +948,11 @@ impl MoqSession { // again on the next connection. Reservations survive the gap. #[cfg(not(target_arch = "wasm32"))] Inner::Connection(connection) => connection.bandwidth(), + #[cfg(not(target_arch = "wasm32"))] Inner::Session(session) => session.bandwidth(), + // Persistent from before the handshake, so a reservation made while dialing counts. + #[cfg(target_arch = "wasm32")] + Inner::Dial(dial) => dial.bandwidth(), } } @@ -997,7 +966,6 @@ impl MoqSession { Self { inner: inner.clone(), closed: Task::new(inner.clone()), - status: Task::new(inner), publisher, consumer, bandwidth, @@ -1012,12 +980,15 @@ impl MoqSession { .await } - /// Abort the live transport (if any) with `err` and stop any reconnect loop. + /// Abort the live transport (if any) with `err` and stop any dial or reconnect loop. fn teardown(&self, err: moq_net::Error) { match &self.inner { #[cfg(not(target_arch = "wasm32"))] Inner::Connection(connection) => connection.abort(err), + #[cfg(not(target_arch = "wasm32"))] Inner::Session(session) => session.abort(err), + #[cfg(target_arch = "wasm32")] + Inner::Dial(dial) => dial.stop(err), } } } @@ -1027,7 +998,7 @@ impl Drop for MoqSession { let _guard = crate::ffi::enter(); // Close the transport while the runtime is entered. The backend spawns a // lingering CLOSE task, which panics if no reactor is in context. We can't leave this to the last `Session` clone's drop: clones - // live in the `closed`/`status` tasks and the connection state, released after + // live in the `closed` task and the connection state, released after // this guard, off-runtime. Close-once dedup then makes those trailing drops no-ops. self.teardown(moq_net::Error::Cancel); } @@ -1041,7 +1012,7 @@ impl MoqSession { /// terminal error when it gave up (retries exhausted, or the session's close reason /// with reconnecting disabled), `Ok` after a local [`shutdown`](Self::shutdown) / /// [`cancel`](Self::cancel). Transient drops the reconnect loop rides out do not - /// resolve this; watch [`status`](Self::status) for those. A server-accepted + /// resolve this; watch [`state_changed`](Self::state_changed) for those. A server-accepted /// session resolves with the session's close reason. pub async fn closed(&self) -> Result<(), MoqError> { // We have a task to run all of the closed calls juuuuust so they use the same tokio runtime. @@ -1049,49 +1020,62 @@ impl MoqSession { match &*inner { #[cfg(not(target_arch = "wasm32"))] Inner::Connection(connection) => connection.closed().await.map_err(map_closed_error), + #[cfg(not(target_arch = "wasm32"))] Inner::Session(session) => session.closed().await, + #[cfg(target_arch = "wasm32")] + Inner::Dial(dial) => dial.closed().await, } })) .await } - /// Wait for the connection status to differ from the one this handle last reported. - /// - /// A client session reports `Connected` first (the connect it was built from), then - /// follows the reconnect loop: `Disconnected` while redialing, `Connected` again on - /// success, `Migrating` during a GOAWAY handover. It returns an error once the - /// connection stops for good (same terminal result as [`closed`](Self::closed)). - /// A server-accepted session is a single transport, so its only transition is - /// terminal: this waits for the close and returns its reason. + /// Read the connection lifecycle fields together without advancing any watcher. + pub fn state(&self) -> MoqConnectionState { + let _runtime = crate::ffi::enter(); + match &self.inner { + #[cfg(not(target_arch = "wasm32"))] + Inner::Connection(connection) => connection.monitor().state().into(), + #[cfg(not(target_arch = "wasm32"))] + Inner::Session(session) => session.state(), + #[cfg(target_arch = "wasm32")] + Inner::Dial(dial) => dial.state(), + } + } + + /// Wait for a revision different from `after`, without sharing a cursor with other callers. /// - /// This is the current status, not a queue of every edge: a drop that reconnects - /// before you ask again is coalesced away, so the outages it hides are the ones - /// that already healed. Don't count outages with it. - pub async fn status(&self) -> Result { - self.watch(self.status.run(|mut inner| async move { - match &mut *inner { + /// Pass the revision from this session's last snapshot. Changes between reading and + /// waiting are returned immediately; repeated failed dials advance it too. The final + /// snapshot reports `Closed`; waiting again at that revision returns the close reason. + pub async fn state_changed(&self, after: u64) -> Result { + self.watch(Task::new(self.inner.clone()).run(|inner| async move { + match &*inner { #[cfg(not(target_arch = "wasm32"))] - Inner::Connection(connection) => Ok(connection.status().await.map_err(map_closed_error)?.into()), - Inner::Session(session) => session.closed().await, + Inner::Connection(connection) => Ok(connection + .monitor() + .state_changed(after) + .await + .map_err(map_closed_error)? + .into()), + #[cfg(not(target_arch = "wasm32"))] + Inner::Session(session) => { + let state = session.state(); + if state.revision != after { + return Ok(state); + } + if state.phase == MoqConnectionPhase::Closed { + return Err(state.failure.unwrap_or(MoqError::Closed)); + } + let _ = session.closed::<()>().await; + Ok(session.state()) + } + #[cfg(target_arch = "wasm32")] + Inner::Dial(dial) => dial.state_changed(after).await, } })) .await } - /// How many times this session has connected: 1 for the connect it was built from, one more - /// on each reconnect. A server-accepted session is a single transport, so it stays 1. - /// - /// The count pairs with [`status`](Self::status): a `Connected` transition whose - /// count grew is a reconnect, so a worker can log each one by number. Migrations - /// count too, since the replacement is a new session. - pub fn connects(&self) -> u64 { - match &self.inner { - #[cfg(not(target_arch = "wasm32"))] - Inner::Connection(connection) => connection.connects(), - Inner::Session(_) => 1, - } - } - /// Close the session with the given error code, stopping any reconnect loop. pub fn cancel(&self, code: u32) { let _guard = crate::ffi::enter(); @@ -1113,7 +1097,10 @@ impl MoqSession { match inner { #[cfg(not(target_arch = "wasm32"))] Inner::Connection(connection) => connection.close().await.map_err(map_closed_error), + #[cfg(not(target_arch = "wasm32"))] Inner::Session(session) => session.close().await, + #[cfg(target_arch = "wasm32")] + Inner::Dial(dial) => dial.close().await, } }) .await; @@ -1160,7 +1147,13 @@ impl MoqSession { Arc::new(MoqAuth::new(match &self.inner { #[cfg(not(target_arch = "wasm32"))] Inner::Connection(connection) => crate::auth::Handle::Connection(connection.auth()), + #[cfg(not(target_arch = "wasm32"))] Inner::Session(session) => crate::auth::Handle::Session(session.auth()), + #[cfg(target_arch = "wasm32")] + Inner::Dial(dial) => match dial.session() { + Some(session) => crate::auth::Handle::Session(session.auth()), + None => crate::auth::Handle::Dial(dial.clone()), + }, })) } @@ -1169,7 +1162,10 @@ impl MoqSession { let consumer = match &self.inner { #[cfg(not(target_arch = "wasm32"))] Inner::Connection(connection) => Some(connection.recv_bandwidth()), + #[cfg(not(target_arch = "wasm32"))] Inner::Session(session) => session.recv_bandwidth(), + #[cfg(target_arch = "wasm32")] + Inner::Dial(dial) => Some(dial.recv_bandwidth()), }?; Some(Arc::new(crate::bandwidth::MoqBandwidthConsumer::new(consumer))) } @@ -1189,22 +1185,13 @@ impl MoqSession { Some(snapshot) => MoqConnectionStats::new(snapshot.stats, Some(snapshot.version)), None => MoqConnectionStats::new(Default::default(), None), }, - Inner::Session(session) => MoqConnectionStats::new(session.stats(), Some(session.version())), - } - } - - /// Why a client session is reconnecting: the error that ended the last connection or - /// failed the latest redial, or `None` once a connection lands. - /// - /// A redial that keeps failing never changes [`status`](Self::status), so poll this - /// while it reports `Disconnected` to show the reason, such as a refused dial. - /// Giving up for good reports through [`closed`](Self::closed) instead. A - /// server-accepted session never reconnects, so it is always `None`. - pub fn failure(&self) -> Option { - match &self.inner { #[cfg(not(target_arch = "wasm32"))] - Inner::Connection(connection) => connection.monitor().failure().map(map_closed_error), - Inner::Session(_) => None, + Inner::Session(session) => MoqConnectionStats::new(session.stats(), Some(session.version())), + #[cfg(target_arch = "wasm32")] + Inner::Dial(dial) => match dial.session() { + Some(session) => MoqConnectionStats::new(session.stats(), Some(session.version())), + None => MoqConnectionStats::new(Default::default(), None), + }, } } } diff --git a/rs/moq-ffi/src/session/dial.rs b/rs/moq-ffi/src/session/dial.rs new file mode 100644 index 00000000000..1f304165902 --- /dev/null +++ b/rs/moq-ffi/src/session/dial.rs @@ -0,0 +1,282 @@ +//! A browser connection: one dial its session owns from the start, then the session it +//! establishes. + +use std::future::Future; +use std::task::Poll; + +use super::{Accepted, MoqConnectionPhase, MoqConnectionState}; +use crate::error::MoqError; + +/// Why a dial ended without a session. +#[derive(Clone)] +enum Failure { + /// The caller stopped it. + Stopped, + /// WebTransport did not connect. + Transport(String), + /// The MoQ handshake failed. + Handshake(moq_net::Error), +} + +impl Failure { + /// The error a failed dial reports, or `None` for a local stop. + fn error(&self) -> Option { + match self { + Self::Stopped => None, + Self::Transport(reason) => Some(MoqError::Connect { reason: reason.clone() }), + Self::Handshake(err) => Some(err.clone().into()), + } + } +} + +#[derive(Default)] +struct State { + /// The established session. + session: Option, + /// Why the dial ended without one. + failed: Option, + /// A stop request, which the dial and its session both honor. + stop: Option, +} + +/// One browser dial and the session it establishes, shared by every handle of its session. +/// +/// Revisions run 0 while dialing, 1 once the dial settles (connected or failed), and 2 +/// once an established session closes. +#[derive(Clone)] +pub(crate) struct Dial { + state: kio::Producer, + /// Persistent from before the handshake: the session probes for these reservations. + bandwidth: moq_net::bandwidth::Allocator, + /// The session's receive estimate, forwarded while a consumer holds it. + recv: moq_net::bandwidth::Weak, +} + +impl Dial { + /// Start dialing, returning before the transport or the handshake completes. + pub fn start(client: moq_net::Client, transport: impl Future> + 'static) -> Self + where + T: moq_net::transport::poll::Boxable, + E: std::fmt::Display, + { + let state = kio::Producer::new(State::default()); + let send = moq_net::bandwidth::Producer::new(); + let recv = moq_net::bandwidth::Producer::new(); + let bandwidth = moq_net::bandwidth::Allocator::new(send.consume()); + let client = client.with_bandwidth(bandwidth.clone()); + let dial = Self { + state: state.clone(), + bandwidth, + recv: recv.weak(), + }; + + let handshake = async move { + let transport = transport.await.map_err(|err| Failure::Transport(err.to_string()))?; + client + .connect(moq_clock::now(), transport) + .await + .map_err(Failure::Handshake) + }; + crate::ffi::spawn(run(state, handshake, send, recv)); + dial + } + + /// Stop the dial, or abort the session it established, with `err`. + pub fn stop(&self, err: moq_net::Error) { + // Under the lock the dial publishes its session with, so a session landing now is + // either aborted here or refused by the dial. + if let Ok(mut state) = self.state.write() { + if let Some(session) = &state.session { + session.abort(err.clone()); + } + state.stop.get_or_insert(err); + } + } + + /// The established session, if the dial has completed. + pub fn session(&self) -> Option { + self.state + .read() + .session + .as_ref() + .map(|accepted| accepted.session.clone()) + } + + /// Wait for the dial to settle: the session, `None` after a local stop, or why it failed. + pub async fn established(&self) -> Result, MoqError> { + Ok(self.settled().await?.map(|accepted| accepted.session)) + } + + async fn settled(&self) -> Result, MoqError> { + let settled = self + .state + .consume() + .wait(|state| match (&state.session, &state.failed) { + (Some(session), _) => Poll::Ready(Ok(Some(session.clone()))), + (None, Some(failure)) => Poll::Ready(failure.error().map_or(Ok(None), Err)), + (None, None) => Poll::Pending, + }) + .await; + // The dial task keeps the channel open for as long as any handle exists. + settled.unwrap_or(Err(MoqError::Closed)) + } + + pub fn state(&self) -> MoqConnectionState { + let state = self.state.read(); + if let Some(session) = &state.session { + let mut state = session.state(); + state.revision += 1; + return state; + } + let (revision, phase) = match state.failed { + Some(_) => (1, MoqConnectionPhase::Closed), + None => (0, MoqConnectionPhase::Connecting), + }; + MoqConnectionState { + revision, + phase, + connects: 0, + failure: state.failed.as_ref().and_then(Failure::error), + version: None, + } + } + + pub async fn state_changed(&self, after: u64) -> Result { + loop { + let state = self.state(); + if state.revision != after { + return Ok(state); + } + if state.phase == MoqConnectionPhase::Closed { + return Err(state.failure.unwrap_or(MoqError::Closed)); + } + match self.settled().await { + Ok(Some(session)) if state.phase == MoqConnectionPhase::Connected => { + let _ = session.closed::<()>().await; + } + _ => {} + } + } + } + + /// Wait for the session to end: `Ok` after a local stop, else why it failed or closed. + pub async fn closed(&self) -> Result<(), MoqError> { + match self.settled().await? { + Some(session) => session.closed().await, + None => Ok(()), + } + } + + /// Drain an established session; a dial still running is stopped instead. + pub async fn close(&self) -> Result<(), MoqError> { + let session = self.state.read().session.clone(); + match session { + Some(session) => session.close().await, + None => { + self.stop(moq_net::Error::Cancel); + // A handshake that won the race is published already and aborted by the stop. + Ok(()) + } + } + } + + pub fn bandwidth(&self) -> moq_net::bandwidth::Allocator { + self.bandwidth.clone() + } + + pub fn recv_bandwidth(&self) -> moq_net::bandwidth::Consumer { + self.recv.consume() + } +} + +/// Dial, publish the outcome, then drive the session until it closes. +async fn run( + state: kio::Producer, + handshake: impl Future>, + send: moq_net::bandwidth::Producer, + recv: moq_net::bandwidth::Producer, +) { + let stopped = state.consume(); + let stopped = stopped.wait(|state| match state.stop { + Some(_) => Poll::Ready(()), + None => Poll::Pending, + }); + let result = tokio::select! { + biased; + _ = stopped => Err(Failure::Stopped), + result = handshake => result, + }; + + let Ok(mut published) = state.write() else { return }; + let (session, driver) = match result { + Ok(established) if published.stop.is_none() => established, + Ok((session, _)) => { + // The stop arrived during the handshake's last step. + session.abort(published.stop.clone().unwrap_or(moq_net::Error::Cancel)); + published.failed = Some(Failure::Stopped); + return; + } + Err(failure) => { + published.failed = Some(failure); + return; + } + }; + published.session = Some(Accepted { + session: session.clone(), + driver: crate::ffi::Background::default(), + }); + drop(published); + + // Mirror the session's estimates into the persistent ones its handles hold. + let forward = async { + tokio::join!( + forward_send(session.send_bandwidth(), &send), + forward_recv(&session, &recv) + ); + std::future::pending::<()>().await + }; + tokio::select! { + _ = moq_net::time::run(driver) => {} + _ = forward => {} + } + let _ = send.set(None); + let _ = recv.set(None); +} + +async fn forward_send(source: Option, out: &moq_net::bandwidth::Producer) { + let Some(mut source) = source else { return }; + while let Ok(rate) = source.changed().await { + let _ = out.set(rate); + } +} + +/// Forward the receive estimate only while someone holds `out`, since holding the +/// session's consumer is what requests PROBE. +async fn forward_recv(session: &moq_net::Session, out: &moq_net::bandwidth::Producer) { + loop { + if out.used().await.is_err() { + return; + } + let Some(mut source) = session.recv_bandwidth() else { + return; + }; + loop { + tokio::select! { + biased; + unused = out.unused() => { + if unused.is_err() { + return; + } + let _ = out.set(None); + break; + } + rate = source.changed() => match rate { + Ok(rate) => { + let _ = out.set(rate); + } + Err(_) => return, + }, + } + } + } +} diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 6b0ec675961..7b6ebd3adb6 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -15,7 +15,7 @@ use crate::json::{ }; use crate::media::*; use crate::session::{ - MoqBackoff, MoqCongestionControl, MoqConnectionStatus, MoqQuicConfig, MoqWebSocketConfig, moq_client_defaults, + MoqBackoff, MoqCongestionControl, MoqConnectionPhase, MoqQuicConfig, MoqWebSocketConfig, moq_client_defaults, moq_qlog_supported, moq_versions, }; @@ -5996,14 +5996,22 @@ async fn request_per_session_publish_override() { server.cancel(); } -/// A first dial that keeps failing never resolves `connect`, so `MoqClient::failure` is the -/// only place its reason shows until a session connects, and the connect clears it. -#[tokio::test] -async fn client_failure_names_a_failing_first_dial() { - // Hold the port with a socket that never answers, so each dial times out. - let silent = std::net::UdpSocket::bind("127.0.0.1:0").expect("bind"); - let addr = silent.local_addr().expect("local addr"); +async fn wait_phase( + session: &MoqSession, + phase: MoqConnectionPhase, +) -> Result { + let mut state = session.state(); + while state.phase != phase { + state = session.state_changed(state.revision).await?; + } + Ok(state) +} +/// The session exposes repeated first-dial failures even after its Client is released. +#[tokio::test] +async fn session_state_names_a_failing_first_dial() { + let silent = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); + let addr = silent.local_addr().unwrap(); let client = MoqClient::new(MoqClientConfig { tls: insecure_tls(), bind: Some("127.0.0.1:0".into()), @@ -6016,29 +6024,21 @@ async fn client_failure_names_a_failing_first_dial() { ..Default::default() }) .unwrap(); - assert!(client.failure().is_none(), "nothing is dialing yet"); - - let dialer = client.clone(); - let url = format!("https://{addr}"); - let connect = tokio::spawn(async move { dialer.connect(url).await }); - - let failure = tokio::time::timeout(TIMEOUT, async { - loop { - if let Some(failure) = client.failure() { - return failure; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("the failing dial never reported why"); - assert!(matches!(failure, MoqError::Connect { .. }), "{failure:?}"); - assert!( - !connect.is_finished(), - "connect resolved while the dial was still failing" - ); - - // Serve the port; the next retry lands, which resolves the connect and clears the report. + let session = client.connect(format!("https://{addr}")).await.unwrap(); + let mut state = session.state(); + assert_eq!(state.phase, MoqConnectionPhase::Connecting); + assert_eq!(state.connects, 0); + assert!(state.version.is_none()); + drop(client); + for _ in 0..2 { + state = tokio::time::timeout(TIMEOUT, session.state_changed(state.revision)) + .await + .unwrap() + .unwrap(); + assert_eq!(state.phase, MoqConnectionPhase::Connecting); + assert_eq!(state.connects, 0); + assert!(matches!(state.failure, Some(MoqError::Connect { .. }))); + } drop(silent); let server = MoqServer::new(MoqServerConfig { bind: Some(addr.to_string()), @@ -6046,27 +6046,37 @@ async fn client_failure_names_a_failing_first_dial() { ..Default::default() }) .unwrap(); - tokio::time::timeout(TIMEOUT, server.listen()) - .await - .expect("listen timed out") - .expect("listen failed"); - let request = tokio::time::timeout(TIMEOUT, server.accept()) - .await - .expect("accept timed out") - .expect("accept errored") - .expect("accept returned None"); - let server_session = request.accept(None, None).await.expect("handshake failed"); - let cs = tokio::time::timeout(TIMEOUT, connect) + server.listen().await.unwrap(); + let request = server.accept().await.unwrap().unwrap(); + let accepted = request.accept(None, None).await.unwrap(); + let connected = tokio::time::timeout(TIMEOUT, wait_phase(&session, MoqConnectionPhase::Connected)) .await - .expect("connect timed out") - .expect("connect task panicked") - .expect("connect failed"); - assert!(client.failure().is_none(), "the connect must clear the failure"); - assert!(cs.failure().is_none(), "the session has not dropped"); - - cs.cancel(0); - server_session.cancel(0); - client.cancel(); + .unwrap() + .unwrap(); + assert_eq!(connected.connects, 1); + assert!(connected.failure.is_none()); + assert!(connected.version.is_some()); + let initial_accepted = accepted.state(); + assert_eq!(initial_accepted.phase, MoqConnectionPhase::Connected); + assert_eq!(initial_accepted.connects, 1); + let ending = accepted.state_changed(initial_accepted.revision); + tokio::pin!(ending); + assert!( + std::future::poll_fn(|cx| std::task::Poll::Ready(ending.as_mut().poll(cx))) + .await + .is_pending() + ); + accepted.cancel(0); + let terminal = tokio::time::timeout(TIMEOUT, ending).await.unwrap().unwrap(); + assert_eq!(terminal.phase, MoqConnectionPhase::Closed); + assert!(terminal.version.is_none()); + assert!(terminal.failure.is_some()); + assert_eq!(accepted.state().revision, terminal.revision); + assert!(accepted.state_changed(terminal.revision).await.is_err()); + session.cancel(0); + session.closed().await.unwrap(); + assert_eq!(session.state().phase, MoqConnectionPhase::Closed); + accepted.cancel(0); server.cancel(); } @@ -6134,15 +6144,15 @@ async fn client_reconnects_and_resumes_announcements() { .expect("connect timed out") .expect("connect failed"); - // The first status is the connect this session was built from. - let status = tokio::time::timeout(TIMEOUT, cs.status()) + // Observe the first successful connect through the same state as its initial dial. + let status = tokio::time::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Connected)) .await .expect("status timed out") .expect("status errored"); - assert_eq!(status, MoqConnectionStatus::Connected); - assert_eq!(cs.connects(), 1); - assert!(cs.failure().is_none(), "nothing has failed yet"); - let version = cs.stats().version.expect("a live connection reports its version"); + assert_eq!(status.phase, MoqConnectionPhase::Connected); + assert_eq!(status.connects, 1); + assert!(status.failure.is_none(), "nothing has failed yet"); + let version = status.version.expect("a live connection reports its version"); crate::session::parse_versions(&[version]).expect("the version is spelled like the config's"); // Kill the transport under the client, simulating a relay restart. @@ -6153,34 +6163,28 @@ async fn client_reconnects_and_resumes_announcements() { .expect("accept task gone"); first.cancel(0); - let status = tokio::time::timeout(TIMEOUT, cs.status()) + let status = tokio::time::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Disconnected)) .await .expect("disconnect status timed out") .expect("disconnect status errored"); - assert_eq!(status, MoqConnectionStatus::Disconnected); + assert_eq!(status.phase, MoqConnectionPhase::Disconnected); // Recorded before the status moved, so the watcher woken by the drop finds why. - assert!(cs.failure().is_some(), "the drop must report its reason"); + assert!(status.failure.is_some(), "the drop must report its reason"); + assert!(status.version.is_none()); assert!(cs.stats().version.is_none(), "nothing is live to report a version"); // Open the gate; the redial completes. regate_tx.send(()).expect("accept task gone"); - let status = tokio::time::timeout(TIMEOUT, cs.status()) + let status = tokio::time::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Connected)) .await .expect("reconnect status timed out") .expect("reconnect status errored"); - assert_eq!(status, MoqConnectionStatus::Connected); - assert!(cs.failure().is_none(), "the reconnect must clear the failure"); + assert_eq!(status.phase, MoqConnectionPhase::Connected); + assert!(status.failure.is_none(), "the reconnect must clear the failure"); + assert!(status.version.is_some()); assert!(cs.stats().version.is_some(), "the reconnect reports its version"); - // The reconnect advances the count. The watcher may land just after the status - // edge it watched, so poll rather than assume ordering. - tokio::time::timeout(TIMEOUT, async { - while cs.connects() < 2 { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("the connect count did not advance on reconnect"); + assert_eq!(status.connects, 2, "phase and count come from one observation"); let server_session = tokio::time::timeout(TIMEOUT, accept) .await @@ -6338,7 +6342,7 @@ async fn cancel_before_connect_fails_fast() { /// edge. Every repeatable read on the bindings (`status`, `next`, `read_frame`, /// `recv_datagram`) sits on that path; `status` is just the easiest to drive. #[tokio::test] -async fn cancelled_status_does_not_swallow_the_next_transition() { +async fn cancelled_state_wait_does_not_swallow_the_next_transition() { let server = MoqServer::new(MoqServerConfig { bind: Some("127.0.0.1:0".into()), tls: localhost_tls(), @@ -6382,17 +6386,17 @@ async fn cancelled_status_does_not_swallow_the_next_transition() { .expect("server accept timed out") .expect("server accept task panicked"); - let status = tokio::time::timeout(TIMEOUT, cs.status()) + let status = tokio::time::timeout(TIMEOUT, wait_phase(&cs, MoqConnectionPhase::Connected)) .await .expect("status timed out") .expect("status errored"); - assert_eq!(status, MoqConnectionStatus::Connected); + assert_eq!(status.phase, MoqConnectionPhase::Connected); // Give up on a status that isn't coming. The window is generous on purpose: // the abandoned call has to actually reach its await for this to prove // anything, and a spawn that never got there would pass either way. assert!( - tokio::time::timeout(Duration::from_millis(200), cs.status()) + tokio::time::timeout(Duration::from_millis(200), cs.state_changed(status.revision)) .await .is_err(), "no transition was pending, so this must be the caller giving up", @@ -6401,11 +6405,11 @@ async fn cancelled_status_does_not_swallow_the_next_transition() { // The transition the abandoned call would have eaten. server_session.cancel(0); - let status = tokio::time::timeout(TIMEOUT, cs.status()) + let status = tokio::time::timeout(TIMEOUT, cs.state_changed(status.revision)) .await .expect("the cancelled waiter swallowed the disconnect") .expect("status errored"); - assert_eq!(status, MoqConnectionStatus::Disconnected); + assert_eq!(status.phase, MoqConnectionPhase::Disconnected); cs.cancel(0); server.cancel(); @@ -6653,12 +6657,9 @@ async fn session_protocol_codes_cross_the_ffi() { } } #[tokio::test] -async fn client_cancel_aborts_a_pending_connect() { - // A bound socket that never answers, so the QUIC handshake can't finish before cancel. - // A real server would not do: the dial establishes without the server accepting. +async fn cancelling_a_session_aborts_its_first_dial() { let silent = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); let addr = silent.local_addr().unwrap(); - let client = MoqClient::new(MoqClientConfig { tls: insecure_tls(), bind: Some("127.0.0.1:0".into()), @@ -6670,24 +6671,18 @@ async fn client_cancel_aborts_a_pending_connect() { ..Default::default() }) .unwrap(); - - // Poll in place rather than spawning, so cancel lands before the next poll. - let mut connect = std::pin::pin!(client.connect(format!("https://{addr}"))); - let first = std::future::poll_fn(|cx| std::task::Poll::Ready(connect.as_mut().poll(cx))).await; - assert!( - first.is_pending(), - "connect resolved before cancel: {:?}", - first.map(|result| result.map(|_| "session")), - ); - + let session = client.connect(format!("https://{addr}")).await.unwrap(); + let revision = session.state().revision; client.cancel(); - - let connect_err = tokio::time::timeout(TIMEOUT, connect).await.expect("connect timed out"); - assert!( - matches!(connect_err, Err(MoqError::Cancelled)), - "connect returned {:?}", - connect_err.map(|_| "session"), - ); + session.cancel(0); + tokio::time::timeout(TIMEOUT, session.closed()).await.unwrap().unwrap(); + let state = session.state_changed(revision).await.unwrap(); + assert_eq!(state.phase, MoqConnectionPhase::Closed); + assert_eq!(state.connects, 0); + assert!(matches!( + session.state_changed(state.revision).await, + Err(MoqError::Closed) + )); } #[tokio::test] diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index f1cf2afe0e4..1ba3645b06c 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -483,6 +483,10 @@ impl Resolved { /// distinguishes a permanent give-up from a graceful close. #[derive(Default)] struct State { + /// Advances on every lifecycle update, including identical failed dials. + revision: u64, + /// The loop has finished and cannot publish another state. + ended: bool, /// Tokens to queue before publishing a replacement session to its consumers. tokens: std::sync::Mutex>>, /// Current connection status, or `None` before the first connect. @@ -542,6 +546,7 @@ impl Shared { if state.session.is_some() { state.presence.sessions_ended += 1; } + state.revision += 1; state.status = Some(Status::Connected); state.connects += 1; state.presence.sessions_started += 1; @@ -560,6 +565,7 @@ impl Shared { fn status(&self, status: Status) { if let Ok(mut state) = self.state.write() { + state.revision += 1; state.status = Some(status); } } @@ -567,17 +573,15 @@ impl Shared { /// Nothing is live. Clears the session so a handle can't be handed a closed one, /// and drops the estimates that belonged to it. fn disconnected(&self) { + self.offline(None); + } + + fn offline(&self, failure: Option<&Error>) { if let Ok(mut state) = self.state.write() { - // Count one close per live session; a second call without an - // intervening connect (e.g. Drop after the loop already reported - // the close) must not move the counter again. - if state.session.is_some() { - state.presence.sessions_ended += 1; + state.offline(); + if let Some(failure) = failure { + state.failure = Some(failure.clone()); } - state.status = Some(Status::Disconnected); - state.version = None; - state.transport = None; - state.session = None; } let _ = self.send_bw.set(None); let _ = self.recv_bw.set(None); @@ -586,17 +590,27 @@ impl Shared { /// Record why the loop is retrying, for [`Monitor::failure`]. fn retrying(&self, err: &Error) { if let Ok(mut state) = self.state.write() { + state.revision += 1; state.failure = Some(err.clone()); } } - /// Record the error the loop gave up with, for [`Connection::closed`]. Nothing is + /// The loop is over: drop the session and publish the terminal snapshot in one + /// revision, so a watcher never sees a `Disconnected` the loop will not redial + /// from. `err` is what it gave up with, for [`Connection::closed`]. Nothing is /// retrying anymore, so [`Monitor::failure`] stops reporting. - fn failed(&self, err: Error) { + fn end(&self, err: Option) { if let Ok(mut state) = self.state.write() { - state.error = Some(err); + if state.ended { + return; + } + state.offline(); + state.ended = true; state.failure = None; + state.error = err; } + let _ = self.send_bw.set(None); + let _ = self.recv_bw.set(None); } } @@ -608,11 +622,7 @@ impl Drop for Shared { // keep the session clone parked here alive and the transport open with // nothing left able to reach it. Releasing it drops the last clone, which // is what closes the transport. - self.disconnected(); - // Nothing retries anymore, however the loop ended. - if let Ok(mut state) = self.state.write() { - state.failure = None; - } + self.end(None); } } @@ -626,7 +636,99 @@ pub struct Monitor { last_presence: moq_net::stats::Presence, } +/// The current lifecycle phase of a reconnecting connection. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Phase { + /// No session has connected yet. + Connecting, + /// A session is serving. + Connected, + /// No session is serving while the connection redials. + Disconnected, + /// The old session serves while its replacement dials. + Migrating, + /// The reconnect loop has stopped for good. + Closed, +} + +/// One coherent observation of a connection's lifecycle. +#[derive(Clone, Debug)] +pub struct Observation { + /// An opaque revision to pass back to the next state wait. + pub revision: u64, + /// The current lifecycle phase, distinct from cumulative statistics presence. + pub phase: Phase, + /// How many sessions have connected, including replacements. + pub connects: u64, + /// The latest failed attempt or terminal failure, cleared by a successful connect. + pub failure: Option, + /// The live session's negotiated version, or none while offline. + pub version: Option, +} + +impl State { + /// Nothing is live: one lifecycle revision that drops the session and its version. + fn offline(&mut self) { + // Count one close per live session; a second call without an intervening + // connect (e.g. Drop after the loop already reported the close) must not + // move the counter again. + if self.session.is_some() { + self.presence.sessions_ended += 1; + } + self.revision += 1; + self.status = Some(Status::Disconnected); + self.version = None; + self.transport = None; + self.session = None; + } + + fn observation(&self) -> Observation { + Observation { + revision: self.revision, + phase: if self.ended { + Phase::Closed + } else { + match self.status { + None => Phase::Connecting, + Some(Status::Connected) => Phase::Connected, + Some(Status::Disconnected) => Phase::Disconnected, + Some(Status::Migrating) => Phase::Migrating, + } + }, + connects: self.connects, + failure: self.error.clone().or_else(|| self.failure.clone()), + version: self.version, + } + } +} + impl Monitor { + /// Read the lifecycle fields together under one lock. + pub fn state(&self) -> Observation { + self.state.read().observation() + } + + /// Poll for a lifecycle revision different from the caller's last snapshot. + fn poll_state(&self, waiter: &kio::Waiter, after: u64) -> Poll> { + match self.state.poll(waiter, |state| { + if state.revision != after { + Poll::Ready(Ok(state.observation())) + } else if state.ended { + Poll::Ready(Err(terminal(state))) + } else { + Poll::Pending + } + }) { + Poll::Ready(Ok(result)) => Poll::Ready(result), + Poll::Ready(Err(state)) => Poll::Ready(Err(terminal(&state))), + Poll::Pending => Poll::Pending, + } + } + + /// Wait for a lifecycle revision without sharing a cursor with other observers. + pub async fn state_changed(&self, after: u64) -> crate::Result { + kio::wait(|waiter| self.poll_state(waiter, after)).await + } /// Cumulative connects and disconnects of this reconnect loop, the same shape as a relay's /// sessions track: `sessions_started - sessions_ended` is 1 while connected, and a rate is a delta over /// any window. @@ -757,15 +859,17 @@ impl Connection { let closed: CloseGuard = Default::default(); let task_closed = closed.clone(); + // Own final-state publication before spawning: aborting an unpolled task + // must still drop Shared and publish its terminal revision. + let shared = Shared { + state: producer, + send_bw, + recv_bw, + closed: task_closed, + }; let task = tokio::spawn(async move { let reconnect = client.reconnect; - let shared = Shared { - state: producer, - send_bw, - recv_bw, - closed: task_closed, - }; // Isolated inside `shared`, so a panic still records a terminal error // instead of closing the channels as if the caller had stopped it. let res = crate::panic::isolate(Self::run(&shared, client, addrs)) @@ -778,7 +882,7 @@ impl Connection { true => tracing::error!(%err, "connection loop exited"), false => tracing::info!(%err, "connection closed"), } - shared.failed(err); + shared.end(Some(err)); } // Dropping the producers here closes the channels, signaling consumers. }); @@ -896,15 +1000,6 @@ impl Connection { // persistent producers meanwhile so consumers track the live stats across the // connection, and draining any predecessor left over from a migration. let ended = run_session(shared, &session, &mut draining, client.restart).await; - // Before any status moves, so a watcher woken by `Disconnected` finds why. Only - // a retry has a reason to report; a session that ends the loop reports through - // `closed` instead. - if let Ended::Closed(Err(err)) = &ended - && client.reconnect - && !err.is_terminal() - { - shared.retrying(err); - } let tenure = connected.elapsed(); @@ -931,7 +1026,6 @@ impl Connection { // sides end up waiting on each other forever. Checked before the // migration branch below, which would otherwise loop back to redial. if !client.reconnect && matches!(ended, Ended::Goaway(_)) { - shared.disconnected(); return Ok(()); } @@ -1031,15 +1125,15 @@ impl Connection { continue; } - shared.disconnected(); - + // Both returns below leave the offline bookkeeping to the terminal + // snapshot, so they never publish a `Disconnected` first. + // // Refusals and malformed protocol input are settled failures, however long // the session lived. A new connection cannot repair either one. - if let Ended::Closed(Err(err)) = &ended { - let err = err.clone(); - if err.is_terminal() { - return Err(err); - } + if let Ended::Closed(Err(err)) = &ended + && err.is_terminal() + { + return Err(err.clone()); } // One-shot mode: the session ending ends the connection. Its close @@ -1052,6 +1146,13 @@ impl Connection { }; } + // Publish the lost transport and why, in one lifecycle observation. + let failure = match &ended { + Ended::Closed(Err(err)) => Some(err), + _ => None, + }; + shared.offline(failure); + if healthy { // The backoff window was reset, so a one-off drop reconnects promptly. tracing::warn!(peer = %Endpoint(&url), "session closed, reconnecting"); @@ -2275,6 +2376,143 @@ mod tests { config.init(Default::default()).expect("build client") } + #[test] + fn observation_keeps_independent_revisions_and_never_misses_registration() { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + use std::task::{Wake, Waker}; + struct Wakes(AtomicUsize); + impl Wake for Wakes { + fn wake(self: Arc) { + self.wake_by_ref(); + } + fn wake_by_ref(self: &Arc) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + let shared = shared(); + let first = Monitor { + state: shared.state.consume(), + last_presence: Default::default(), + }; + let second = first.clone(); + let initial = first.state(); + assert_eq!(initial.phase, Phase::Connecting); + assert_eq!(initial.connects, 0); + assert!(initial.version.is_none()); + let failure = Error::ConnectFailed; + // The update precedes registration: reading a token must not lose this wake. + shared.retrying(&failure); + let waiter = kio::Waiter::noop(); + let Poll::Ready(Ok(next)) = first.poll_state(&waiter, initial.revision) else { + panic!("missed earlier update") + }; + assert_eq!(next.phase, Phase::Connecting); + assert!(next.failure.is_some()); + assert!( + matches!(second.poll_state(&waiter, initial.revision), Poll::Ready(Ok(_))), + "independent observer lost its update" + ); + // Register first: even another failure with the same diagnostic must wake it. + let wakes = Arc::new(Wakes(AtomicUsize::new(0))); + let registered = kio::Waiter::new(Waker::from(wakes.clone())); + assert!(first.poll_state(®istered, next.revision).is_pending()); + shared.retrying(&failure); + assert!(wakes.0.load(Ordering::SeqCst) > 0); + let Poll::Ready(Ok(repeated)) = first.poll_state(&waiter, next.revision) else { + panic!("identical failed attempt was hidden") + }; + assert_ne!(repeated.revision, next.revision); + shared.end(Some(failure)); + drop(shared); + let final_state = first.state(); + assert_eq!(final_state.phase, Phase::Closed); + assert!(final_state.failure.is_some(), "terminal cause must remain observable"); + assert!( + matches!(first.poll_state(&waiter, repeated.revision), Poll::Ready(Ok(state)) if state.phase == Phase::Closed) + ); + assert!(matches!( + first.poll_state(&waiter, final_state.revision), + Poll::Ready(Err(_)) + )); + } + + #[tokio::test] + async fn cancelled_observation_does_not_advance_another_waiter() { + let shared = shared(); + let monitor = Monitor { + state: shared.state.consume(), + last_presence: Default::default(), + }; + let revision = monitor.state().revision; + { + let mut abandoned = std::pin::pin!(monitor.state_changed(revision)); + assert!(futures::poll!(&mut abandoned).is_pending()); + } + shared.retrying(&Error::ConnectFailed); + let first = monitor.state_changed(revision).await.unwrap(); + let second = monitor.state_changed(revision).await.unwrap(); + assert_eq!(first.revision, second.revision); + } + + /// Records the phase a watcher reads the moment it is woken, as one on another thread could. + struct Woken(Monitor, std::sync::Mutex>); + + impl std::task::Wake for Woken { + fn wake(self: std::sync::Arc) { + self.wake_by_ref(); + } + fn wake_by_ref(self: &std::sync::Arc) { + self.1.lock().unwrap().push(self.0.state().phase); + } + } + + impl Woken { + /// Park on the monitor's current revision, for as long as the returned waiter lives. + fn watch(monitor: &Monitor) -> (std::sync::Arc, kio::Waiter) { + let woken = std::sync::Arc::new(Self(monitor.clone(), Default::default())); + let waiter = kio::Waiter::new(std::task::Waker::from(woken.clone())); + assert!(monitor.poll_state(&waiter, monitor.state().revision).is_pending()); + (woken, waiter) + } + + fn phases(&self) -> Vec { + self.1.lock().unwrap().clone() + } + } + + #[test] + fn ending_the_loop_never_shows_a_redialing_phase() { + let shared = shared(); + let monitor = Monitor { + state: shared.state.consume(), + last_presence: Default::default(), + }; + let (woken, _waiter) = Woken::watch(&monitor); + drop(shared); + assert_eq!(woken.phases(), [Phase::Closed]); + } + + #[cfg(feature = "tcp")] + #[tokio::test] + async fn aborting_before_the_loop_is_polled_publishes_its_final_snapshot() { + // The current-thread runtime cannot poll the spawned loop before our first await. + let connection = Connection::new( + client(), + Addrs::collect([Url::parse("http://127.0.0.1:1").unwrap()]).unwrap(), + ); + let monitor = connection.monitor(); + let initial = monitor.state(); + connection.abort(moq_net::Error::Cancel); + connection.closed().await.unwrap(); + let final_state = monitor.state_changed(initial.revision).await.unwrap(); + assert_eq!(final_state.phase, Phase::Closed); + assert_eq!(final_state.connects, 0); + assert!(monitor.state_changed(final_state.revision).await.is_err()); + } + fn shared() -> Shared { Shared { state: kio::Producer::default(), @@ -2547,12 +2785,21 @@ mod tests { let monitor = connection.monitor(); let session = tokio::time::timeout(WAIT, accepted.recv()).await.unwrap().unwrap(); + let mut state = monitor.state(); + while state.phase != Phase::Connected { + state = tokio::time::timeout(WAIT, monitor.state_changed(state.revision)) + .await + .unwrap() + .unwrap(); + } + let (woken, _waiter) = Woken::watch(&monitor); session.abort(moq_net::Error::App(7)); let closed = tokio::time::timeout(WAIT, connection.closed()) .await .expect("the connection did not close"); assert!(closed.is_err(), "the abort ends the loop with an error"); assert!(monitor.failure().is_none(), "nothing is retrying"); + assert_eq!(woken.phases(), [Phase::Closed], "the loop is not redialing"); } /// A settled answer from one candidate ends the walk instead of being buried. diff --git a/swift/MIGRATE.md b/swift/MIGRATE.md index 4557d249cd4..df8d029a81c 100644 --- a/swift/MIGRATE.md +++ b/swift/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Connection state + +`Client.connect(to:)` returns a connecting native session. Replace `status()`, `connects()`, and both `failure()` polls with `state()` and `stateChanged(after: state.revision)`. Use `ConnectionState.phase`, `connects`, `failure`, and `version`; `ConnectionPhase` replaces `ConnectionStatus`. + ### Exact encoder rates and publication options Raw video input framerates are exact numerator/denominator records, not integers. diff --git a/swift/Sources/Moq/Aliases.swift b/swift/Sources/Moq/Aliases.swift index 21b54d9ffe5..3a99de9ee17 100644 --- a/swift/Sources/Moq/Aliases.swift +++ b/swift/Sources/Moq/Aliases.swift @@ -94,8 +94,11 @@ public typealias CongestionControl = MoqFFI.MoqCongestionControl /// The WebSocket fallback raced against QUIC: whether it runs and QUIC's head start. public typealias WebSocketConfig = MoqFFI.MoqWebSocketConfig -/// A connection lifecycle transition reported by `Session.status()`. -public typealias ConnectionStatus = MoqFFI.MoqConnectionStatus +/// The connection lifecycle phase. +public typealias ConnectionPhase = MoqFFI.MoqConnectionPhase + +/// One coherent connection lifecycle snapshot. +public typealias ConnectionState = MoqFFI.MoqConnectionState /// The network transport carrying an incoming session. public typealias Transport = MoqFFI.MoqTransport diff --git a/swift/Sources/Moq/Client.swift b/swift/Sources/Moq/Client.swift index 4f0bb638118..cfdfc349968 100644 --- a/swift/Sources/Moq/Client.swift +++ b/swift/Sources/Moq/Client.swift @@ -54,7 +54,7 @@ public final class Client: Sendable { )) } - /// Connect and wait for the session to be established. Cancellable via `cancel()`. + /// Start a connection and return its session without waiting for the native first dial to succeed. public func connect(to url: String) async throws -> Session { Session(try await ffi.connect(url: url)) } @@ -64,15 +64,7 @@ public final class Client: Sendable { ffi.cancel() } - /// Why the pending `connect(to:)` is still dialing: the error that failed its - /// latest attempt, or `nil` while nothing has failed or no connect is pending. - /// - /// A first dial that keeps failing and retrying never returns from `connect(to:)`, - /// so poll this to show the reason. Giving up for good throws from `connect(to:)` - /// instead. Once connected, `Session.failure()` reports the reconnects. - public func failure() -> MoqError? { - ffi.failure() - } + } /// The protocol versions offered by default, most preferred first, spelled the way @@ -86,7 +78,7 @@ public func qlogSupported() -> Bool { moqQlogSupported() } -/// An established MoQ session. +/// A MoQ session, including its initial native dial. public final class Session: Sendable { let ffi: MoqSession @@ -108,41 +100,19 @@ public final class Session: Sendable { /// Suspend until the session is over: an error when the connection gave up for /// good, a normal return after a local `shutdown()`/`cancel()`. Transient drops - /// the reconnect loop rides out don't resolve this; watch `status()` for those. + /// the reconnect loop rides out don't resolve this; watch `stateChanged(after:)` for those. public func closed() async throws { try await ffi.closed() } - /// Suspend until the connection status differs from the one last reported. A - /// client session reports `.connected` first, then follows the reconnect loop - /// (`.disconnected` while redialing, `.migrating` during a GOAWAY handover) and - /// throws once the connection stops for good. A server-accepted session's only - /// transition is terminal: this waits for the close and throws its reason. - /// - /// This is the current status, not a queue of every edge: a drop that - /// reconnects before you ask again is coalesced away, so the outages it hides - /// are the ones that already healed. Don't count outages with it. - public func status() async throws -> ConnectionStatus { - try await ffi.status() - } - - /// How many times this session has connected: 1 for the connect that built it, one more - /// on each reconnect. A server-accepted session stays at 1. - /// - /// Pair it with `status()` to log each reconnect by number: a `.connected` - /// status whose count grew is a reconnect. - public func connects() -> UInt64 { - ffi.connects() + /// Read one coherent lifecycle snapshot without advancing a watcher. + public func state() -> ConnectionState { + ffi.state() } - /// Why a client session is reconnecting: the error that ended the last - /// connection or failed the latest redial, or `nil` once a connection lands. - /// - /// A redial that keeps failing never changes `status()`, so poll this while it - /// reports `.disconnected` to show the reason. Giving up for good throws from - /// `closed()` instead. A server-accepted session always returns `nil`. - public func failure() -> MoqError? { - ffi.failure() + /// Wait for a revision different from `after`; independent callers retain their own revisions. + public func stateChanged(after: UInt64) async throws -> ConnectionState { + try await ffi.stateChanged(after: after) } /// Close the session with the given error code. Code 0 means "no error"; diff --git a/swift/ffi/MIGRATE.md b/swift/ffi/MIGRATE.md index 99bcbe61794..1869c0a2795 100644 --- a/swift/ffi/MIGRATE.md +++ b/swift/ffi/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Connection state + +Generated connection APIs now expose `MoqConnectionState` and `MoqConnectionPhase`, with `state()` and revision-based `state_changed(after)` instead of status, connect-count, and failure polls. Connect returns before its first dial completes. Regenerate bindings from the matching Rust metadata. + ### Exact encoder rates and publication options Encoder configuration is breaking: `MoqVideoEncoderInput.framerate` is now a diff --git a/test/interop/clients/c/subscribe.c b/test/interop/clients/c/subscribe.c index 36660993927..662a2660455 100644 --- a/test/interop/clients/c/subscribe.c +++ b/test/interop/clients/c/subscribe.c @@ -67,7 +67,7 @@ typedef struct { // Callbacks run on moq-c's runtime thread; main waits on the condvar. ctx lives // on main's stack and moq-c keeps the pointer until each registration's // terminal (<= 0) callback fires, so main must not return until every one of -// them has. Closing the session ends its status registration alone; +// them has. Closing the session ends its state registration alone; // moq_origin_announced_broadcast, moq_consume_catalog and moq_consume_video each // keep the pointer until their own terminal. See drain() at the bottom. static void done(ctx_t *c, int *flag) { @@ -77,17 +77,18 @@ static void done(ctx_t *c, int *flag) { pthread_mutex_unlock(&c->mu); } -static void on_status(void *ud, int32_t code) { +static void on_state(void *ud, const moq_connection_state *state) { ctx_t *c = (ctx_t *)ud; - fprintf(stderr, "session status: %d\n", code); - if (c->finish.enabled && code > 0) { + fprintf(stderr, "session state: phase=%d connects=%llu failure=%d\n", (int)state->phase, + (unsigned long long)state->connects, state->failure); + if (c->finish.enabled && state->connects > 0) { pthread_mutex_lock(&c->mu); - c->finish.connected = code; - if (code > 1) c->finish.failed = 1; + c->finish.connected = (int)state->connects; + if (state->connects > 1) c->finish.failed = 1; pthread_cond_broadcast(&c->cv); pthread_mutex_unlock(&c->mu); } - if (code <= 0) done(c, &c->done_status); + if (state->phase == MOQ_CONNECTION_PHASE_CLOSED) done(c, &c->done_status); } static void on_frame(void *ud, int32_t frame) { @@ -506,7 +507,7 @@ int main(int argc, char **argv) { } // origin_publish = 0 disables publishing; consume via our origin. - c.session = moq_session_connect(url, strlen(url), version ? &config : NULL, 0, (uint32_t)c.origin, on_status, &c); + c.session = moq_session_connect(url, strlen(url), version ? &config : NULL, 0, (uint32_t)c.origin, on_state, &c); if (c.session <= 0) { // A registration that fails never invokes its callback, so &c isn't held // yet and returning is still safe here. diff --git a/test/interop/clients/cpp/main.cpp b/test/interop/clients/cpp/main.cpp index 505daa92e8d..1d9c8877ec6 100644 --- a/test/interop/clients/cpp/main.cpp +++ b/test/interop/clients/cpp/main.cpp @@ -257,7 +257,7 @@ int publish( // Only teardown waits on the FIFO; linger has already completed on its own clock. std::ifstream ack(finish_ack); std::string line; - if (!std::getline(ack, line) || line != "complete" || session->connects() != 1) { + if (!std::getline(ack, line) || line != "complete" || session->state().connects != 1) { fail("finish acknowledgement or session continuity failed"); } ok(health->close(), "health close"); @@ -382,7 +382,7 @@ int subscribe( fail("health payload or timestamp"); } if (until(group->read_frame(), read_deadline, "health group EOF") || - until(track->next_group(), read_deadline, "health track EOF") || session->connects() != 1) { + until(track->next_group(), read_deadline, "health track EOF") || session->state().connects != 1) { fail("health EOF or session continuity"); } std::printf("finish clean frames=%zu catalog=eof announce=end health=ok\n", frames); diff --git a/test/interop/clients/go/main.go b/test/interop/clients/go/main.go index 83c99799cee..b164dd79474 100644 --- a/test/interop/clients/go/main.go +++ b/test/interop/clients/go/main.go @@ -263,7 +263,7 @@ func publish(ctx context.Context, url, broadcast string, opts dialOptions, timeo if command != "complete\n" { return errors.New("expected finish completion acknowledgement") } - if client.Session().Connects() != 1 { + if client.Session().State().Connects != 1 { return errors.New("publisher reconnected during finish") } fmt.Println("finish acknowledged") @@ -434,7 +434,7 @@ func finishSubscribe(ctx context.Context, client *moq.Client, broadcast string, next.Cancel() return errors.New("session health track did not end after one group") } - if client.Session().Connects() != 1 { + if client.Session().State().Connects != 1 { return errors.New("subscriber reconnected during finish") } fmt.Printf("finish clean frames=%d catalog=eof announce=end health=ok\n", frames) diff --git a/test/interop/clients/python/interop.py b/test/interop/clients/python/interop.py index b85b0422fad..7d58336ee68 100644 --- a/test/interop/clients/python/interop.py +++ b/test/interop/clients/python/interop.py @@ -164,7 +164,7 @@ def acknowledge() -> None: raise RuntimeError("expected finish completion acknowledgement") await loop.run_in_executor(None, acknowledge) - if client.session is None or client.session.connects() != 1: + if client.session is None or client.session.state().connects != 1: raise RuntimeError("publisher reconnected during finish") print("finish acknowledged", flush=True) @@ -234,7 +234,7 @@ async def _finish_subscribe(client: moq.Client, broadcast: str, frames: int) -> seen = True if not seen: raise RuntimeError("missing session health payload") - if client.session is None or client.session.connects() != 1: + if client.session is None or client.session.state().connects != 1: raise RuntimeError("subscriber reconnected during finish") print(f"finish clean frames={frames} catalog=eof announce=end health=ok", flush=True) diff --git a/test/smoke/clients/c/subscribe.c b/test/smoke/clients/c/subscribe.c index 5138d2c4523..6e3aafa7fe9 100644 --- a/test/smoke/clients/c/subscribe.c +++ b/test/smoke/clients/c/subscribe.c @@ -29,9 +29,10 @@ typedef struct { // Callbacks run on libmoq's runtime thread; main waits on the condvar. ctx // lives on main's stack and outlives the callbacks (main blocks until got/ // timeout, then the process exits), so there's no use-after-free. -static void on_status(void *ud, int32_t code) { +static void on_state(void *ud, const moq_connection_state *state) { (void)ud; - fprintf(stderr, "session status: %d\n", code); + fprintf(stderr, "session state: phase=%d connects=%llu failure=%d\n", (int)state->phase, + (unsigned long long)state->connects, state->failure); } static void on_frame(void *ud, int32_t frame) { @@ -115,7 +116,7 @@ int main(int argc, char **argv) { // NULL config dials with the defaults; origin_publish = 0 disables // publishing; consume via our origin. - int32_t session = moq_session_connect(url, strlen(url), NULL, 0, (uint32_t)origin, on_status, &c); + int32_t session = moq_session_connect(url, strlen(url), NULL, 0, (uint32_t)origin, on_state, &c); if (session <= 0) { fprintf(stderr, "error: moq_session_connect failed: %d\n", session); return 1; diff --git a/test/wasm/uniffi/cases.ts b/test/wasm/uniffi/cases.ts index 2472f40b1f0..fb08d31051b 100644 --- a/test/wasm/uniffi/cases.ts +++ b/test/wasm/uniffi/cases.ts @@ -12,6 +12,8 @@ import { MoqClient, MoqClientConfig, MoqClientTls, + MoqConnectionPhase, + type MoqConnectionState, type MoqGroupConsumer, type MoqGroupConsumerLike, type MoqSessionLike, @@ -110,21 +112,42 @@ async function pending(promise: Promise): Promise { return !settled; } -async function connect(relay: Relay): Promise { - const response = await fetch(new URL("/certificate.sha256", relay.url)); - if (!response.ok) throw new Error(`certificate HTTP ${response.status}`); +/** Start a dial to `relay`, trusting `fingerprint` (the relay's own by default). */ +async function dial(relay: Relay, fingerprint?: string): Promise { + if (fingerprint === undefined) { + const response = await fetch(new URL("/certificate.sha256", relay.url)); + if (!response.ok) throw new Error(`certificate HTTP ${response.status}`); + fingerprint = (await response.text()).trim(); + } const url = new URL(relay.url); url.protocol = "https:"; const client = new MoqClient( MoqClientConfig.create({ - // moq-ffi exposes no negotiated version, so offering only the expected one is the check. + // Offering only the expected version makes connecting the check. versions: [relay.version], - tls: MoqClientTls.create({ fingerprints: [(await response.text()).trim()] }), + tls: MoqClientTls.create({ fingerprints: [fingerprint] }), }), ); return client.connect(url.toString()); } +/** Wait for the dial to settle, returning its state. */ +async function settled(session: MoqSessionLike): Promise { + let state = session.state(); + while (state.phase === MoqConnectionPhase.Connecting) { + state = await within(session.stateChanged(state.revision), 10000, "dial"); + } + return state; +} + +/** Connect to `relay`, failing unless the session establishes. */ +async function connect(relay: Relay): Promise { + const session = await dial(relay); + const state = await settled(session); + if (state.phase !== MoqConnectionPhase.Connected) throw new Error(`dial ended: ${state.failure}`); + return session; +} + /** A standalone group with a consumer, no session. */ function localTrack() { const broadcast = new MoqBroadcastProducer(); @@ -272,7 +295,38 @@ const local: Record Promise> = { const remote: Record Promise> = { "negotiates the relay's version": async (relay) => { const session = await connect(relay); + const state = session.state(); + session.cancel(0); + if (state.version !== relay.version) throw new Error(`negotiated ${state.version}`); + if (state.connects !== 1n) throw new Error(`connects ${state.connects}`); + return undefined; + }, + + "connect returns before a refused dial and reports it": async (relay) => { + // A certificate hash nothing matches, so the browser refuses the handshake. + const session = await dial(relay, "00".repeat(32)); + const first = session.state(); + if (first.phase !== MoqConnectionPhase.Connecting) throw new Error(`returned ${first.phase}`); + const state = await settled(session); + if (state.phase !== MoqConnectionPhase.Closed) throw new Error(`settled ${state.phase}`); + if (!state.failure) throw new Error("no failure reported"); + const closed = await settle( + session.closed(), + 5000, + "closed", + () => "resolved", + (err: unknown) => (err as Error).message, + ); + if (closed === "resolved") throw new Error("closed resolved after a refused dial"); + return closed; + }, + + "cancelling a dial closes it": async (relay) => { + const session = await dial(relay); session.cancel(0); + const state = await settled(session); + if (state.phase !== MoqConnectionPhase.Closed) throw new Error(`settled ${state.phase}`); + await within(session.closed(), 5000, "closed"); return undefined; },