diff --git a/c/moq/MIGRATE.md b/c/moq/MIGRATE.md index cfa3a5b8eab..d80ff8da638 100644 --- a/c/moq/MIGRATE.md +++ b/c/moq/MIGRATE.md @@ -6,6 +6,10 @@ How to update your code for each breaking change, newest first. The hand-written crate never published as moq-c: a libmoq 0.6 user applies these entries before moving to the generated API. +### Session allocator ([#6751](https://github.com/moq-dev/moq/pull/6751)) + +`moq_session_bandwidth` is `moq_session_allocator`, `moq_bandwidth_reserve` is `moq_allocator_reserve`, and `moq_bandwidth_close` is `moq_allocator_close`, matching `moq_net::bandwidth::Allocator`. `moq_reservation_grant` is `moq_reservation_rate`, matching `moq_net::bandwidth::Reservation::rate()`. Signatures are unchanged. The receive estimate keeps its names (`moq_session_recv_bandwidth`, `moq_bandwidth_consumer_*`). + ### 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)`. diff --git a/cpp/obs/src/moq-output.cpp b/cpp/obs/src/moq-output.cpp index f39c990d3ac..752ea8c3775 100644 --- a/cpp/obs/src/moq-output.cpp +++ b/cpp/obs/src/moq-output.cpp @@ -260,7 +260,7 @@ void MoQOutput::OnConnect(const std::shared_ptr ¤t, moq::expected current->session = *result; { std::lock_guard lock(media_mutex); - bandwidth = current->session->bandwidth(); + allocator = current->session->allocator(); } { std::lock_guard lock(mutex); @@ -399,7 +399,7 @@ void MoQOutput::Reset() track.producer->finish(); } audio_tracks.clear(); - bandwidth.reset(); + allocator.reset(); // Close the broadcast so the origin retracts it immediately; Start() // creates a fresh one on restart. @@ -677,7 +677,7 @@ void MoQOutput::VideoData(struct encoder_packet *packet) // Read before the frame is written, so a retune lands on the encoder's next // frame. obs_encoder_update only flags an active encoder for its own thread. if (track.rate && track.reservation) { - if (auto next = track.rate->Update(track.reservation->grant(), MoQRate::Clock::now())) + if (auto next = track.rate->Update(track.reservation->rate(), MoQRate::Clock::now())) SetBitrate(encoder, *next); } @@ -698,7 +698,7 @@ void MoQOutput::VideoData(struct encoder_packet *packet) // NOTE: Caller must hold media_mutex. void MoQOutput::Reserve(Track &track) { - if (track.reservation || !bandwidth || track.bitrate_bps == 0) + if (track.reservation || !allocator || track.bitrate_bps == 0) return; auto demand = track.producer->demand(); if (!demand) { @@ -706,7 +706,7 @@ void MoQOutput::Reserve(Track &track) track.bitrate_bps = 0; return; } - track.reservation = bandwidth->reserve(*demand, track.bitrate_bps); + track.reservation = allocator->reserve(*demand, track.bitrate_bps); } // NOTE: Caller must hold media_mutex. diff --git a/cpp/obs/src/moq-output.h b/cpp/obs/src/moq-output.h index a54c6559ae3..00ed4ea892c 100644 --- a/cpp/obs/src/moq-output.h +++ b/cpp/obs/src/moq-output.h @@ -191,7 +191,7 @@ class MoQOutput { std::map audio_tracks; // The session's allocator once it connects. It survives reconnects: grants // read empty while disconnected and resume on the next connection. - std::shared_ptr bandwidth; + std::shared_ptr allocator; // `closed()` of retired sessions still draining, which the destructor waits // out. Guarded by signal_mutex. diff --git a/dart/moq/MIGRATE.md b/dart/moq/MIGRATE.md index 30b8f73849f..3a3ee2ab154 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 +### `Allocator` ([#6751](https://github.com/moq-dev/moq/pull/6751)) + +`Bandwidth` is `Allocator`, `bandwidth()` is `allocator()`, and `Reservation.grant()` is `rate()`. The producers' `bandwidth` option keeps its name. + ### Decoders read gaps and ends `audio.Consumer.next()` and `video.Consumer.next()` return a `Read` instead of a frame. Take `read.frame` from a `ReadFrame` where you used the frame; `ReadGap` marks lost media and `ReadEnd` where the publisher stopped its encoder, and what follows either does not continue what came before. diff --git a/dart/moq/lib/src/aliases.dart b/dart/moq/lib/src/aliases.dart index a1dfc8787d9..69e4f15118e 100644 --- a/dart/moq/lib/src/aliases.dart +++ b/dart/moq/lib/src/aliases.dart @@ -142,12 +142,12 @@ typedef FetchGroupOptions = MoqFetchGroupOptions; typedef TrackInfo = MoqTrackInfo; /// Divides one connection's send estimate among the tracks sharing it. -typedef Bandwidth = MoqBandwidth; +typedef Allocator = MoqAllocator; /// An owned bandwidth estimate; release it to stop receive PROBE demand. typedef BandwidthConsumer = MoqBandwidthConsumer; -/// One track's standing claim on a [Bandwidth]. +/// One track's standing claim on an [Allocator]. typedef Reservation = MoqReservation; /// A snapshot of transport connection statistics. diff --git a/dart/moq/lib/src/client.dart b/dart/moq/lib/src/client.dart index e5bb1f15e3f..713434feebb 100644 --- a/dart/moq/lib/src/client.dart +++ b/dart/moq/lib/src/client.dart @@ -239,10 +239,10 @@ final class Moq { /// The session's bandwidth allocator. /// - /// Every call returns a handle to the same registry. [Bandwidth.reserve] + /// Every call returns a handle to the same registry. [Allocator.reserve] /// a share for an app-owned encoder; dropping the [Reservation] hands /// the room back. - Bandwidth bandwidth() => session.bandwidth(); + Allocator allocator() => session.allocator(); /// Follow the grant the peer gave this session. /// diff --git a/dart/moq/test/moq_test.dart b/dart/moq/test/moq_test.dart index cd3f2e7c228..16fc6c33e86 100644 --- a/dart/moq/test/moq_test.dart +++ b/dart/moq/test/moq_test.dart @@ -238,7 +238,7 @@ void main() { ), ).timeout(timeout); final serverSession = await accepted; - expect(client.bandwidth(), isA()); + expect(client.allocator(), isA()); final announcement = client.announced().updates().firstWhere( (event) => event is AnnounceEventStart, diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index cb9603b2c64..79e5421a936 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -474,7 +474,7 @@ class MoqAudioProducerOptions { final MoqAudioEncoderInput input; final MoqAudioEncoderOutput output; final String? track; - final MoqBandwidth? bandwidth; + final MoqAllocator? bandwidth; MoqAudioProducerOptions({ required this.input, required this.output, @@ -505,7 +505,7 @@ class FfiConverterMoqAudioProducerOptions { ); final track = track_lifted.value; new_offset += track_lifted.bytesRead; - final bandwidth_lifted = FfiConverterOptionalMoqBandwidth.read( + final bandwidth_lifted = FfiConverterOptionalMoqAllocator.read( Uint8List.view(buf.buffer, new_offset), ); final bandwidth = bandwidth_lifted.value; @@ -526,7 +526,7 @@ class FfiConverterMoqAudioProducerOptions { FfiConverterMoqAudioEncoderInput.allocationSize(value.input) + FfiConverterMoqAudioEncoderOutput.allocationSize(value.output) + FfiConverterOptionalString.allocationSize(value.track) + - FfiConverterOptionalMoqBandwidth.allocationSize(value.bandwidth) + + FfiConverterOptionalMoqAllocator.allocationSize(value.bandwidth) + 0; final buf = Uint8List(total_length); write(value, buf); @@ -547,7 +547,7 @@ class FfiConverterMoqAudioProducerOptions { value.track, Uint8List.view(buf.buffer, new_offset), ); - new_offset += FfiConverterOptionalMoqBandwidth.write( + new_offset += FfiConverterOptionalMoqAllocator.write( value.bandwidth, Uint8List.view(buf.buffer, new_offset), ); @@ -558,7 +558,7 @@ class FfiConverterMoqAudioProducerOptions { return FfiConverterMoqAudioEncoderInput.allocationSize(value.input) + FfiConverterMoqAudioEncoderOutput.allocationSize(value.output) + FfiConverterOptionalString.allocationSize(value.track) + - FfiConverterOptionalMoqBandwidth.allocationSize(value.bandwidth) + + FfiConverterOptionalMoqAllocator.allocationSize(value.bandwidth) + 0; } } @@ -4720,7 +4720,7 @@ class MoqVideoProducerOptions { final MoqVideoEncoderInput input; final MoqVideoEncoderOutput output; final String? track; - final MoqBandwidth? bandwidth; + final MoqAllocator? bandwidth; final MoqVideoProducer? lower; MoqVideoProducerOptions({ required this.input, @@ -4753,7 +4753,7 @@ class FfiConverterMoqVideoProducerOptions { ); final track = track_lifted.value; new_offset += track_lifted.bytesRead; - final bandwidth_lifted = FfiConverterOptionalMoqBandwidth.read( + final bandwidth_lifted = FfiConverterOptionalMoqAllocator.read( Uint8List.view(buf.buffer, new_offset), ); final bandwidth = bandwidth_lifted.value; @@ -4780,7 +4780,7 @@ class FfiConverterMoqVideoProducerOptions { FfiConverterMoqVideoEncoderInput.allocationSize(value.input) + FfiConverterMoqVideoEncoderOutput.allocationSize(value.output) + FfiConverterOptionalString.allocationSize(value.track) + - FfiConverterOptionalMoqBandwidth.allocationSize(value.bandwidth) + + FfiConverterOptionalMoqAllocator.allocationSize(value.bandwidth) + FfiConverterOptionalMoqVideoProducer.allocationSize(value.lower) + 0; final buf = Uint8List(total_length); @@ -4802,7 +4802,7 @@ class FfiConverterMoqVideoProducerOptions { value.track, Uint8List.view(buf.buffer, new_offset), ); - new_offset += FfiConverterOptionalMoqBandwidth.write( + new_offset += FfiConverterOptionalMoqAllocator.write( value.bandwidth, Uint8List.view(buf.buffer, new_offset), ); @@ -4817,7 +4817,7 @@ class FfiConverterMoqVideoProducerOptions { return FfiConverterMoqVideoEncoderInput.allocationSize(value.input) + FfiConverterMoqVideoEncoderOutput.allocationSize(value.output) + FfiConverterOptionalString.allocationSize(value.track) + - FfiConverterOptionalMoqBandwidth.allocationSize(value.bandwidth) + + FfiConverterOptionalMoqAllocator.allocationSize(value.bandwidth) + FfiConverterOptionalMoqVideoProducer.allocationSize(value.lower) + 0; } @@ -9047,29 +9047,29 @@ class FfiConverterMoqGrantConsumer { } } -abstract class MoqBandwidthInterface { +abstract class MoqAllocatorInterface { MoqReservation reserve({required MoqTrackDemand demand, required int maxBps}); } -final _MoqBandwidthFinalizer = Finalizer>((ptr) { - rustCall((status) => uniffi_moq_ffi_fn_free_moqbandwidth(ptr, status)); +final _MoqAllocatorFinalizer = Finalizer>((ptr) { + rustCall((status) => uniffi_moq_ffi_fn_free_moqallocator(ptr, status)); }); -class MoqBandwidth implements MoqBandwidthInterface { +class MoqAllocator implements MoqAllocatorInterface { late final Pointer _ptr; bool _isDisposed = false; - MoqBandwidth._(this._ptr) { - _MoqBandwidthFinalizer.attach(this, _ptr, detach: this); + MoqAllocator._(this._ptr) { + _MoqAllocatorFinalizer.attach(this, _ptr, detach: this); } - factory MoqBandwidth.lift(Pointer ptr) { - return MoqBandwidth._(ptr); + factory MoqAllocator.lift(Pointer ptr) { + return MoqAllocator._(ptr); } Pointer uniffiClonePointer() { if (_isDisposed) { throw StateError("Object has already been disposed"); } return rustCall( - (status) => uniffi_moq_ffi_fn_clone_moqbandwidth(_ptr, status), + (status) => uniffi_moq_ffi_fn_clone_moqallocator(_ptr, status), ); } @@ -9078,8 +9078,8 @@ class MoqBandwidth implements MoqBandwidthInterface { return; } _isDisposed = true; - _MoqBandwidthFinalizer.detach(this); - rustCall((status) => uniffi_moq_ffi_fn_free_moqbandwidth(_ptr, status)); + _MoqAllocatorFinalizer.detach(this); + rustCall((status) => uniffi_moq_ffi_fn_free_moqallocator(_ptr, status)); } MoqReservation reserve({ @@ -9087,7 +9087,7 @@ class MoqBandwidth implements MoqBandwidthInterface { required int maxBps, }) { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqbandwidth_reserve( + (status) => uniffi_moq_ffi_fn_method_moqallocator_reserve( uniffiClonePointer(), FfiConverterMoqTrackDemand.lower(demand), FfiConverterUInt64.lower(maxBps), @@ -9099,26 +9099,26 @@ class MoqBandwidth implements MoqBandwidthInterface { } } -class FfiConverterMoqBandwidth { - static MoqBandwidth lift(Pointer ptr) { - return MoqBandwidth.lift(ptr); +class FfiConverterMoqAllocator { + static MoqAllocator lift(Pointer ptr) { + return MoqAllocator.lift(ptr); } - static Pointer lower(MoqBandwidth value) { + static Pointer lower(MoqAllocator value) { return value.uniffiClonePointer(); } - static int allocationSize(MoqBandwidth value) { + static int allocationSize(MoqAllocator value) { return 8; } - static LiftRetVal read(Uint8List buf) { + static LiftRetVal read(Uint8List buf) { final handle = buf.buffer.asByteData(buf.offsetInBytes).getInt64(0); final pointer = Pointer.fromAddress(handle); - return LiftRetVal(MoqBandwidth.lift(pointer), 8); + return LiftRetVal(MoqAllocator.lift(pointer), 8); } - static int write(MoqBandwidth value, Uint8List buf) { + static int write(MoqAllocator value, Uint8List buf) { final handle = lower(value); buf.buffer.asByteData(buf.offsetInBytes).setInt64(0, handle.address); return 8; @@ -9228,7 +9228,7 @@ class FfiConverterMoqBandwidthConsumer { } abstract class MoqReservationInterface { - int? grant(); + int? rate(); void update({required int maxBps}); } @@ -9263,9 +9263,9 @@ class MoqReservation implements MoqReservationInterface { rustCall((status) => uniffi_moq_ffi_fn_free_moqreservation(_ptr, status)); } - int? grant() { + int? rate() { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqreservation_grant( + (status) => uniffi_moq_ffi_fn_method_moqreservation_rate( uniffiClonePointer(), status, ), @@ -13650,7 +13650,7 @@ class FfiConverterMoqClient { } abstract class MoqSessionInterface { - MoqBandwidth bandwidth(); + MoqAllocator allocator(); void cancel({required int code}); UniffiRustFuture closed(); MoqOriginConsumer consume(); @@ -13695,13 +13695,13 @@ class MoqSession implements MoqSessionInterface { rustCall((status) => uniffi_moq_ffi_fn_free_moqsession(_ptr, status)); } - MoqBandwidth bandwidth() { + MoqAllocator allocator() { return rustCallWithLifter( - (status) => uniffi_moq_ffi_fn_method_moqsession_bandwidth( + (status) => uniffi_moq_ffi_fn_method_moqsession_allocator( uniffiClonePointer(), status, ), - FfiConverterMoqBandwidth.lift, + FfiConverterMoqAllocator.lift, null, ); } @@ -14888,6 +14888,53 @@ class FfiConverterOptionalDuration { } } +class FfiConverterOptionalMoqAllocator { + static MoqAllocator? lift(RustBuffer buf) { + return FfiConverterOptionalMoqAllocator.read(buf.asUint8List()).value; + } + + static LiftRetVal read(Uint8List buf) { + if (ByteData.view(buf.buffer, buf.offsetInBytes).getInt8(0) == 0) { + return LiftRetVal(null, 1); + } + final result = FfiConverterMoqAllocator.read( + Uint8List.view(buf.buffer, buf.offsetInBytes + 1), + ); + return LiftRetVal(result.value, result.bytesRead + 1); + } + + static int allocationSize([MoqAllocator? value]) { + if (value == null) { + return 1; + } + return FfiConverterMoqAllocator.allocationSize(value) + 1; + } + + static RustBuffer lower(MoqAllocator? value) { + if (value == null) { + return toRustBuffer(Uint8List.fromList([0])); + } + final buf = Uint8List( + FfiConverterOptionalMoqAllocator.allocationSize(value), + ); + FfiConverterOptionalMoqAllocator.write(value, buf); + return toRustBuffer(buf); + } + + static int write(MoqAllocator? value, Uint8List buf) { + if (value == null) { + buf[0] = 0; + return 1; + } + buf[0] = 1; + return FfiConverterMoqAllocator.write( + value, + Uint8List.view(buf.buffer, buf.offsetInBytes + 1), + ) + + 1; + } +} + class FfiConverterOptionalMoqAnchor { static MoqAnchor? lift(RustBuffer buf) { return FfiConverterOptionalMoqAnchor.read(buf.asUint8List()).value; @@ -15027,53 +15074,6 @@ class FfiConverterOptionalMoqAudioRead { } } -class FfiConverterOptionalMoqBandwidth { - static MoqBandwidth? lift(RustBuffer buf) { - return FfiConverterOptionalMoqBandwidth.read(buf.asUint8List()).value; - } - - static LiftRetVal read(Uint8List buf) { - if (ByteData.view(buf.buffer, buf.offsetInBytes).getInt8(0) == 0) { - return LiftRetVal(null, 1); - } - final result = FfiConverterMoqBandwidth.read( - Uint8List.view(buf.buffer, buf.offsetInBytes + 1), - ); - return LiftRetVal(result.value, result.bytesRead + 1); - } - - static int allocationSize([MoqBandwidth? value]) { - if (value == null) { - return 1; - } - return FfiConverterMoqBandwidth.allocationSize(value) + 1; - } - - static RustBuffer lower(MoqBandwidth? value) { - if (value == null) { - return toRustBuffer(Uint8List.fromList([0])); - } - final buf = Uint8List( - FfiConverterOptionalMoqBandwidth.allocationSize(value), - ); - FfiConverterOptionalMoqBandwidth.write(value, buf); - return toRustBuffer(buf); - } - - static int write(MoqBandwidth? value, Uint8List buf) { - if (value == null) { - buf[0] = 0; - return 1; - } - buf[0] = 1; - return FfiConverterMoqBandwidth.write( - value, - Uint8List.view(buf.buffer, buf.offsetInBytes + 1), - ) + - 1; - } -} - class FfiConverterOptionalMoqBandwidthConsumer { static MoqBandwidthConsumer? lift(RustBuffer buf) { return FfiConverterOptionalMoqBandwidthConsumer.read( @@ -17227,7 +17227,7 @@ external RustBuffer uniffi_moq_ffi_fn_method_moqgrantconsumer_grant( @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_clone_moqbandwidth( +external Pointer uniffi_moq_ffi_fn_clone_moqallocator( Pointer handle, Pointer uniffiStatus, ); @@ -17235,7 +17235,7 @@ external Pointer uniffi_moq_ffi_fn_clone_moqbandwidth( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external void uniffi_moq_ffi_fn_free_moqbandwidth( +external void uniffi_moq_ffi_fn_free_moqallocator( Pointer handle, Pointer uniffiStatus, ); @@ -17248,7 +17248,7 @@ external void uniffi_moq_ffi_fn_free_moqbandwidth( Pointer, ) >(assetId: _uniffiAssetId) -external Pointer uniffi_moq_ffi_fn_method_moqbandwidth_reserve( +external Pointer uniffi_moq_ffi_fn_method_moqallocator_reserve( Pointer ptr, Pointer demand, int max_bps, @@ -17310,7 +17310,7 @@ external void uniffi_moq_ffi_fn_free_moqreservation( @Native, Pointer)>( assetId: _uniffiAssetId, ) -external RustBuffer uniffi_moq_ffi_fn_method_moqreservation_grant( +external RustBuffer uniffi_moq_ffi_fn_method_moqreservation_rate( Pointer ptr, Pointer uniffiStatus, ); @@ -19264,7 +19264,7 @@ external void uniffi_moq_ffi_fn_free_moqsession( @Native Function(Pointer, Pointer)>( assetId: _uniffiAssetId, ) -external Pointer uniffi_moq_ffi_fn_method_moqsession_bandwidth( +external Pointer uniffi_moq_ffi_fn_method_moqsession_allocator( Pointer ptr, Pointer uniffiStatus, ); @@ -20045,7 +20045,7 @@ external int uniffi_moq_ffi_checksum_method_moqgrantconsumer_changed(); external int uniffi_moq_ffi_checksum_method_moqgrantconsumer_grant(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqbandwidth_reserve(); +external int uniffi_moq_ffi_checksum_method_moqallocator_reserve(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqbandwidthconsumer_cancel(); @@ -20057,7 +20057,7 @@ external int uniffi_moq_ffi_checksum_method_moqbandwidthconsumer_rate(); external int uniffi_moq_ffi_checksum_method_moqbandwidthconsumer_rate_changed(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqreservation_grant(); +external int uniffi_moq_ffi_checksum_method_moqreservation_rate(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqreservation_update(); @@ -20487,7 +20487,7 @@ external int uniffi_moq_ffi_checksum_method_moqclient_cancel(); external int uniffi_moq_ffi_checksum_method_moqclient_connect(); @Native(assetId: _uniffiAssetId) -external int uniffi_moq_ffi_checksum_method_moqsession_bandwidth(); +external int uniffi_moq_ffi_checksum_method_moqsession_allocator(); @Native(assetId: _uniffiAssetId) external int uniffi_moq_ffi_checksum_method_moqsession_cancel(); @@ -20738,7 +20738,7 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqaudioproducer_reanchor() != 34412) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqaudioproducer_reservation() != 43848) { + if (uniffi_moq_ffi_checksum_method_moqaudioproducer_reservation() != 50185) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqaudioproducer_write() != 48796) { @@ -20753,7 +20753,7 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqgrantconsumer_grant() != 36088) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqbandwidth_reserve() != 27807) { + if (uniffi_moq_ffi_checksum_method_moqallocator_reserve() != 34785) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqbandwidthconsumer_cancel() != 58304) { @@ -20766,7 +20766,7 @@ void _checkApiChecksums() { 38021) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqreservation_grant() != 10773) { + if (uniffi_moq_ffi_checksum_method_moqreservation_rate() != 65114) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqreservation_update() != 9626) { @@ -21218,7 +21218,7 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqclient_connect() != 5016) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqsession_bandwidth() != 8006) { + if (uniffi_moq_ffi_checksum_method_moqsession_allocator() != 12118) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqsession_cancel() != 39476) { @@ -21306,10 +21306,10 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqvideoproducer_finish() != 40208) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqvideoproducer_reservation() != 64430) { + if (uniffi_moq_ffi_checksum_method_moqvideoproducer_reservation() != 25410) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqvideoproducer_set_bitrate() != 28203) { + if (uniffi_moq_ffi_checksum_method_moqvideoproducer_set_bitrate() != 19081) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqvideoproducer_write() != 17427) { diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index 19594809aab..f40ea29e942 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -51,7 +51,7 @@ publication.announce(); - **Timing is per track, with no default.** A track that declares a `timescale` carries a `timestamp` on every frame; one without is [untimed](/concept/moq-lite#subscriptions) and its frames carry none. Omitting it means untimed, as in Rust. Nothing stamps a frame for you: the publisher passes the timestamp, and the `Timed` type (`{ value, at }`) carries one into the `@moq/json` and `@moq/flate` producers. - **Subscriber staleness is `maxDelay`.** It counts from a group's successor, by media time and by wall clock, whichever reaches it first. Passing the old `maxAge` key throws a `TypeError` naming `maxDelay`. Publisher retention is the separate `Track.Info.maxAge`. - **Hidden paths** stay out of discovery unless the announce request opts in. See [hidden broadcasts](/concept/moq-lite#hidden-broadcasts). -- **Authorization is in band.** On moq-lite 07 (opt in with `versions: ["moq-lite-07-wip", "moq-lite-06"]`, listing every fallback you still want) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `auth.grant` watches what the relay lets this side publish and subscribe to, and `auth.add(token)` presents another token without reconnecting. Publishing outside the grant closes the connection with `SessionCode.Unauthorized`, naming the path. On moq-lite, a subscription or track listing the grant stops covering resets with `StreamCode.Unauthorized` and the session stays up. On moq-transport, `auth.add(token)` keeps the token even without the extension, and a broadcast announced with the `Auth.Auth` it returns (`publication.announce({ auth })`) carries it on that announcement's `PUBLISH_NAMESPACE`; announcing again with another renews the request. A `Connection`'s `auth` handle (a getter on a pooled connection, following its URL) outlives its sessions: a token added there is presented on every reconnect and keeps riding the announcements that name it, with no re-add or re-announce. A one-shot session's `auth` ends with it, unless `Connection.connect` was given a `new Auth.Handle()` as `auth`. +- **Authorization is in band.** On moq-lite 07 (opt in with `versions: ["moq-lite-07-wip", "moq-lite-06"]`, listing every fallback you still want) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `auth.grant` watches what the relay lets this side publish and subscribe to, and `auth.add(token)` presents another token without reconnecting. Publishing outside the grant closes the connection with `SessionCode.Unauthorized`, naming the path. On moq-lite, a subscription or track listing the grant stops covering resets with `StreamCode.Unauthorized` and the session stays up. On moq-transport, `auth.add(token)` keeps the token even without the extension, and a broadcast announced with the `Auth.Credential` it returns (`publication.announce({ auth })`) carries it on that announcement's `PUBLISH_NAMESPACE`; announcing again with another renews the request. A `Connection`'s `auth` handle (a getter on a pooled connection, following its URL) outlives its sessions: a token added there is presented on every reconnect and keeps riding the announcements that name it, with no re-add or re-announce. A one-shot session's `auth` ends with it, unless `Connection.connect` was given a `new Auth.Handle()` as `auth`. - **A graceful close waits.** `await connection.close()` withdraws announcements and drains for up to one second. Application delivery requires explicit `moq-lite-07-wip`; older Lite versions wait only for transport ACKs. IETF media streams are not drained. `abort()` ends immediately. Examples: diff --git a/doc/lib/py/index.md b/doc/lib/py/index.md index 004d81a5f9a..e876ba9a07a 100644 --- a/doc/lib/py/index.md +++ b/doc/lib/py/index.md @@ -118,7 +118,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.** `session.shutdown()` requests a drain immediately; `await session.closed()` waits up to one second and reports its result. `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 `finish()` on its `moq.media.CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. A track still open at the close, or released without a finish, ends with `Unroutable`, which readers take as the publisher leaving. -- **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. +- **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 `BandwidthConsumer` 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), `async for grant in session.grants()` yields the `Grant` the relay sent back and each change, `None` until it answers and while a client session reconnects. `grants().grant()` reads it once; cancelling or leaving an `async with` releases the wait. - **Tokens.** Pass `tokens=[...]` instead of putting the credential in the URL. The first is the connection credential, sent in SETUP and, while an offered version can't carry it there (lite before 07), as the URL's `?jwt=`; each other token widens the grant over AUTH. `session.tokens().set([...])` replaces a client session's tokens before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the session redials only if they changed. `await tokens.answered()` returns once the relay accepts them and raises its refusal with the relay's code. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index 6c68eb723d3..24a98d20ca3 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -104,7 +104,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.** `session.shutdown()` requests a drain immediately; `try await session.closed()` waits up to one second and reports its result. `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 finish()` on its `Media.CatalogProducer` to finish the catalog, which ends the content. The broadcast stays announced and keeps serving the finished tracks, so a subscriber still catching up can drain them, until `broadcast.close()` takes it offline. How long to keep it up is yours to decide. A track still open at the close, or released without a finish, ends with `Unroutable`, which readers take as the publisher leaving. -- **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. 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. +- **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. 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 `Client(versions:)`) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `for try await grant in session.grants()` yields the `Grant` the relay sent back and each change, `nil` until it answers and while a client session reconnects. Cancelling the iterating task cancels the native wait. - **Tokens.** Pass `Client(tokens: [...])` instead of putting the credential in the URL. The first is the connection credential, sent in SETUP and, while an offered version can't carry it there (lite before 07), as the URL's `?jwt=`; each other token widens the grant over AUTH. `try session.tokens()?.set([...])` replaces them before they expire: the next dial presents them, a live AUTH session at once, and after an authorization refusal the session redials only if they changed. `try await tokens.answered()` returns once the relay accepts them and throws its refusal with the relay's code. A `?jwt=` already in the URL stays the connection credential, which is how to reach a relay older than this release. - **Errors.** Diagnostic cases use the `reason:` argument label; match their associated value to inspect it. Protocol errors carry `details`. diff --git a/go/wrapper/MIGRATE.md b/go/wrapper/MIGRATE.md index 0a9d505c875..3791436c1eb 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 +### `Allocator` ([#6751](https://github.com/moq-dev/moq/pull/6751)) + +`Bandwidth` is `Allocator`, `Session.Bandwidth()` is `Session.Allocator()`, and `Reservation.Grant()` is `Reservation.Rate()`. The `Bandwidth` field of `ProducerOptions` keeps its name and takes a `*moq.Allocator`. + ### Decoders read gaps and ends `audio.Consumer.Next` and `video.Consumer.Next` return a `Read` (and `All` ranges over them) instead of a frame pointer. Switch on `ReadFrame` and take its `Frame` where you used the frame; `ReadGap` marks lost media and `ReadEnd` where the publisher stopped its encoder, and what follows either does not continue what came before. A nil `Read` still means the track ended. diff --git a/go/wrapper/README.md b/go/wrapper/README.md index ced19add59c..e4a288fdbb9 100644 --- a/go/wrapper/README.md +++ b/go/wrapper/README.md @@ -71,7 +71,7 @@ pinning a generated self-signed certificate. `Client.Session().Stats()` returns a connection stats snapshot. Fields are nil when the transport backend does not report that metric yet. -An encoder you manage can claim a share of `Client.Session().Bandwidth()` with +An encoder you manage can claim a share of `Client.Session().Allocator()` with `Reserve(demand, maxBps)`, using the track's `Demand()`. Keep one reservation and change its ceiling with `Update(maxBps)`. Call `Update(0)` before abandoning or replacing it to return its share and automatic probe ceiling immediately, even while the track diff --git a/go/wrapper/audio/audio.go b/go/wrapper/audio/audio.go index 231b6c77c40..6387fb7d133 100644 --- a/go/wrapper/audio/audio.go +++ b/go/wrapper/audio/audio.go @@ -131,7 +131,7 @@ type ProducerOptions struct { // Track names the published track; nil derives a name from the codec. Track *string // Bandwidth reserves the track against a session allocator when non-nil. - Bandwidth *moq.Bandwidth + Bandwidth *moq.Allocator } // NewProducer opens an audio track on the catalog's broadcast and registers its rendition. @@ -140,9 +140,9 @@ func NewProducer(catalog *media.CatalogProducer, options ProducerOptions) (*Prod if err != nil { return nil, err } - var bw **ffi.MoqBandwidth + var bw **ffi.MoqAllocator if options.Bandwidth != nil { - raw := bridge.Bandwidth(options.Bandwidth) + raw := bridge.Allocator(options.Bandwidth) bw = &raw } inner, err := ffi.NewMoqAudioProducer(bridge.CatalogProducer(catalog), ffi.MoqAudioProducerOptions{Input: options.Input, Output: out, Track: options.Track, Bandwidth: bw}) diff --git a/go/wrapper/bandwidth_test.go b/go/wrapper/bandwidth_test.go index ef0407bcad6..5783bed2e4c 100644 --- a/go/wrapper/bandwidth_test.go +++ b/go/wrapper/bandwidth_test.go @@ -24,10 +24,10 @@ func TestReservationUpdateReleasesSubscribedTrack(t *testing.T) { t.Fatal(err) } defer client.Close() - // Dial returns while connecting; the grants need the live session's estimate. + // Dial returns while connecting; the rates 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() + bandwidth := client.Session().Allocator() broadcast, err := moq.NewBroadcastProducer() if err != nil { t.Fatal(err) @@ -53,14 +53,14 @@ func TestReservationUpdateReleasesSubscribedTrack(t *testing.T) { } return demand, bandwidth.Reserve(demand, ceiling) } - grant := func(reservation *moq.Reservation, want uint64) { + rate := func(reservation *moq.Reservation, want uint64) { t.Helper() - got := reservation.Grant() + got := reservation.Rate() if got == nil { - t.Fatalf("grant unavailable, want %d", want) + t.Fatalf("rate unavailable, want %d", want) } if *got != want { - t.Fatalf("grant = %d, want %d", *got, want) + t.Fatalf("rate = %d, want %d", *got, want) } } @@ -69,18 +69,18 @@ func TestReservationUpdateReleasesSubscribedTrack(t *testing.T) { replacement := bandwidth.Reserve(demand, 1) // Even a retained predecessor must relinquish the allocation explicitly. // Priority makes this independent of the live estimate's exact value. - grant(sibling, 0) + rate(sibling, 0) retired.Update(0) - grant(retired, 0) - grant(replacement, 1) - grant(sibling, 1) + rate(retired, 0) + rate(replacement, 1) + rate(sibling, 1) // Zero is reversible and repeated release is harmless. retired.Update(math.MaxUint64) - grant(sibling, 0) + rate(sibling, 0) retired.Update(0) retired.Update(0) - grant(sibling, 1) + rate(sibling, 1) if demand.Wanted() == nil { t.Fatal("release ended the track subscription") } diff --git a/go/wrapper/bridge.go b/go/wrapper/bridge.go index 99ca4693d1d..116ac0f1392 100644 --- a/go/wrapper/bridge.go +++ b/go/wrapper/bridge.go @@ -18,7 +18,7 @@ func init() { bridge.TrackConsumer = func(v any) *ffi.MoqTrackConsumer { return v.(*TrackConsumer).inner } bridge.GroupConsumer = func(v any) *ffi.MoqGroupConsumer { return v.(*GroupConsumer).inner } bridge.TrackDemand = func(inner *ffi.MoqTrackDemand) any { return &TrackDemand{inner: inner} } - bridge.Bandwidth = func(v any) *ffi.MoqBandwidth { return v.(*Bandwidth).inner } + bridge.Allocator = func(v any) *ffi.MoqAllocator { return v.(*Allocator).inner } bridge.Reservation = func(inner *ffi.MoqReservation) any { return &Reservation{inner: inner} } bridge.VideoDecodedFrame = func(inner *ffi.MoqVideoDecodedFrame) any { return &VideoDecodedFrame{inner: inner} } } diff --git a/go/wrapper/internal/bridge/handles.go b/go/wrapper/internal/bridge/handles.go index 2c1c5821d45..39dc92d85e8 100644 --- a/go/wrapper/internal/bridge/handles.go +++ b/go/wrapper/internal/bridge/handles.go @@ -22,8 +22,8 @@ var ( GroupConsumer func(any) *ffi.MoqGroupConsumer // TrackDemand wraps a handle as a *moq.TrackDemand. TrackDemand func(*ffi.MoqTrackDemand) any - // Bandwidth returns the handle behind a *moq.Bandwidth. - Bandwidth func(any) *ffi.MoqBandwidth + // Allocator returns the handle behind a *moq.Allocator. + Allocator func(any) *ffi.MoqAllocator // Reservation wraps a native reservation as *moq.Reservation. Reservation func(*ffi.MoqReservation) any // CatalogProducer returns the handle behind a *media.CatalogProducer. diff --git a/go/wrapper/session.go b/go/wrapper/session.go index e97f2f85a9a..119ab1317f3 100644 --- a/go/wrapper/session.go +++ b/go/wrapper/session.go @@ -62,12 +62,12 @@ func (s *Session) Stats() ConnectionStats { return connectionStatsFromFFI(s.inner.Stats()) } -// Bandwidth is the session's bandwidth allocator. Every call returns a handle +// Allocator is the session's bandwidth allocator. Every call returns a handle // to the same registry, so reservations made through one are visible to the // others. A client handle survives reconnects: the grant is nil while // disconnected and resumes on the next connection. -func (s *Session) Bandwidth() *Bandwidth { - return &Bandwidth{inner: s.inner.Bandwidth()} +func (s *Session) Allocator() *Allocator { + return &Allocator{inner: s.inner.Allocator()} } // Grants follows the grant the peer gave this session. Each call returns an @@ -140,9 +140,9 @@ func (t *Tokens) Answered(ctx context.Context) error { return bridge.CallErr(ctx, nil, t.inner.Answered) } -// Bandwidth divides one connection's send estimate among the tracks sharing it. -type Bandwidth struct { - inner *ffi.MoqBandwidth +// Allocator divides one connection's send estimate among the tracks sharing it. +type Allocator struct { + inner *ffi.MoqAllocator } // Reserve claims up to maxBps for the track demand watches; every track @@ -150,23 +150,23 @@ type Bandwidth struct { // reserve the most the track can ever send. Reuse Reservation.Update to change // the ceiling, or call Update(0) before abandoning or replacing the reservation // to hand the room back without waiting for garbage collection. -func (b *Bandwidth) Reserve(demand *TrackDemand, maxBps uint64) *Reservation { - return &Reservation{inner: b.inner.Reserve(demand.inner, maxBps)} +func (a *Allocator) Reserve(demand *TrackDemand, maxBps uint64) *Reservation { + return &Reservation{inner: a.inner.Reserve(demand.inner, maxBps)} } -// Reservation is one track's standing claim on a Bandwidth. +// Reservation is one track's standing claim on an Allocator. // -// Grant is a snapshot: nil means no estimate, so hold the current rate, and 0 is -// a real zero grant. While nothing subscribes it is the share the track would get. +// Rate is a snapshot: nil means no estimate, so hold the current rate, and 0 is +// a real zero rate. While nothing subscribes it is the share the track would get. // Update(0) relinquishes the allocation while the track stays subscribed; the // handle remains usable and a later Update can claim bandwidth again. type Reservation struct { inner *ffi.MoqReservation } -// Grant returns this reservation's slice right now, in bits per second. -func (r *Reservation) Grant() *uint64 { - return r.inner.Grant() +// Rate returns this reservation's slice right now, in bits per second. +func (r *Reservation) Rate() *uint64 { + return r.inner.Rate() } // Update changes the ceiling, keeping the same claim. Zero immediately gives diff --git a/go/wrapper/video/video.go b/go/wrapper/video/video.go index a129a137c27..919bb268f5f 100644 --- a/go/wrapper/video/video.go +++ b/go/wrapper/video/video.go @@ -83,7 +83,7 @@ type ProducerOptions struct { // Track names the published track; nil derives a name from the codec. Track *string // Bandwidth reserves the track against a session allocator when non-nil. - Bandwidth *moq.Bandwidth + Bandwidth *moq.Allocator // Lower is the next rendition down a simulcast ladder: when non-nil, this one // disables while the grant cannot fund it and resumes once it recovers. Needs // Bandwidth and a bitrate above the lower rendition's. @@ -92,9 +92,9 @@ type ProducerOptions struct { // NewProducer opens a video track on the catalog's broadcast and registers its rendition. func NewProducer(catalog *media.CatalogProducer, options ProducerOptions) (*Producer, error) { - var bw **ffi.MoqBandwidth + var bw **ffi.MoqAllocator if options.Bandwidth != nil { - raw := bridge.Bandwidth(options.Bandwidth) + raw := bridge.Allocator(options.Bandwidth) bw = &raw } var lower **ffi.MoqVideoProducer diff --git a/js/e2ee/src/e2ee.test.ts b/js/e2ee/src/e2ee.test.ts index a186320abfa..6af3d41f614 100644 --- a/js/e2ee/src/e2ee.test.ts +++ b/js/e2ee/src/e2ee.test.ts @@ -402,8 +402,7 @@ test("grouped authentication failure ends the track", async () => { group.close(); // A forged second group, written straight to the net track. - const bad = new NetGroup.Producer(1); - p.net.writeGroup(bad); + const bad = p.net.createGroup(1); bad.writeFrame({ timestamp: ms(2), payload: await sealed(p, GROUP, 1, 0, "ok", true) }); bad.finish(); @@ -420,12 +419,10 @@ test("grouped failure wakes pending reads and releases demand", async () => { expect(demand.wanted.peek()).toBeDefined(); // One authentic frame, then silence. The group and the track stay open. - const open = new NetGroup.Producer(0); - p.net.writeGroup(open); + const open = p.net.createGroup(0); open.writeFrame({ timestamp: ms(1), payload: await sealed(p, GROUP, 0, 0, "ok") }); - const bad = new NetGroup.Producer(1); + const bad = p.net.createGroup(1); const badDemand = bad.demand(); - p.net.writeGroup(bad); bad.writeFrame({ timestamp: ms(2), payload: await sealed(p, GROUP, 1, 0, "nope", true) }); const good = await recvGroup(p.consumer); @@ -451,8 +448,7 @@ test("grouped failure wakes pending reads and releases demand", async () => { test("a grouped failure ahead of a datagram open rejects the datagram", async () => { const p = await pair("audio"); - const bad = new NetGroup.Producer(0); - p.net.writeGroup(bad); + const bad = p.net.createGroup(0); bad.writeFrame({ timestamp: ms(1), payload: await sealed(p, GROUP, 0, 0, "nope", true) }); p.net.insertDatagram(0, ms(2), await sealed(p, DATAGRAM, 0, 0, "late")); const forged = await recvGroup(p.consumer); @@ -795,11 +791,9 @@ test("a timestamp out of range at the track's timescale spends nothing", async ( test("a grouped failure skips opens queued behind it", async () => { const p = await pair("video"); - const bad = new NetGroup.Producer(0); - p.net.writeGroup(bad); + const bad = p.net.createGroup(0); bad.writeFrame({ timestamp: ms(1), payload: await sealed(p, GROUP, 0, 0, "nope", true) }); - const good = new NetGroup.Producer(1); - p.net.writeGroup(good); + const good = p.net.createGroup(1); good.writeFrame({ timestamp: ms(2), payload: await sealed(p, GROUP, 1, 0, "ok") }); p.net.insertDatagram(0, ms(3), await sealed(p, DATAGRAM, 0, 0, "late")); const forged = await recvGroup(p.consumer); diff --git a/js/e2ee/src/track.ts b/js/e2ee/src/track.ts index 0a16898b9f8..2d1720d8b30 100644 --- a/js/e2ee/src/track.ts +++ b/js/e2ee/src/track.ts @@ -3,7 +3,7 @@ * * @module */ -import { Group as NetGroup, type Track as NetTrack, type Time } from "@moq/net"; +import type { Group as NetGroup, Track as NetTrack, Time } from "@moq/net"; import type { Event } from "./datagram.ts"; import { checkU53 } from "./derive.ts"; import { Failure } from "./failure.ts"; @@ -58,8 +58,7 @@ export class Producer { this.#writable(); this.#reserve(sequence); this.#next = sequence + 1; - const inner = new NetGroup.Producer(sequence); - this.#inner.writeGroup(inner); + const inner = this.#inner.createGroup(sequence); return Group.Producer.make(inner, this.#writer); } diff --git a/js/hang/bench/slow-group.ts b/js/hang/bench/slow-group.ts index 127e8405449..a1622c64879 100644 --- a/js/hang/bench/slow-group.ts +++ b/js/hang/bench/slow-group.ts @@ -1,7 +1,7 @@ // Measure warning traffic and catch-up time over the groups a slow consumer skips. import { Milli } from "@moq/clock"; -import { Group, Time, Track, Varint } from "@moq/net"; +import { Time, Track, Varint } from "@moq/net"; import { Signal } from "@moq/signals"; import { Consumer } from "../src/container/consumer.ts"; import { Format } from "../src/container/legacy.ts"; @@ -15,9 +15,8 @@ for (const count of [1, 16, 256, 1024]) { maxDelay, }); const write = (sequence: number) => { - const group = new Group.Producer(sequence); + const group = track.createGroup(sequence); group.writeFrame({ payload: Varint.encode(sequence * 1000), timestamp: Time.Timestamp.now() }); - track.writeGroup(group); }; const buffered = async (timestamp: number) => { while (consumer.buffered.peek().at(-1)?.end !== timestamp) await consumer.buffered.changed(); diff --git a/js/hang/src/container/consumer.holes.test.ts b/js/hang/src/container/consumer.holes.test.ts index 958d2e6550e..9b0d50f540e 100644 --- a/js/hang/src/container/consumer.holes.test.ts +++ b/js/hang/src/container/consumer.holes.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "bun:test"; import { Manual, Micro, Milli, Nano } from "@moq/clock"; -import { Group, Time, Track } from "@moq/net"; +import { Time, Track } from "@moq/net"; import { Consumer, type Read } from "./consumer.ts"; import { encodeFrame, Format } from "./legacy.ts"; @@ -23,14 +23,12 @@ test.each([0, 100])("a sequence hole before a paused data marker expires at %sms } })(); try { - const first = new Group.Producer(0); - track.writeGroup(first); + const first = track.createGroup(0); first.writeFrame({ payload: encodeFrame(new Uint8Array([1]), Micro(10_000)), timestamp: Time.Timestamp.now() }); first.finish(); await flush(); expect(results).toHaveLength(1); - const marker = new Group.Producer(2); - track.writeGroup(marker); + const marker = track.createGroup(2); marker.writeFrame({ payload: new Uint8Array(), timestamp: Time.Timestamp.now() }); marker.finish(); await flush(); @@ -70,8 +68,7 @@ test("a filled hole cancels its timer and the next hole gets a fresh budget", as } })(); const write = (sequence: number, timestamp?: number) => { - const group = new Group.Producer(sequence); - track.writeGroup(group); + const group = track.createGroup(sequence); group.writeFrame({ payload: timestamp === undefined ? new Uint8Array() : encodeFrame(new Uint8Array([1]), Micro(timestamp)), timestamp: Time.Timestamp.fromMicros(timestamp ?? 20_000), @@ -122,8 +119,7 @@ test("the holes a stalled source left behind share one budget", async () => { } })(); const write = (sequence: number) => { - const group = new Group.Producer(sequence); - track.writeGroup(group); + const group = track.createGroup(sequence); group.writeFrame({ payload: encodeFrame(new Uint8Array([1]), Micro(sequence * 10_000)), timestamp: Time.Timestamp.fromMicros(sequence * 10_000), @@ -164,8 +160,7 @@ test("a hole is late from the earliest arrival past it", async () => { } })(); const write = (sequence: number) => { - const group = new Group.Producer(sequence); - track.writeGroup(group); + const group = track.createGroup(sequence); group.writeFrame({ payload: encodeFrame(new Uint8Array([1]), Micro(sequence * 10_000)), timestamp: Time.Timestamp.fromMicros(sequence * 10_000), diff --git a/js/hang/src/container/consumer.nonsequential.test.ts b/js/hang/src/container/consumer.nonsequential.test.ts index 5544943625d..600101460d3 100644 --- a/js/hang/src/container/consumer.nonsequential.test.ts +++ b/js/hang/src/container/consumer.nonsequential.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "bun:test"; import type { Micro, Milli } from "@moq/clock"; -import { Group, Time, Track, Varint } from "@moq/net"; +import { Time, Track, Varint } from "@moq/net"; import { Consumer } from "./consumer.ts"; import { Format as LegacyFormat } from "./legacy.ts"; @@ -41,13 +41,12 @@ test("Consumer waits on a non-sequential hang group because it has no per-frame }); // Group A at a large sequence, completed so the cursor advances past it. - const a = new Group.Producer(1_000_000); + const a = track.createGroup(1_000_000); a.writeFrame({ payload: encodeLegacyFrame(0 as Micro, new Uint8Array([0x01])), timestamp: Time.Timestamp.now(), }); a.finish(); - track.writeGroup(a); // Drain A's frame. const firstFrame = await nextFrame(consumer); @@ -59,8 +58,7 @@ test("Consumer waits on a non-sequential hang group because it has no per-frame // Open group B at a large jump (+90_000, NOT +1) with a frame far past A's last PTS, and leave it // open. Legacy has no duration, so A's end is unknown -- B could be continuous, or group 1_000_001 // could still be coming. We cannot tell, so B must NOT surface yet. - const b = new Group.Producer(1_090_000); - track.writeGroup(b); + const b = track.createGroup(1_090_000); b.writeFrame({ payload: encodeLegacyFrame(1_000_000 as Micro, new Uint8Array([0x02])), timestamp: Time.Timestamp.now(), diff --git a/js/hang/src/container/consumer.outoforder.test.ts b/js/hang/src/container/consumer.outoforder.test.ts index 736e53fcbb6..e654b2e3b33 100644 --- a/js/hang/src/container/consumer.outoforder.test.ts +++ b/js/hang/src/container/consumer.outoforder.test.ts @@ -1,6 +1,6 @@ import { expect, spyOn, test } from "bun:test"; import { Micro, Milli } from "@moq/clock"; -import { Group, Time, Track, Varint } from "@moq/net"; +import { type Group, Time, Track, Varint } from "@moq/net"; import { Consumer } from "./consumer.ts"; import { Format as LegacyFormat } from "./legacy.ts"; @@ -32,8 +32,7 @@ function publishFrame(group: Group.Producer, millis: number, tag: number) { /** Publish one closed group carrying a single frame at `millis`. */ function publish(track: Track.Producer, sequence: number, millis: number) { - const group = new Group.Producer(sequence); - track.writeGroup(group); + const group = track.createGroup(sequence); publishFrame(group, millis, sequence); group.finish(); } @@ -94,14 +93,12 @@ test("a below-cursor group still downloading is not truncated", async () => { }); // The live edge group arrives first and starts delivery (still open). - const live = new Group.Producer(3); - track.writeGroup(live); + const live = track.createGroup(3); publishFrame(live, 3000, 30); expect((await nextFrame(consumer))?.frame.payload[0]).toBe(30); // A backlog group lands below the cursor, one frame at a time (mid-download). - const backlog = new Group.Producer(1); - track.writeGroup(backlog); + const backlog = track.createGroup(1); publishFrame(backlog, 1000, 10); const first = await nextFrame(consumer); expect(first?.group).toBe(1); @@ -135,8 +132,7 @@ test("delayed older groups survive a floor established by two newer groups", asy publish(track, 3, 30); expect((await nextFrame(consumer))?.group).toBe(3); - const latest = new Group.Producer(4); - track.writeGroup(latest); + const latest = track.createGroup(4); publishFrame(latest, 40, 4); expect((await nextFrame(consumer))?.group).toBe(4); diff --git a/js/hang/src/container/consumer.skips.test.ts b/js/hang/src/container/consumer.skips.test.ts index 02bb22e1e95..3592cfbd6dd 100644 --- a/js/hang/src/container/consumer.skips.test.ts +++ b/js/hang/src/container/consumer.skips.test.ts @@ -1,6 +1,6 @@ import { expect, spyOn, test } from "bun:test"; import { Milli } from "@moq/clock"; -import { Group, Time, Track, Varint } from "@moq/net"; +import { Time, Track, Varint } from "@moq/net"; import { Signal } from "@moq/signals"; import { Consumer } from "./consumer.ts"; import { Format } from "./legacy.ts"; @@ -15,9 +15,8 @@ for (const count of [1, 16, 256]) { maxDelay, }); const write = (sequence: number, timestamp: number) => { - const group = new Group.Producer(sequence); + const group = track.createGroup(sequence); group.writeFrame({ payload: Varint.encode(timestamp), timestamp: Time.Timestamp.now() }); - track.writeGroup(group); return group; }; const buffered = async (timestamp: number) => { diff --git a/js/hang/src/container/consumer.startup.test.ts b/js/hang/src/container/consumer.startup.test.ts index c29b9f41daf..b8ac21339ea 100644 --- a/js/hang/src/container/consumer.startup.test.ts +++ b/js/hang/src/container/consumer.startup.test.ts @@ -1,6 +1,6 @@ import { expect, jest, onTestFinished, spyOn, test } from "bun:test"; import { Micro, Milli } from "@moq/clock"; -import { Group, Error as NetError, StreamCode, Time, Track } from "@moq/net"; +import { type Group, Error as NetError, StreamCode, Time, Track } from "@moq/net"; import { Consumer, type Read } from "./consumer.ts"; import { encodeFrame, Format } from "./legacy.ts"; @@ -62,12 +62,10 @@ for (const emptySuccessor of [false, true]) { `Consumer starts across a hole after an empty reset (empty successor: ${emptySuccessor}, maxDelay: %s)`, async (maxDelay) => { const { track, results, warn } = setup(maxDelay); - const stale = new Group.Producer(16); - track.writeGroup(stale); + const stale = track.createGroup(16); await flush(); if (emptySuccessor) { - const empty = new Group.Producer(17); - track.writeGroup(empty); + const empty = track.createGroup(17); empty.finish(); await flush(); } @@ -76,8 +74,7 @@ for (const emptySuccessor of [false, true]) { expect(results).toEqual([]); const sequence = emptySuccessor ? 19 : 18; - const live = new Group.Producer(sequence); - track.writeGroup(live); + const live = track.createGroup(sequence); for (let i = 0; i < 5; i++) write(live, 1_000_000 + i * 33_333); await flush(); @@ -95,15 +92,13 @@ for (const emptySuccessor of [false, true]) { test("Consumer preserves a declared marker before its first media across a hole", async () => { const { track, results, warn } = setup(); - const marker = new Group.Producer(16); - track.writeGroup(marker); + const marker = track.createGroup(16); write(marker, 0, true); marker.finish(); await flush(); expect(items(results)).toEqual(["end 16@0"]); - const live = new Group.Producer(18); - track.writeGroup(live); + const live = track.createGroup(18); write(live, 50_000); await flush(); // Group 17 never arrived, so the media after the marker is past a gap. It spans the declared @@ -115,32 +110,28 @@ test("Consumer preserves a declared marker before its first media across a hole" test.each([false, true])("Consumer still waits for a gap after media (playhead reset: %s)", async (reset) => { const { track, consumer, results, warn } = setup(1000); - const first = new Group.Producer(16); - track.writeGroup(first); + const first = track.createGroup(16); write(first, 0); first.finish(); await flush(); expect(items(results)).toEqual(["16@0"]); if (reset) { - const marker = new Group.Producer(17); - track.writeGroup(marker); + const marker = track.createGroup(17); write(marker, 0, true); marker.finish(); await flush(); expect(items(results)).toEqual(["16@0", "end 17@0"]); } const sequence = reset ? 20 : 19; - const later = new Group.Producer(sequence); - track.writeGroup(later); + const later = track.createGroup(sequence); write(later, 50_000); await flush(); expect(consumer.buffered.peek().length).toBeGreaterThan(0); expect(frames(results)).toHaveLength(1); // Supply the missing, timestamp-contiguous bridge and prove the queued frame survives. - const bridge = new Group.Producer(sequence - 1); - track.writeGroup(bridge); + const bridge = track.createGroup(sequence - 1); write(bridge, 0); bridge.finish(); await flush(); diff --git a/js/hang/src/container/consumer.test.ts b/js/hang/src/container/consumer.test.ts index 38e583dbdb0..c3f21d7b4d4 100644 --- a/js/hang/src/container/consumer.test.ts +++ b/js/hang/src/container/consumer.test.ts @@ -2,7 +2,7 @@ import { expect, spyOn, test } from "bun:test"; import { readFileSync } from "node:fs"; import { Manual, type Micro, Milli, Nano } from "@moq/clock"; import { Format as LocFormat } from "@moq/loc"; -import { Group, Error as NetError, SessionCode, StreamCode, Time, Track, Varint } from "@moq/net"; +import { type Group, Error as NetError, SessionCode, StreamCode, Time, Track, Varint } from "@moq/net"; import { decodeInitSegment, type InitSegment } from "../cmaf/decode.ts"; import { Format as CmafFormat } from "../cmaf/format.ts"; import { Consumer, type Read } from "./consumer.ts"; @@ -506,22 +506,20 @@ function writeGroupWithLegacyFrames( timestamps: Micro[], stamp: (ts: Micro) => Time.Timestamp = (ts) => Time.Timestamp.fromMicros(ts), ) { - const group = new Group.Producer(sequence); + const group = track.createGroup(sequence); for (const ts of timestamps) { group.writeFrame({ payload: encodeLegacy(ts), timestamp: stamp(ts) }); } group.finish(); - track.writeGroup(group); } function writeMarkerGroup(track: Track.Producer, sequence: number, timestamp: Micro) { - const group = new Group.Producer(sequence); + const group = track.createGroup(sequence); group.writeFrame({ payload: encodeLegacyFrame(timestamp, new Uint8Array()), timestamp: Time.Timestamp.fromMicros(timestamp), }); group.finish(); - track.writeGroup(group); } async function drainFrames( @@ -600,11 +598,10 @@ test("Consumer index spans MoQ frames for keyframe detection", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: multiFormat, maxDelay: 500 as Milli }); - const group = new Group.Producer(0); + const group = track.createGroup(0); group.writeFrame({ payload: new Uint8Array([0x01]), timestamp: Time.Timestamp.now() }); // first MoQ frame → 3 samples group.writeFrame({ payload: new Uint8Array([0x02]), timestamp: Time.Timestamp.now() }); // second MoQ frame → 3 samples group.finish(); - track.writeGroup(group); track.finish(); track.close(); @@ -634,17 +631,15 @@ for (const [where, payloads] of [ const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: failingFormat, maxDelay: 500 as Milli }); - const g0 = new Group.Producer(0); + const g0 = track.createGroup(0); for (const byte of payloads) g0.writeFrame({ payload: new Uint8Array([byte]), timestamp: Time.Timestamp.now() }); g0.finish(); - track.writeGroup(g0); // A later group that decodes cleanly is never reached. - const g1 = new Group.Producer(1); + const g1 = track.createGroup(1); g1.writeFrame({ payload: new Uint8Array([0x04]), timestamp: Time.Timestamp.now() }); g1.finish(); - track.writeGroup(g1); track.finish(); track.close(); @@ -669,11 +664,10 @@ test("Consumer delivers everything ahead of a decode error", async () => { writeGroupWithLegacyFrames(track, 0, [0 as Micro]); writeGroupWithLegacyFrames(track, 2, [100_000 as Micro]); - const malformed = new Group.Producer(3); + const malformed = track.createGroup(3); // A truncated timestamp varint. malformed.writeFrame({ payload: new Uint8Array([0x80]), timestamp: Time.Timestamp.fromMicros(200_000) }); malformed.finish(); - track.writeGroup(malformed); track.finish(); track.close(); @@ -698,10 +692,9 @@ test("Consumer keeps the first of several decode errors", async () => { const consumer = new Consumer(replay(track), { format: failingFormat, maxDelay: 500 as Milli }); for (const sequence of [0, 1]) { - const group = new Group.Producer(sequence); + const group = track.createGroup(sequence); group.writeFrame({ payload: new Uint8Array([sequence]), timestamp: Time.Timestamp.now() }); group.finish(); - track.writeGroup(group); } track.finish(); track.close(); @@ -729,13 +722,11 @@ test("Consumer releases its open groups when an error ends it", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: failingFormat, maxDelay: 500 as Milli }); - const malformed = new Group.Producer(0); + const malformed = track.createGroup(0); malformed.writeFrame({ payload: new Uint8Array([0xff]), timestamp: Time.Timestamp.now() }); malformed.finish(); - track.writeGroup(malformed); - const later = new Group.Producer(1); + const later = track.createGroup(1); later.writeFrame({ payload: new Uint8Array([0x01]), timestamp: Time.Timestamp.now() }); - track.writeGroup(later); await open; expect(later.demand().used.peek()).toBe(true); @@ -763,14 +754,13 @@ test("Consumer keeps frames decoded before a group reset (truncated GoP)", async const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format, maxDelay: 500 as Milli }); - const g0 = new Group.Producer(0); + const g0 = track.createGroup(0); for (const timestamp of [1, 2]) { g0.writeFrame({ payload: encodeLegacyFrame(timestamp as Micro, new Uint8Array([1])), timestamp: Time.Timestamp.fromMicros(timestamp), }); } - track.writeGroup(g0); await decoded; g0.abort(new NetError.Stream(StreamCode.Cancel)); @@ -965,7 +955,7 @@ test("Consumer keeps a trailing duration marker internal", async () => { maxDelay: 500 as Milli, }); - const group = new Group.Producer(0); + const group = track.createGroup(0); group.writeFrame({ payload: encodeLegacyFrame(0 as Micro, new Uint8Array([0xde, 0xad])), timestamp: Time.Timestamp.now(), @@ -975,7 +965,6 @@ test("Consumer keeps a trailing duration marker internal", async () => { timestamp: Time.Timestamp.now(), }); group.finish(); - track.writeGroup(group); track.finish(); track.close(); await settle(); @@ -996,7 +985,7 @@ test("Consumer reads a leading marker as an end and keeps the first media keyfra maxDelay: 500 as Milli, }); - const group = new Group.Producer(0); + const group = track.createGroup(0); group.writeFrame({ payload: encodeLegacyFrame(20_000 as Micro, new Uint8Array()), timestamp: Time.Timestamp.now(), @@ -1006,7 +995,6 @@ test("Consumer reads a leading marker as an end and keeps the first media keyfra timestamp: Time.Timestamp.now(), }); group.finish(); - track.writeGroup(group); track.finish(); track.close(); @@ -1117,11 +1105,10 @@ test("Consumer throws the first error in delivery order", async () => { const consumer = new Consumer(replay(track), { format: new LegacyFormat("data"), maxDelay: 30_000 as Milli }); writeGroupWithLegacyFrames(track, 0, [10_000_000 as Micro], wallClock); - const malformed = new Group.Producer(1); + const malformed = track.createGroup(1); // A truncated timestamp varint. malformed.writeFrame({ payload: new Uint8Array([0x80]), timestamp: wallClock() }); malformed.finish(); - track.writeGroup(malformed); writeGroupWithLegacyFrames(track, 2, [0 as Micro, 100_000 as Micro], wallClock); track.finish(); track.close(); @@ -1147,13 +1134,12 @@ test("Consumer checks a whole decoded batch before a skip drops its group", asyn }, }; const write = (sequence: number, timestamps: number[]) => { - const group = new Group.Producer(sequence); + const group = track.createGroup(sequence); // Transport stamps follow the sequence, so a lower group may land after a higher one. group.writeFrame({ payload: new TextEncoder().encode(JSON.stringify(timestamps)), timestamp: Time.Timestamp.fromMicros(sequence * 1000), }); - track.writeGroup(group); return group; }; @@ -1261,14 +1247,13 @@ test("Consumer reads no gap when retiring a group holding only its endpoint", as const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new LegacyFormat("video"), maxDelay: 150 as Milli }); - const group = new Group.Producer(0); + const group = track.createGroup(0); group.writeFrame({ payload: encodeLegacy(0 as Micro), timestamp: Time.Timestamp.fromMicros(0) }); group.writeFrame({ payload: encodeLegacyFrame(33_000 as Micro, new Uint8Array()), timestamp: Time.Timestamp.fromMicros(33_000), }); group.finish(); - track.writeGroup(group); await settle(); expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); @@ -1287,9 +1272,8 @@ test("Consumer reads a gap when retiring a truncated group", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxDelay: 150 as Milli }); - const group = new Group.Producer(0); + const group = track.createGroup(0); group.writeFrame({ payload: encodeLegacy(0 as Micro), timestamp: Time.Timestamp.fromMicros(0) }); - track.writeGroup(group); await settle(); expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); @@ -1310,9 +1294,8 @@ test("Consumer reads a gap when retiring an open group", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxDelay: 150 as Milli }); - const group = new Group.Producer(0); + const group = track.createGroup(0); group.writeFrame({ payload: encodeLegacy(0 as Micro), timestamp: Time.Timestamp.fromMicros(0) }); - track.writeGroup(group); await settle(); expect(frameOf(await consumer.next()).timestamp).toBe(0 as Micro); @@ -1388,11 +1371,10 @@ test("Consumer handles empty decode result without deadlock", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: emptyThenValid, maxDelay: 500 as Milli }); - const group = new Group.Producer(0); + const group = track.createGroup(0); group.writeFrame({ payload: new Uint8Array([0x01]), timestamp: Time.Timestamp.now() }); // empty decode group.writeFrame({ payload: new Uint8Array([0x02]), timestamp: Time.Timestamp.now() }); // valid decode group.finish(); - track.writeGroup(group); track.finish(); track.close(); @@ -1414,10 +1396,9 @@ test("Consumer preserves empty media from formats without endpoint markers", asy }; const track = new Track.Producer("test"); const consumer = new Consumer(track.subscribe(), { format, maxDelay: 500 as Milli }); - const group = new Group.Producer(0); + const group = track.createGroup(0); group.writeFrame({ payload: new Uint8Array([1]), timestamp: Time.Timestamp.now() }); group.finish(); - track.writeGroup(group); track.finish(); track.close(); @@ -1434,7 +1415,7 @@ test("Consumer with CmafFormat delivers correct timestamps", async () => { maxDelay: 500 as Milli, }); - const group = new Group.Producer(0); + const group = track.createGroup(0); group.writeFrame({ payload: fragment("key"), timestamp: at(0), @@ -1444,7 +1425,6 @@ test("Consumer with CmafFormat delivers correct timestamps", async () => { timestamp: at(3000), }); group.finish(); - track.writeGroup(group); track.finish(); track.close(); @@ -1464,11 +1444,10 @@ test("Consumer with CmafFormat times an untimed track from tfdt", async () => { maxDelay: 500 as Milli, }); - const group = new Group.Producer(0); + const group = track.createGroup(0); group.writeFrame({ payload: fragment("untimedKey") }); group.writeFrame({ payload: fragment("untimedDelta") }); group.finish(); - track.writeGroup(group); track.finish(); track.close(); @@ -1508,16 +1487,14 @@ test("Consumer duration-skips a stalled group once it is covered", async () => { const consumer = new Consumer(replay(track), { format: durationFormat, maxDelay: 10_000 as Milli }); // Group.Producer 0: one frame at ts=0 lasting 33ms, never closed (stalled). - const g0 = new Group.Producer(0); + const g0 = track.createGroup(0); g0.writeFrame({ payload: new Uint8Array([0]), timestamp: Time.Timestamp.now() }); // Group.Producer 1: closed, starts exactly where group 0's frame ends. - const g1 = new Group.Producer(1); + const g1 = track.createGroup(1); g1.writeFrame({ payload: new Uint8Array([33]), timestamp: Time.Timestamp.now() }); g1.finish(); - track.writeGroup(g0); - track.writeGroup(g1); track.finish(); track.close(); @@ -1547,16 +1524,13 @@ test("Consumer does not duration-skip when the gap is not covered", async () => // Group.Producer 0 stays open and later receives a second frame; nothing covers the gap, // so that late frame must survive rather than being skipped. - const g0 = new Group.Producer(0); + const g0 = track.createGroup(0); g0.writeFrame({ payload: new Uint8Array([0]), timestamp: Time.Timestamp.now() }); - const g1 = new Group.Producer(1); + const g1 = track.createGroup(1); g1.writeFrame({ payload: new Uint8Array([33]), timestamp: Time.Timestamp.now() }); g1.finish(); - track.writeGroup(g0); - track.writeGroup(g1); - // Let the consumer settle on group 0, then extend it before closing. await new Promise((resolve) => setTimeout(resolve, 20)); g0.writeFrame({ payload: new Uint8Array([20]), timestamp: Time.Timestamp.now() }); @@ -1583,13 +1557,12 @@ test("Consumer delivers a PTS-contiguous next group whose sequence jumped (Legac }); // Group A (seq 1_000_000): one 3000-tick sample, so its content ends at 33_333µs (3000/90000 * 1e6). - const a = new Group.Producer(1_000_000); + const a = track.createGroup(1_000_000); a.writeFrame({ payload: encodeLegacyFrame(Math.round((0 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x01])), timestamp: at(0), }); a.finish(); - track.writeGroup(a); expect(frameOf(await nextFrame(consumer)).payload).toEqual(new Uint8Array([0x01])); @@ -1599,8 +1572,7 @@ test("Consumer delivers a PTS-contiguous next group whose sequence jumped (Legac // A.end (33_333µs) -- the sub-millisecond skew a genuinely contiguous CMAF boundary shows because // per-sample durations and base-decode-times round to µs independently. It's within the contiguity // tolerance, so the timeline is unbroken and B must deliver immediately even while still open. - const b = new Group.Producer(1_090_000); - track.writeGroup(b); + const b = track.createGroup(1_090_000); b.writeFrame({ payload: encodeLegacyFrame(Math.round((3045 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x02])), timestamp: at(3045), @@ -1628,13 +1600,12 @@ test("Consumer waits on a PTS gap instead of skipping to a later buffered group }); // Group A (seq 1_000_000): content ends at 33_333µs. - const a = new Group.Producer(1_000_000); + const a = track.createGroup(1_000_000); a.writeFrame({ payload: encodeLegacyFrame(Math.round((0 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x01])), timestamp: at(0), }); a.finish(); - track.writeGroup(a); expect(frameOf(await nextFrame(consumer)).payload).toEqual(new Uint8Array([0x01])); @@ -1642,8 +1613,7 @@ test("Consumer waits on a PTS gap instead of skipping to a later buffered group // Group C (seq 1_090_000) starts at 90_000 ticks (1_000_000µs) -- far past A.end (33_333µs), a real // gap. An intermediate group may still be in transit, so C must NOT be delivered yet. - const c = new Group.Producer(1_090_000); - track.writeGroup(c); + const c = track.createGroup(1_090_000); c.writeFrame({ payload: encodeLegacyFrame(Math.round((90_000 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x03])), timestamp: at(90_000), @@ -1657,8 +1627,7 @@ test("Consumer waits on a PTS gap instead of skipping to a later buffered group // The missing group B arrives, contiguous with A (first PTS 3000 ticks = 33_333µs = A.end); it // continues the timeline, so delivery resumes with B's frame. - const b = new Group.Producer(1_045_000); - track.writeGroup(b); + const b = track.createGroup(1_045_000); b.writeFrame({ payload: encodeLegacyFrame(Math.round((3000 / TIMESCALE) * 1_000_000) as Micro, new Uint8Array([0x02])), timestamp: at(3000), @@ -1682,8 +1651,7 @@ test("Consumer delivers a contiguous group after one that completed out of order }); // A (seq 1_000_000) stays open so it remains the active group. - const a = new Group.Producer(1_000_000); - track.writeGroup(a); + const a = track.createGroup(1_000_000); a.writeFrame(timedFrame(0x01, 0, 0)); expect(frameOf(await nextFrame(consumer)).payload).toEqual(new Uint8Array([0x01])); @@ -1694,8 +1662,7 @@ test("Consumer delivers a contiguous group after one that completed out of order // B (seq 1_045_000) starts at A's end and is CLOSED while A is still active, so B's own finally // block sees sequence !== #active and never records anything. B ends at 9000 ticks (100_000µs). - const b = new Group.Producer(1_045_000); - track.writeGroup(b); + const b = track.createGroup(1_045_000); b.writeFrame(timedFrame(0x03, 6000, 2)); b.finish(); await settle(); @@ -1706,8 +1673,7 @@ test("Consumer delivers a contiguous group after one that completed out of order // C (seq 1_090_000) starts at B's end, so it continues the timeline and must deliver. const pending = consumer.next(); - const c = new Group.Producer(1_090_000); - track.writeGroup(c); + const c = track.createGroup(1_090_000); c.writeFrame(timedFrame(0x04, 9000, 3)); const result = await Promise.race([pending, settle(300).then(() => "timeout" as const)]); @@ -1728,8 +1694,7 @@ test("Consumer plays the head once a waited-out gap exceeds the budget (Legacy)" }); // A (seq 1000): one frame, ends at 3000 ticks (33_333µs). - const a = new Group.Producer(1000); - track.writeGroup(a); + const a = track.createGroup(1000); a.writeFrame(timedFrame(0x01, 0, 0)); expect(frameOf(await nextFrame(consumer)).payload).toEqual(new Uint8Array([0x01])); a.finish(); @@ -1739,8 +1704,7 @@ test("Consumer plays the head once a waited-out gap exceeds the budget (Legacy)" // B (seq 2000) starts at 90_000 ticks (1_000_000µs), a second past A's end: the missing group // could only ever arrive far beyond the 100ms budget, so B plays from its first frame. - const b = new Group.Producer(2000); - track.writeGroup(b); + const b = track.createGroup(2000); b.writeFrame(timedFrame(0x02, 90_000, 1)); // The missing group's span was never delivered, so a gap from A's end to B comes first. @@ -1760,15 +1724,13 @@ test("Consumer waits on a gap within the budget, then plays the head once it exc }); // A (seq 1000): one frame, ends at 3000 ticks (33_333µs). - const a = new Group.Producer(1000); - track.writeGroup(a); + const a = track.createGroup(1000); a.writeFrame(timedFrame(0x01, 0, 0)); expect(frameOf(await nextFrame(consumer)).payload).toEqual(new Uint8Array([0x01])); a.finish(); // B (seq 2000) starts at 6000 ticks (66_667µs): a gap, but only 33ms past A's end. - const b = new Group.Producer(2000); - track.writeGroup(b); + const b = track.createGroup(2000); b.writeFrame(timedFrame(0x02, 6000, 1)); const pending = consumer.next(); @@ -1832,8 +1794,7 @@ test("Consumer empty groups mean nothing", async () => { const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxDelay: 2_000 as Milli }); writeGroupWithLegacyFrames(track, 0, [0 as Micro]); - const empty = new Group.Producer(1); - track.writeGroup(empty); + const empty = track.createGroup(1); empty.finish(); writeGroupWithLegacyFrames(track, 2, [1_000 as Micro]); await settle(); @@ -1886,8 +1847,7 @@ test("Consumer reads a shed marker group as a gap", async () => { const track = new Track.Producer("test"); const consumer = new Consumer(replay(track), { format: new LegacyFormat("audio"), maxDelay: 0 as Milli }); - const group0 = new Group.Producer(0); - track.writeGroup(group0); + const group0 = track.createGroup(0); group0.writeFrame({ payload: encodeLegacy(0 as Micro), timestamp: Time.Timestamp.fromMicros(0), @@ -1915,16 +1875,14 @@ test("Consumer yields no gap across a PTS-contiguous group id jump (Legacy)", as maxDelay: 10_000 as Milli, }); - const a = new Group.Producer(1_000_000); - track.writeGroup(a); + const a = track.createGroup(1_000_000); a.writeFrame(timedFrame(0x01, 0, 0)); a.finish(); expect(frameOf(await nextFrame(consumer)).payload).toEqual(new Uint8Array([0x01])); // Sequence jumps +90_000 but the first PTS meets A's end, so nothing is missing. - const b = new Group.Producer(1_090_000); - track.writeGroup(b); + const b = track.createGroup(1_090_000); b.writeFrame(timedFrame(0x02, 3000, 1)); expect(frameOf(await consumer.next()).payload).toEqual(new Uint8Array([0x02])); diff --git a/js/net/MIGRATE.md b/js/net/MIGRATE.md index d3ea176ca95..155be7ef6c2 100644 --- a/js/net/MIGRATE.md +++ b/js/net/MIGRATE.md @@ -4,6 +4,13 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Names say one thing ([#6751](https://github.com/moq-dev/moq/pull/6751)) + +`Auth.Auth` is `Auth.Credential`, and `Reservation.grant` is `Reservation.rate`. +A connection's `bandwidth` allocator is `allocator`, mirroring Rust's `Session::allocator()`. +`Track.Producer.writeGroup(group)` is `createGroup(sequence)`, which creates the group and returns it like `appendGroup()`: replace `const group = new Group.Producer(n); track.writeGroup(group);` with `const group = track.createGroup(n);`. +A group can no longer be written before it joins a track, or join more than one track. + ### One lifecycle vocabulary ([#6750](https://github.com/moq-dev/moq/pull/6750)) `Group.Producer.close(abort?)` and `Track.Producer.close(abort?)` split by meaning: call `finish()` for a clean end and `abort(err)` for an error. On a group, `finish()` is terminal and an `abort` after it is a no-op. On a track, `finish()` only declares the end, so groups below it stay writable; then call `close()` to release the producer, which aborts with a `Cancel` stream error if no end was declared. Replace `track.close()` with `track.finish(); track.close();`. diff --git a/js/net/api/index.api.md b/js/net/api/index.api.md index 264ef3217c9..8d6826c0e8a 100644 --- a/js/net/api/index.api.md +++ b/js/net/api/index.api.md @@ -57,17 +57,11 @@ declare namespace Auth { Handle, Unsupported, Grant, - Auth_2 as Auth + Credential_2 as Credential } } export { Auth } -interface Auth_2 { - close(): void; - readonly closed: PromiseLike; - readonly grant: Getter; -} - declare namespace Bandwidth { export { Allocator, @@ -109,9 +103,9 @@ function connect(input: ConnectProps): Promise; export class Connection { constructor(props?: ConnectionProps); static readonly accept: typeof accept; + readonly allocator: Getter; announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; readonly auth: Getter; - readonly bandwidth: Getter; static readonly certificateHash: typeof certificateHash; static readonly checkVersions: typeof checkVersions; close(abort?: Error): void; @@ -245,6 +239,12 @@ const Cost: { zero: bigint; }; +interface Credential_2 { + close(): void; + readonly closed: PromiseLike; + readonly grant: Getter; +} + interface Datagram { payload: Uint8Array; sequence: number; @@ -396,7 +396,7 @@ class GroupTooLarge extends Stream { class Handle { constructor(); abort(err?: Error): void; - add(token: string | Uint8Array): Promise; + add(token: string | Uint8Array): Promise; get grant(): Getter; } @@ -564,6 +564,7 @@ class Producer { appendGroup(): Producer_2; close(): void; get closed(): GetPromise; + createGroup(sequence: number): Producer_2; demand(): Demand; finish(): void; finishAt(end: Position): void; @@ -575,7 +576,6 @@ class Producer { subscribe(options?: Subscription): Subscriber; get subscription(): Getter; writeFrame(frame: Frame): void; - writeGroup(group: Producer_2): void; } class Producer_2 { @@ -688,15 +688,15 @@ interface RequestOptions { class Reservation implements Disposable { [Symbol.dispose](): void; close(): void; - get grant(): Getter; peek(): number | undefined; + get rate(): Getter; update(max: number): void; } function resolve(base: Valid, rel: Relative): Valid; interface Route { - auth?: Auth_2; + auth?: Credential_2; cost: Cost; epoch?: Epoch.Valid; hops: Hop[]; @@ -708,7 +708,7 @@ const Route: { epoch?: Epoch.Valid; hops?: readonly Hop[]; cost?: Cost; - auth?: Auth_2; + auth?: Credential_2; }): Route; }; diff --git a/js/net/api/zod.api.md b/js/net/api/zod.api.md index 2c10c295cf3..8119cbfb81a 100644 --- a/js/net/api/zod.api.md +++ b/js/net/api/zod.api.md @@ -140,6 +140,7 @@ class Producer { appendGroup(): Producer_2; close(): void; get closed(): GetPromise; + createGroup(sequence: number): Producer_2; demand(): Demand; finish(): void; finishAt(end: Position): void; @@ -151,7 +152,6 @@ class Producer { subscribe(options?: Subscription): Subscriber; get subscription(): Getter; writeFrame(frame: Frame): void; - writeGroup(group: Producer_2): void; } class Producer_2 { diff --git a/js/net/bench/resume.ts b/js/net/bench/resume.ts index 8e68cd64e48..e76a48044e7 100644 --- a/js/net/bench/resume.ts +++ b/js/net/bench/resume.ts @@ -48,8 +48,7 @@ async function measure(readers: number, swaps: number | undefined, fork = false) const track = broadcast.createTrack("seq"); // Every route's copy holds the same groups under the same sequences. const write = () => { - const group = new GroupProducer(sequence); - track.writeGroup(group); + const group = track.createGroup(sequence); group.writeFrame({ payload }); group.finish(); }; diff --git a/js/net/bench/subscribe-drop.ts b/js/net/bench/subscribe-drop.ts index 64d9a38c5f3..beec4fc7566 100644 --- a/js/net/bench/subscribe-drop.ts +++ b/js/net/bench/subscribe-drop.ts @@ -1,6 +1,5 @@ /** Sweep failed group sends over independent publishers and subscribers. */ import { Milli } from "@moq/clock"; -import { Producer as GroupProducer } from "../src/group.ts"; import { randomHop } from "../src/hop.ts"; import { Publisher } from "../src/lite/publisher.ts"; import { decodeSubscribeResponseMaybe, Subscribe } from "../src/lite/subscribe.ts"; @@ -29,10 +28,9 @@ try { broadcastPublication.announce(); const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); for (let sequence = 0; sequence < groups; sequence++) { - const group = new GroupProducer(sequence); + const group = track.createGroup(sequence); group.writeFrame(textFrame("frame")); group.finish(); - track.writeGroup(group); } track.finish(); track.close(); diff --git a/js/net/bench/track.ts b/js/net/bench/track.ts index 63736cd8542..07c4dc2215e 100644 --- a/js/net/bench/track.ts +++ b/js/net/bench/track.ts @@ -1,7 +1,7 @@ /** Sweep retained groups and subscribers for one group published through a track and received. */ import { Milli } from "@moq/clock"; -import { type Consumer as GroupConsumer, Producer as GroupProducer } from "../src/group.ts"; +import type { Consumer as GroupConsumer, Producer as GroupProducer } from "../src/group.ts"; import { Timescale, Timestamp } from "../src/time.ts"; import { Producer, type Subscriber } from "../src/track.ts"; import { untilGivenUp } from "../src/util/given_up.ts"; @@ -62,8 +62,7 @@ async function measure( // Inserted by sequence, the way the wire hands a subscribed track its groups. const publish = (close: boolean) => { clock += held > 0 ? 1 : CACHE_WINDOW_MS / retained; - const group = new GroupProducer(sequence); - producer.writeGroup(group); + const group = producer.createGroup(sequence); group.writeFrame({ payload, timestamp: Timestamp.fromMillis(sequence++) }); if (close) group.finish(); return group; diff --git a/js/net/src/auth.ts b/js/net/src/auth.ts index 0a4b2685a09..622271afe13 100644 --- a/js/net/src/auth.ts +++ b/js/net/src/auth.ts @@ -8,11 +8,11 @@ * undefined. There {@link Handle.add} rejects with {@link Unsupported} on moq-lite, and on * moq-transport keeps the token, with no grant, for the announcements whose route names it. * {@link Handle.grant} is the union of every token this side presented, and {@link Handle.add} - * presents another without reconnecting, returning its {@link Auth}. + * presents another without reconnecting, returning its {@link Credential}. * * A {@link Handle} passed to `connect` as `auth`, or the one a reconnecting `Connection` owns, * outlives its sessions: each presents every token it holds, so a route naming one of its - * {@link Auth}s keeps it across a reconnect. Only the peer's verdict ends such a token; a + * {@link Credential}s keeps it across a reconnect. Only the peer's verdict ends such a token; a * session ending leaves it for the next. Mirrors the Rust `moq_net::auth`. * * @module @@ -40,9 +40,9 @@ export interface Grant { /** * A token this side presented, which a route can name, on every session of its handle. - * {@link Auth.close} withdraws it. + * {@link Credential.close} withdraws it. */ -export interface Auth { +export interface Credential { /** * This token's own grant on the live session: undefined until its peer answers, while no * session is live, and again once it ends. diff --git a/js/net/src/auth_session.ts b/js/net/src/auth_session.ts index 3ddcae27b63..8fda004f5f9 100644 --- a/js/net/src/auth_session.ts +++ b/js/net/src/auth_session.ts @@ -1,6 +1,6 @@ import { Instant, Milli, Nano, now, sleep, wall } from "@moq/clock"; import { type Dispose, type Getter, Once, race, Signal } from "@moq/signals"; -import type { Auth, Grant, Issued, Request, Requests } from "./auth.ts"; +import type { Credential, Grant, Issued, Request, Requests } from "./auth.ts"; import { closeReason, error, ProtocolViolation, SessionCode, SessionError, StreamCode, StreamError } from "./error.ts"; import * as Path from "./path.ts"; import type { Reader, Stream, Writer } from "./stream.ts"; @@ -153,7 +153,7 @@ class Presented { } /** A token the application added to a {@link Handle}, presented on every session of it. */ -class Token implements Auth { +class Token implements Credential { readonly grant = new Signal(undefined); readonly closed: Promise; readonly answered: Promise; @@ -325,7 +325,7 @@ export function ended(handle: Handle): Error | undefined { * * A session made without one creates its own, returned by `Established.auth`, which ends with * that session. Pass one to `connect` as `auth` instead and it outlives its sessions: each - * presents every token the handle holds, so an {@link Auth} it returned keeps riding a route's + * presents every token the handle holds, so a {@link Credential} it returned keeps riding a route's * announcements across a reconnect. It backs one active session at a time, plus the ones * draining after a GOAWAY or a `close()`. Mirrors the Rust `moq_net::auth::Handle`. */ @@ -354,7 +354,7 @@ export class Handle { * handle's end. On moq-transport without AUTH it resolves at once with no grant: only a * request whose route names it carries it. */ - async add(token: string | Uint8Array): Promise { + async add(token: string | Uint8Array): Promise { // A copy, so the caller reusing its buffer never changes what a request carries. const bytes = typeof token === "string" ? new TextEncoder().encode(token) : token.slice(); const added = stateOf(this).add(bytes); @@ -680,7 +680,7 @@ export class AuthSession { * The bytes a request carries for `token`: undefined for none, for one another handle * issued, or for one that ended here. */ - carried(token: Auth | undefined): Uint8Array | undefined { + carried(token: Credential | undefined): Uint8Array | undefined { if (!this.#requests || !(token instanceof Token)) return undefined; const presented = this.#byToken.get(token); if (!presented || presented.ended || presented.withdrawn) return undefined; diff --git a/js/net/src/bandwidth.test.ts b/js/net/src/bandwidth.test.ts index f2dd349901f..92c9d1269d3 100644 --- a/js/net/src/bandwidth.test.ts +++ b/js/net/src/bandwidth.test.ts @@ -102,10 +102,10 @@ test("an idle track claims nothing", async () => { // What it would get if a viewer joined, so a rendition stopped for lack of // bandwidth can resume after its viewers left. expect(idle.peek()).toBe(1_000_000); - expect(idle.grant.peek()).toBe(1_000_000); + expect(idle.rate.peek()).toBe(1_000_000); // The idle share keeps following the estimate. - const next = idle.grant.changed(); + const next = idle.rate.changed(); estimate.set(4_000_000); expect(await next).toBe(2_000_000); expect(watched.peek()).toBe(4_000_000); @@ -133,7 +133,7 @@ test("a share wakes when a sibling goes idle", async () => { expect(mine.peek()).toBe(1_000_000); expect(sibling.peek()).toBe(1_000_000); - const next = mine.grant.changed(); + const next = mine.rate.changed(); siblingSub.close(); expect(await next).toBe(2_000_000); expect(mine.peek()).toBe(2_000_000); @@ -152,7 +152,7 @@ test("an unchanged slice still follows the estimate past the cap", async () => { estimate.set(10_000_000); expect(reserved.peek()).toBe(4_000_000); - const next = reserved.grant.changed(); + const next = reserved.rate.changed(); // Still miles above the reservation, so the slice holds at 4 Mbps. estimate.set(9_000_000); expect(reserved.peek()).toBe(4_000_000); @@ -180,7 +180,7 @@ test("a parked share is woken by sibling demand", async () => { expect(reserved.peek()).toBe(1_000_000); expect(sibling.peek()).toBe(1_000_000); - const next = reserved.grant.changed(); + const next = reserved.rate.changed(); siblingSub.close(); expect(await next).toBe(2_000_000); @@ -220,7 +220,7 @@ test("closing a reservation releases it", async () => { const second = allocator.reserve(secondTrack.demand(), 4_000_000); expect(second.peek()).toBe(1_000_000); - const orphan = first.grant; + const orphan = first.rate; expect(orphan.peek()).toBe(1_000_000); const next = orphan.changed(); @@ -267,7 +267,7 @@ test("update wakes a parked reader", async () => { const reserved = allocator.reserve(producer.demand(), 1_000_000); expect(reserved.peek()).toBe(1_000_000); - const next = reserved.grant.changed(); + const next = reserved.rate.changed(); reserved.update(4_000_000); expect(await next).toBe(4_000_000); @@ -293,7 +293,7 @@ test("a closed allocator reports no grant", () => { allocator.close(); expect(reserved.peek()).toBeUndefined(); - expect(reserved.grant.peek()).toBeUndefined(); + expect(reserved.rate.peek()).toBeUndefined(); }); test("reserve and update reject a non-finite or negative ceiling", () => { diff --git a/js/net/src/bandwidth.ts b/js/net/src/bandwidth.ts index 990a47d4d95..5e2788d2d1a 100644 --- a/js/net/src/bandwidth.ts +++ b/js/net/src/bandwidth.ts @@ -81,7 +81,7 @@ interface Entry { demand: Demand; priority: number; max: number; - grant: Signal; + rate: Signal; } interface Registry { @@ -213,7 +213,7 @@ export class Allocator implements Handle { * as the sender is publishing, change the ceiling with * {@link Reservation.update}, and close it to hand the room back. * - * {@link Reservation.peek} / {@link Reservation.grant} report `undefined` + * {@link Reservation.peek} / {@link Reservation.rate} report `undefined` * while the connection has no estimate, telling a sender to hold its current * rate rather than encode at zero. While nothing is subscribed to the track they * report the slice the track would get back, without claiming it from the others. @@ -223,18 +223,18 @@ export class Allocator implements Handle { this.#prune(); const id = this.#nextId++; - const grant = new Signal(undefined); + const rate = new Signal(undefined); this.#entries.mutate((entries) => { entries.push({ id, demand: track, priority: hooks.demandPriority(track), max, - grant, + rate, }); }); - const reservation = makeReservation(this.#registry, id, grant); + const reservation = makeReservation(this.#registry, id, rate); this.#publish(); return reservation; } @@ -247,7 +247,7 @@ export class Allocator implements Handle { if (!this.#alive.peek()) return; this.#alive.set(false); for (const entry of this.#entries.peek()) { - entry.grant.set(undefined); + entry.rate.set(undefined); } this.#entries.set([]); this.#signals.close(); @@ -265,7 +265,7 @@ export class Allocator implements Handle { const entries = this.#entries.peek(); const wants = wantsOf(entries); for (const entry of entries) { - entry.grant.set(estimate == null ? undefined : shareOf(estimate, wants, entry)); + entry.rate.set(estimate == null ? undefined : shareOf(estimate, wants, entry)); } } @@ -299,7 +299,7 @@ export class Allocator implements Handle { } } -let makeReservation: (registry: Registry, id: number, grant: Signal) => Reservation; +let makeReservation: (registry: Registry, id: number, rate: Signal) => Reservation; /** * One track's standing claim on an {@link Allocator}, held for as long as the @@ -312,23 +312,23 @@ let makeReservation: (registry: Registry, id: number, grant: Signal; + readonly #rate: Signal; #closed = false; - private constructor(registry: Registry, id: number, grant: Signal) { + private constructor(registry: Registry, id: number, rate: Signal) { this.#registry = registry; this.#id = id; - this.#grant = grant; + this.#rate = rate; } static { - makeReservation = (registry, id, grant) => new Reservation(registry, id, grant); + makeReservation = (registry, id, rate) => new Reservation(registry, id, rate); } /** * This reservation's slice right now. * - * Stateless, unlike {@link grant}, which is a signal of what was last + * Stateless, unlike {@link rate}, which is a signal of what was last * published and so can lag a synchronous {@link update} by a microtask if * something else writes the registry first. Call this after {@link update}. */ @@ -344,8 +344,8 @@ export class Reservation implements Disposable { * been closed: hold the current rate rather than encode at zero. While nothing * is subscribed it is the slice the track would get back. */ - get grant(): Getter { - return this.#grant; + get rate(): Getter { + return this.#rate; } /** @@ -364,7 +364,7 @@ export class Reservation implements Disposable { close(): void { if (this.#closed) return; this.#closed = true; - this.#grant.set(undefined); + this.#rate.set(undefined); this.#registry.release(this.#id); } diff --git a/js/net/src/broadcast.test.ts b/js/net/src/broadcast.test.ts index ad250583bc9..821de20676e 100644 --- a/js/net/src/broadcast.test.ts +++ b/js/net/src/broadcast.test.ts @@ -2,7 +2,7 @@ import { expect, setSystemTime, test } from "bun:test"; import { Milli } from "@moq/clock"; import { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import { GroupTooLarge, NotFound } from "./error.ts"; -import { Producer as GroupProducer, MAX_GROUP_FRAMES } from "./group.ts"; +import { MAX_GROUP_FRAMES } from "./group.ts"; import { hooks } from "./internal.ts"; import { textFrame } from "./mock.ts"; import { Timescale, Timestamp } from "./time.ts"; @@ -85,8 +85,7 @@ test("a replacement producer starts over", async () => { const firstRequest = await firstPull; if (!firstRequest) throw new Error("expected first request"); const first = firstRequest.accept({ timescale: Timescale.MILLI }); - const group = new GroupProducer(8); - first.writeGroup(group); + const group = first.createGroup(8); group.writeFrame(textFrame("a", Timestamp.fromMillis(1000))); group.finish(); firstSubscriber.close(); diff --git a/js/net/src/connection/bandwidth.test.ts b/js/net/src/connection/bandwidth.test.ts index a0498fdd08c..6cc6fc0721f 100644 --- a/js/net/src/connection/bandwidth.test.ts +++ b/js/net/src/connection/bandwidth.test.ts @@ -46,7 +46,7 @@ test("a connection samples the send rate onto the allocator", async () => { const connection = new Connection({ url }); try { await waitUntil(() => connection.status.peek() === "connected"); - const allocator = connection.bandwidth.peek(); + const allocator = connection.allocator.peek(); if (!allocator) throw new Error("missing allocator"); const track = new TrackProducer("video").accept({ priority: 60 }); @@ -68,8 +68,8 @@ test("two publishers on one connection split the estimate by priority", async () await waitUntil(() => first.status.peek() === "connected"); await waitUntil(() => second.status.peek() === "connected"); - const allocator = first.bandwidth.peek(); - expect(allocator).toBe(second.bandwidth.peek()); + const allocator = first.allocator.peek(); + expect(allocator).toBe(second.allocator.peek()); if (!allocator) throw new Error("missing allocator"); const audio = new TrackProducer("audio").accept({ priority: 80 }); @@ -97,7 +97,7 @@ test("an idle track on a live connection claims nothing", async () => { const handle = new Connection({ url }); try { await waitUntil(() => handle.status.peek() === "connected"); - const allocator = handle.bandwidth.peek(); + const allocator = handle.allocator.peek(); if (!allocator) throw new Error("missing allocator"); const watched = new TrackProducer("watched").accept({ priority: 60 }); @@ -125,7 +125,7 @@ test("a private connection still exposes an allocator", async () => { }); try { await waitUntil(() => connection.status.peek() === "connected"); - const allocator = connection.bandwidth.peek(); + const allocator = connection.allocator.peek(); if (!allocator) throw new Error("missing allocator"); const track = new TrackProducer("video").accept({ priority: 60 }); diff --git a/js/net/src/connection/connect.ts b/js/net/src/connection/connect.ts index 254cb967cbd..df0c598ab1c 100644 --- a/js/net/src/connection/connect.ts +++ b/js/net/src/connection/connect.ts @@ -246,7 +246,7 @@ export interface ConnectProps { /** * Build the session on `auth`, so it presents every token the handle holds and a route - * naming one of its `Auth`s keeps it across a reconnect. Omit to give the session a handle + * naming one of its `Credential`s keeps it across a reconnect. Omit to give the session a handle * of its own, which ends with it. * * The handle backs one active session at a time, plus the ones draining after a GOAWAY or a diff --git a/js/net/src/connection/pool.ts b/js/net/src/connection/pool.ts index 0396fcd5f4d..6f97610c1dc 100644 --- a/js/net/src/connection/pool.ts +++ b/js/net/src/connection/pool.ts @@ -184,7 +184,7 @@ export class Connection { * against one registry. Borrowed, not owned: the type has no close, since * closing it would starve every other handle. */ - readonly bandwidth: Getter; + readonly allocator: Getter; /** * The origin for the current URL, or undefined while disabled or URL-less. @@ -221,7 +221,7 @@ export class Connection { readonly #established = new Signal(undefined); readonly #probe = new Signal | undefined>(undefined); readonly #origin = new Signal(undefined); - readonly #bandwidth = new Signal(undefined); + readonly #allocator = new Signal(undefined); readonly #auth = new Signal(undefined); readonly #error = new Signal(undefined); #signals: Effect; @@ -251,7 +251,7 @@ export class Connection { this.error = this.#error; this.probe = new Follow(this.#probe); this.origin = this.#origin; - this.bandwidth = this.#bandwidth; + this.allocator = this.#allocator; this.auth = this.#auth; this.transport = this.#signals.computed((effect) => effect.get(this.#established)?.transport); @@ -278,7 +278,7 @@ export class Connection { effect.cleanup(lease.release); effect.set(this.#origin, lease.origin, undefined); - effect.set(this.#bandwidth, lease.connection.bandwidth, undefined); + effect.set(this.#allocator, lease.connection.allocator, undefined); effect.set(this.#auth, lease.connection.auth, undefined); // Proxy the shared loop's outputs, so this handle reads like its own connection. @@ -329,7 +329,7 @@ export class Connection { signals.run((effect) => { if (!effect.get(this.enabled) || !effect.get(href)) return; effect.set(this.#origin, origin, undefined); - effect.set(this.#bandwidth, loop.bandwidth, undefined); + effect.set(this.#allocator, loop.allocator, undefined); effect.set(this.#auth, loop.auth, undefined); }); signals.run((effect) => effect.set(this.#status, effect.get(loop.status), "disconnected")); diff --git a/js/net/src/connection/reload.ts b/js/net/src/connection/reload.ts index cbd713f336c..bc8202a2df8 100644 --- a/js/net/src/connection/reload.ts +++ b/js/net/src/connection/reload.ts @@ -222,7 +222,7 @@ export class Reload { * estimate is `undefined` while disconnected, which tells a sender to hold * its rate rather than encode at zero. */ - readonly bandwidth: Allocator; + readonly allocator: Allocator; /** * The auth handle every session of the loop is built on, spanning reconnects. @@ -406,8 +406,8 @@ export class Reload { effect.set(this.#probeSource, effect.get(this.established)?.probe, undefined); }); - this.bandwidth = new Allocator(this.#estimate); - this.#signals.cleanup(() => this.bandwidth.close()); + this.allocator = new Allocator(this.#estimate); + this.#signals.cleanup(() => this.allocator.close()); // The transport has no event for the send-rate estimate, so sample on our // own schedule and skip a tick while the previous snapshot is outstanding. diff --git a/js/net/src/connection/tokens.test.ts b/js/net/src/connection/tokens.test.ts index 4faa1c0b09d..43a11b8be52 100644 --- a/js/net/src/connection/tokens.test.ts +++ b/js/net/src/connection/tokens.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import type { Auth, Handle } from "../auth.ts"; +import type { Credential, Handle } from "../auth.ts"; import * as Ietf from "../ietf/index.ts"; import { createMockTransportPair } from "../mock.ts"; import { Reader } from "../stream.ts"; @@ -55,19 +55,19 @@ test("no tokens present nothing", () => { /** A handle whose answers the test releases one token at a time. */ function handle() { - const answers = new Map void>(); + const answers = new Map void>(); const closed: string[] = []; const presented: string[] = []; const fake = { add(token: string) { presented.push(token); - return new Promise((resolve) => answers.set(token, resolve)); + return new Promise((resolve) => answers.set(token, resolve)); }, } as unknown as Handle; const answer = async (token: string) => { const resolve = answers.get(token); if (!resolve) throw new Error(`${token} was never presented`); - resolve({ close: () => closed.push(token) } as unknown as Auth); + resolve({ close: () => closed.push(token) } as unknown as Credential); // Let the answer and the settle it schedules run. for (let i = 0; i < 3; i++) await Promise.resolve(); }; diff --git a/js/net/src/connection/tokens.ts b/js/net/src/connection/tokens.ts index 5728c525cae..66106369e52 100644 --- a/js/net/src/connection/tokens.ts +++ b/js/net/src/connection/tokens.ts @@ -1,4 +1,4 @@ -import { type Auth, type Handle, Unsupported } from "../auth.ts"; +import { type Handle, type Credential as Presented, Unsupported } from "../auth.ts"; import type { Established } from "./established.ts"; /** What one dial presents, decided from its URL, the offered versions, and the tokens. @internal */ @@ -56,7 +56,7 @@ export function extra(credential: Credential, tokens: readonly string[]): string } interface Entry { - auth?: Auth; + auth?: Presented; pending: boolean; retired: boolean; } diff --git a/js/net/src/flate/group.test.ts b/js/net/src/flate/group.test.ts index 517e47c5cca..eb89465f253 100644 --- a/js/net/src/flate/group.test.ts +++ b/js/net/src/flate/group.test.ts @@ -70,13 +70,12 @@ test("declared plain bytes consume the group budget before any inflation", () => } }); -test("empty frames preserve the window and prewritten groups bind without duplicating plain copies", async () => { - const group = new Group(0); +test("empty frames preserve the window", async () => { + const track = new Track("compressed").accept({ compress: true }); + const group = track.createGroup(0); group.writeFrame({ payload }); group.writeFrame({ payload: new Uint8Array() }); const reader = group.mirror(); - const track = new Track("compressed").accept({ compress: true }); - track.writeGroup(group); group.writeFrame({ payload }); group.finish(); for (const expected of [payload, new Uint8Array(), payload]) diff --git a/js/net/src/group.ts b/js/net/src/group.ts index 4e04be14278..faca0fbd2e0 100644 --- a/js/net/src/group.ts +++ b/js/net/src/group.ts @@ -236,7 +236,6 @@ export class Producer { group.#admits ??= []; group.#admits.push(admit); }; - hooks.groupStart = (group) => (group.#state.total.peek() > 0 ? group.#state.timestamp : undefined); hooks.overRefresh = (group, ratio) => { const state = group.#state; const first = state.frames.peek()[0]; diff --git a/js/net/src/hop.ts b/js/net/src/hop.ts index 75f4047572e..b28e22e4473 100644 --- a/js/net/src/hop.ts +++ b/js/net/src/hop.ts @@ -8,7 +8,7 @@ * @module */ import * as z from "zod/mini"; -import type { Auth } from "./auth.ts"; +import type { Credential } from "./auth.ts"; import type * as Epoch from "./epoch.ts"; import { isLeadingOnes, type StreamVersion } from "./stream.ts"; @@ -116,7 +116,7 @@ export interface Route { * Swapping it renews the request with REQUEST_UPDATE from draft 16, or ends and makes it * again before. Local: a relay never forwards it. Mirrors `Route::auth` in rs/moq-net. */ - auth?: Auth; + auth?: Credential; } /** Constructors and helpers for {@link Route}. */ @@ -125,7 +125,9 @@ export const Route = { default: { hops: [], cost: Cost.zero } as Route, /** Fill route defaults and saturate the static price at the wire ceiling. */ - normalize(route: Route | { epoch?: Epoch.Valid; hops?: readonly Hop[]; cost?: Cost; auth?: Auth } = {}): Route { + normalize( + route: Route | { epoch?: Epoch.Valid; hops?: readonly Hop[]; cost?: Cost; auth?: Credential } = {}, + ): Route { const cost = route.cost ?? Cost.zero; if (typeof cost !== "bigint" || cost < 0n) throw new RangeError("route cost must be a non-negative bigint"); const max = 2n ** 62n - 1n; diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index 89201ddcc4a..c6bf8a7bf72 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -1,11 +1,11 @@ import { expect, jest, onTestFinished, spyOn, test } from "bun:test"; import { Manual, Milli, Nano } from "@moq/clock"; import { Signal } from "@moq/signals"; -import type { Auth, Grant } from "../auth.ts"; +import type { Credential, Grant } from "../auth.ts"; import { Producer as BroadcastProducer } from "../broadcast.ts"; import * as Epoch from "../epoch.ts"; import { error, ProtocolViolation, SessionCode, SessionError, StreamCode, unauthorized } from "../error.ts"; -import { Producer as GroupProducer, MAX_GROUP_FRAMES } from "../group.ts"; +import { MAX_GROUP_FRAMES } from "../group.ts"; import { type Hop, HopSchema } from "../hop.ts"; import { hooks } from "../internal.ts"; import { createMockTransportPair, SessionBroadcast } from "../mock.ts"; @@ -278,10 +278,9 @@ test("TRACK_STATUS is answered on every draft without subscribing", async () => maxAge: Milli(5000), priority: 2, }); - const group = new GroupProducer(4); + const group = track.createGroup(4); group.writeFrame({ payload: new Uint8Array([1]), timestamp: Timestamp.fromMillis(0) }); group.writeFrame({ payload: new Uint8Array([2]), timestamp: Timestamp.fromMillis(1) }); - track.writeGroup(group); const subscribed = spyOn(track, "subscribe"); const { stream, wire } = requestStream(version); @@ -791,24 +790,21 @@ test("a blocked group header is reset when the group expires", async () => { server, ); - const old = new GroupProducer(0); + const old = track.createGroup(0); old.writeFrame({ payload: new TextEncoder().encode("old"), timestamp: Timestamp.fromMillis(0) }); old.finish(); - track.writeGroup(old); await headerStarted; - const edge = new GroupProducer(1); + const edge = track.createGroup(1); edge.writeFrame({ payload: new TextEncoder().encode("edge"), timestamp: Timestamp.fromMillis(10_000) }); edge.finish(); - track.writeGroup(edge); // A group beyond the edge, so group 0's reach (10s, where group 1 begins) is // provably past the budget. A group is bounded by where its successor starts, so // the successor alone never convicts it: nothing yet proves group 0 ends sooner. - const later = new GroupProducer(2); + const later = track.createGroup(2); later.writeFrame({ payload: new TextEncoder().encode("later"), timestamp: Timestamp.fromMillis(20_000) }); later.finish(); - track.writeGroup(later); const resetBeforeRelease = await Promise.race([ streamReset.then(() => true), @@ -877,10 +873,9 @@ test("a group stream whose FIN never completes is reset when the group expires", ); const write = (sequence: number) => { - const group = new GroupProducer(sequence); + const group = track.createGroup(sequence); group.writeFrame({ payload: new TextEncoder().encode("frame"), timestamp: Timestamp.fromMillis(0) }); group.finish(); - track.writeGroup(group); }; write(0); @@ -962,10 +957,9 @@ test("a group stream whose FIN never completes is reset after the cache evicts i // Frozen timestamps, so only the wall clock since group 1 arrived convicts group 0. const write = (sequence: number) => { - const group = new GroupProducer(sequence); + const group = track.createGroup(sequence); group.writeFrame({ payload: new TextEncoder().encode("frame"), timestamp: Timestamp.fromMillis(0) }); group.finish(); - track.writeGroup(group); }; write(0); @@ -1048,10 +1042,9 @@ test("a group that goes stale while its stream opens writes nothing", async () = ); const write = (sequence: number, ms: number) => { - const group = new GroupProducer(sequence); + const group = track.createGroup(sequence); group.writeFrame({ payload: new TextEncoder().encode("frame"), timestamp: Timestamp.fromMillis(ms) }); group.finish(); - track.writeGroup(group); }; write(0, 0); await opening; @@ -1965,10 +1958,10 @@ function republish(origin: OriginProducer, old: BroadcastProducer) { /** The tokens one session issued, each carried as its own bytes. */ class Tokens { readonly ended = new Signal(0); - #issued = new Map(); + #issued = new Map(); - issue(value: string): Auth { - const token: Auth = { + issue(value: string): Credential { + const token: Credential = { grant: new Signal(undefined), closed: new Promise(() => {}), close: () => { @@ -1980,7 +1973,7 @@ class Tokens { return token; } - carried(token: Auth | undefined): Uint8Array | undefined { + carried(token: Credential | undefined): Uint8Array | undefined { return token && this.#issued.get(token); } } @@ -3283,8 +3276,7 @@ test.each(["ascending", "descending"] as const)("draft-22: a sparse fill serves const fx = fixture(); const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); for (const sequence of [0, 3, 9]) { - const group = new GroupProducer(sequence); - track.writeGroup(group); + const group = track.createGroup(sequence); for (let i = 0; i < 2; i++) group.writeFrame({ payload: new TextEncoder().encode(`${sequence}.${i}`), timestamp: Timestamp.now() }); group.finish(); @@ -3353,8 +3345,7 @@ async function subscribeOkLargest(version: IetfVersion): Promise; updating?: boolean; }; @@ -192,7 +192,7 @@ interface Namespaces { /** The bytes a request carries for a token this session issued. */ interface Carrier { - carried(token: Auth | undefined): Uint8Array | undefined; + carried(token: Credential | undefined): Uint8Array | undefined; /** Bumps whenever one of the session's tokens ends, so a request carrying it drops it. */ readonly ended: Getter; } @@ -216,10 +216,10 @@ interface Target { withdraw(key: Path.Valid): Promise; /** The token the peer holds a namespace under, or undefined when its advertisement carries none. */ - held(key: Path.Valid): Auth | undefined; + held(key: Path.Valid): Credential | undefined; /** The token an advertisement naming `auth` carries: only a request can carry one. */ - carry(auth: Auth | undefined): Auth | undefined; + carry(auth: Credential | undefined): Credential | undefined; } /** What {@link Publisher.runGroup} needs to serve one group. */ @@ -2040,7 +2040,7 @@ export class Publisher { } /** `auth` when a request of this session can carry it. */ - #carry(auth: Auth | undefined): Auth | undefined { + #carry(auth: Credential | undefined): Credential | undefined { return this.#auth?.carried(auth) === undefined ? undefined : auth; } diff --git a/js/net/src/ietf/subscriber.ts b/js/net/src/ietf/subscriber.ts index c7084e45e9b..a9cdd085908 100644 --- a/js/net/src/ietf/subscriber.ts +++ b/js/net/src/ietf/subscriber.ts @@ -19,7 +19,7 @@ import { sessionCause, unauthorized, } from "../error.ts"; -import * as netGroup from "../group.ts"; +import type * as netGroup from "../group.ts"; import { Cost, type Route, routesEqual, UNKNOWN_HOP } from "../hop.ts"; import { finalSequence, @@ -1617,8 +1617,7 @@ export class Subscriber { `group ${group.groupId} is at or past the declared end ${subscription.end}`, ); } - producer = new netGroup.Producer(group.groupId); - track.writeGroup(producer); + producer = track.createGroup(group.groupId); } return producer; }; diff --git a/js/net/src/integration.test.ts b/js/net/src/integration.test.ts index b8bfb03686d..fd087c7d256 100644 --- a/js/net/src/integration.test.ts +++ b/js/net/src/integration.test.ts @@ -13,7 +13,6 @@ import { } from "./connection/index.ts"; import * as Epoch from "./epoch.ts"; import { SessionCode, SessionError, StreamCode, StreamError, TooFarBehind } from "./error.ts"; -import { Producer as GroupProducer } from "./group.ts"; import * as Ietf from "./ietf/index.ts"; import { Parameters } from "./ietf/parameters.ts"; import { Publisher as IetfPublisher } from "./ietf/publisher.ts"; @@ -1042,8 +1041,7 @@ test.each(["gap", "end"])("integration: lite fetch rejects coalesced misses at % let serving: Promise | undefined; if (missing === "gap") { const producer = broadcast.createTrack("video", { timescale: Timescale.MILLI }); - const group = new GroupProducer(1); - producer.writeGroup(group); + const group = producer.createGroup(1); group.finish(); } else { serving = (async () => { diff --git a/js/net/src/internal.ts b/js/net/src/internal.ts index df098329efb..fb76722f169 100644 --- a/js/net/src/internal.ts +++ b/js/net/src/internal.ts @@ -526,8 +526,6 @@ export const hooks: { * the group joined accepted it. */ admitGroupStart: (group: GroupProducer, admit: (start: Timestamp) => () => void) => void; - /** Return a group producer's first timestamp, if it already holds a frame. */ - groupStart: (group: GroupProducer) => Timestamp | undefined; /** Whether a group's bytes after its first frame exceed `ratio` times the first frame. */ overRefresh: (group: GroupProducer, ratio: number) => boolean; /** Keep a mirror of a group accepted unverified below its track's eviction watermark out of media-time expiry. */ @@ -729,9 +727,6 @@ export const hooks: { admitGroupStart: () => { throw new Error("group.ts not loaded"); }, - groupStart: () => { - throw new Error("group.ts not loaded"); - }, overRefresh: () => { throw new Error("group.ts not loaded"); }, diff --git a/js/net/src/lite/publisher.test.ts b/js/net/src/lite/publisher.test.ts index 04426fc450a..a4f98abb92a 100644 --- a/js/net/src/lite/publisher.test.ts +++ b/js/net/src/lite/publisher.test.ts @@ -4,7 +4,7 @@ import { Signal } from "@moq/signals"; import type { Grant } from "../auth.ts"; import { Producer as BroadcastProducer } from "../broadcast.ts"; import { fromTransport, SessionCode, StreamCode, StreamError, toStreamCode } from "../error.ts"; -import { Producer as GroupProducer } from "../group.ts"; +import type { Producer as GroupProducer } from "../group.ts"; import { randomHop } from "../hop.ts"; import { Version as IetfVersion } from "../ietf/version.ts"; import { hooks } from "../internal.ts"; @@ -210,10 +210,9 @@ async function subscribeEnd(sequences: number[], version: Version = Version.DRAF // Finish the track only once it's being served, so the publisher observes a live // track ending rather than resolving a subscribe against an already-closed one. for (const sequence of sequences) { - const group = new GroupProducer(sequence); + const group = track.createGroup(sequence); group.writeFrame(textFrame("hello", Timestamp.fromMillis(sequence))); group.finish(); - track.writeGroup(group); // Let the publisher drain this group before the next, so arrival order is the // order given rather than whatever the cache hands over in one batch. A group that @@ -262,7 +261,7 @@ async function groupSendOrders(options: { version?: Version; }) { const { priority, sequences, update, version = Version.DRAFT_05 } = options; - const groups = sequences.map((sequence) => new GroupProducer(sequence)); + const groups: GroupProducer[] = []; const pair = createMockTransportPair(ALPN_05); const origin = new OriginProducer(); const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); @@ -286,15 +285,16 @@ async function groupSendOrders(options: { const opened = pair.client.incomingUnidirectionalStreams.getReader(); try { - for (const [index, group] of groups.entries()) { + for (const [index, sequence] of sequences.entries()) { if (index === 1 && update !== undefined) { await replayUpdate({ priority: update }).encode(client.writer, version); // Wait for the publisher to apply it, rather than assuming it beat the next group. while (track.subscription.peek()?.priority !== update) await track.subscription.changed(); } + const group = track.createGroup(sequence); + groups.push(group); group.writeFrame(textFrame("hello")); - track.writeGroup(group); // One stream per group, in the order given: wait for this one before queuing the next. await servingNextGroup(opened); @@ -374,9 +374,8 @@ test("lite draft-05: a subscribe update re-ranks a group already on the wire", a void publisher.runSubscribe(msg, server); // Leave the group open, so its stream is still being served when the update lands. - const group = new GroupProducer(4); + const group = track.createGroup(4); group.writeFrame(textFrame("hello")); - track.writeGroup(group); const opened = pair.client.incomingUnidirectionalStreams.getReader(); await servingNextGroup(opened); @@ -437,9 +436,8 @@ test("lite draft-05: a subscribe update during the stream open still ranks the g }); void publisher.runSubscribe(msg, server); - const group = new GroupProducer(4); + const group = track.createGroup(4); group.writeFrame(textFrame("hello")); - track.writeGroup(group); try { // The publisher is now parked inside the open, having already read priority 1. @@ -487,13 +485,14 @@ test("lite draft-05: many concurrent groups share one subscription listener", as void publisher.runSubscribe(msg, server); // Leave every group open, so all of their streams are in flight at once. - const groups = Array.from({ length: count }, (_, sequence) => new GroupProducer(sequence)); + const groups: GroupProducer[] = []; const opened = pair.client.incomingUnidirectionalStreams.getReader(); try { - for (const group of groups) { + for (let sequence = 0; sequence < count; sequence++) { + const group = track.createGroup(sequence); + groups.push(group); group.writeFrame(textFrame("hello")); - track.writeGroup(group); await servingNextGroup(opened); } opened.releaseLock(); @@ -528,10 +527,9 @@ test("lite draft-05: the fetch response ranks the publisher's own writes", async const broadcast = publish(origin, Path.from("test")); const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); - const group = new GroupProducer(7); + const group = track.createGroup(7); group.writeFrame(textFrame("hello")); group.finish(); - track.writeGroup(group); const client = await Stream.open(pair.client, { version: Version.DRAFT_05 }); @@ -564,10 +562,9 @@ test("lite draft-06: an unchecked track's fetched frames carry their send time", const broadcast = publish(origin, Path.from("test")); const track = broadcast.createTrack("video", { timescale: Timescale.MICRO, ietf: IetfVersion.DRAFT_22 }); - const group = new GroupProducer(0); + const group = track.createGroup(0); group.writeFrame(textFrame("hello", Timestamp.fromMillis(36_000_000))); group.finish(); - track.writeGroup(group); const client = await Stream.open(pair.client, { version: Version.DRAFT_06 }); const server = await Stream.accept(pair.server, Version.DRAFT_06); @@ -717,10 +714,9 @@ async function servedSubscription( release: gate.release, // Stamped by sequence, so a group served out of order still starts in order. serve(sequence: number) { - const group = new GroupProducer(sequence); + const group = track.createGroup(sequence); for (const frame of frames) group.writeFrame(textFrame(frame, Timestamp.fromMillis(sequence))); group.finish(); - track.writeGroup(group); }, // Makes the next group stream withhold its FIN from the client, the way a stream the // browser never finishes sending looks; resolves with the reason the publisher resets it. @@ -832,8 +828,7 @@ test("lite draft-06: a cut group is dropped early, once", async () => { expect(await sub.servedSequence()).toBe(0); expect("start" in (await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_06))).toBe(true); - const cut = new GroupProducer(1); - sub.track.writeGroup(cut); + const cut = sub.track.createGroup(1); cut.abort(new Error("cut")); const resp = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_06); if (!("drop" in resp)) throw new Error("expected SUBSCRIBE_DROP"); @@ -859,8 +854,7 @@ for (const version of [Version.DRAFT_06, Version.DRAFT_07]) { expect(await sub.servedSequence()).toBe(0); expect("start" in (await decodeSubscribeResponse(sub.client.reader, version))).toBe(true); - const cut = new GroupProducer(1); - sub.track.writeGroup(cut); + const cut = sub.track.createGroup(1); cut.abort(new StreamError(StreamCode(70), { message: "cut" })); const resp = await decodeSubscribeResponse(sub.client.reader, version); if (!("drop" in resp)) throw new Error("expected SUBSCRIBE_DROP"); @@ -989,8 +983,7 @@ test("lite draft-06: a cut dropped then re-created is not served", async () => { expect(await sub.servedSequence()).toBe(0); expect("start" in (await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_06))).toBe(true); - const cut = new GroupProducer(1); - sub.track.writeGroup(cut); + const cut = sub.track.createGroup(1); cut.abort(new Error("cut")); const resp = await decodeSubscribeResponse(sub.client.reader, Version.DRAFT_06); if (!("drop" in resp)) throw new Error("expected SUBSCRIBE_DROP"); @@ -1205,9 +1198,8 @@ for (const skipped of ["failed", "stale"] as const) { }); try { hooks.startTrack(sub.track, { start: 5, requested: 5 }); - const group = new GroupProducer(5); + const group = sub.track.createGroup(5); group.writeFrame(textFrame("old", Timestamp.fromMillis(5))); - sub.track.writeGroup(group); if (skipped === "failed") group.abort(new Error("cut")); else group.finish(); if (skipped === "failed") hooks.dropTrackGroups(sub.track, 7, 8, new Error("cut")); @@ -1667,10 +1659,9 @@ test("lite draft-07: subscribe end precedes groups below a declared finish", asy ); try { - const first = new GroupProducer(0); + const first = track.createGroup(0); first.writeFrame(textFrame("hello")); first.finish(); - track.writeGroup(first); track.finishAt({ group: 2, frame: 0 }); const start = await decodeSubscribeResponse(client.reader, Version.DRAFT_07); @@ -1679,10 +1670,9 @@ test("lite draft-07: subscribe end precedes groups below a declared finish", asy const early = await pending; expect("end" in early).toBe(true); - const second = new GroupProducer(1); + const second = track.createGroup(1); second.writeFrame(textFrame("hello")); second.finish(); - track.writeGroup(second); track.finish(); track.close(); @@ -1722,10 +1712,9 @@ async function heldOpenEnd() { server, ); - const group = new GroupProducer(0); + const group = track.createGroup(0); group.writeFrame(textFrame("hello")); group.finish(); - track.writeGroup(group); track.finish(); track.close(); @@ -1805,10 +1794,9 @@ test("lite draft-07: a group whose close fails is dropped", async () => { ); try { - const group = new GroupProducer(0); + const group = track.createGroup(0); group.writeFrame(textFrame("hello")); group.finish(); - track.writeGroup(group); track.finish(); track.close(); @@ -1856,10 +1844,9 @@ test("blocked DROP responses stop opening later groups", async () => { await write(chunk); }); const append = (sequence: number) => { - const group = new GroupProducer(sequence); + const group = track.createGroup(sequence); group.writeFrame(textFrame("frame")); group.finish(); - track.writeGroup(group); }; for (let sequence = 0; sequence < 8; sequence++) append(sequence); const serving = publisher.runSubscribe( @@ -1933,10 +1920,9 @@ async function serve( void publisher.runSubscribe(msg, server); for (const [sequence, frames] of Object.entries(groups)) { - const group = new GroupProducer(Number(sequence)); + const group = track.createGroup(Number(sequence)); for (const frame of frames) group.writeFrame(textFrame(frame)); group.finish(); - track.writeGroup(group); // Let the publisher drain each group before the next, so the streams arrive in // the order written rather than whatever the cache hands over in one batch. @@ -2114,10 +2100,9 @@ async function saturatedGroup() { void publisher.runSubscribe(msg, server); // A finished group still has frames to send, so its own close must not drop it. - const group = new GroupProducer(0); + const group = track.createGroup(0); group.writeFrame(textFrame("hello")); group.finish(); - track.writeGroup(group); // The group is queued inside the open from here on. await opened; @@ -2195,16 +2180,14 @@ test("lite draft-05: a blocked group header is reset when the group expires", as server, ); - const old = new GroupProducer(0); + const old = track.createGroup(0); old.writeFrame({ payload: new TextEncoder().encode("old"), timestamp: Timestamp.fromMillis(0) }); old.finish(); - track.writeGroup(old); await headerStarted; - const edge = new GroupProducer(1); + const edge = track.createGroup(1); edge.writeFrame({ payload: new TextEncoder().encode("edge"), timestamp: Timestamp.fromMillis(1000) }); edge.finish(); - track.writeGroup(edge); const resetBeforeRelease = await Promise.race([ streamReset.then(() => true), @@ -2319,7 +2302,7 @@ test("lite draft-05: a group parked at its tail resets as too old when it expire if (!server) throw new Error("publisher never accepted the subscribe stream"); const opened = pair.client.incomingUnidirectionalStreams.getReader(); // Left open: its producer never finishes it. - const open = new GroupProducer(0); + const open = track.createGroup(0); try { void publisher.runSubscribe( @@ -2327,7 +2310,6 @@ test("lite draft-05: a group parked at its tail resets as too old when it expire server, ); open.writeFrame(frame(0)); - track.writeGroup(open); const next = await opened.read(); if (next.done) throw new Error("publisher never opened the group stream"); @@ -2339,10 +2321,9 @@ test("lite draft-05: a group parked at its tail resets as too old when it expire // The track runs a second past group 0's successor while group 0 waits for more. for (const ms of [1000, 2000]) { - const group = new GroupProducer(ms / 1000); + const group = track.createGroup(ms / 1000); group.writeFrame(frame(ms)); group.finish(); - track.writeGroup(group); } const end = await stream.done().then( @@ -2410,10 +2391,9 @@ test("lite draft-05: a group that goes stale while its stream opens writes nothi ); const write = (sequence: number, ms: number) => { - const group = new GroupProducer(sequence); + const group = track.createGroup(sequence); group.writeFrame({ payload: new TextEncoder().encode("frame"), timestamp: Timestamp.fromMillis(ms) }); group.finish(); - track.writeGroup(group); }; write(0, 0); await opening; @@ -2693,9 +2673,8 @@ test("lite draft-06: a grant that shrinks mid-fetch resets the fetch", async () const broadcast = publish(origin, Path.from("live")); const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); // Left open, so the fetch is still serving when the grant shrinks. - const group = new GroupProducer(0); + const group = track.createGroup(0); group.writeFrame(textFrame("first")); - track.writeGroup(group); const client = await Stream.open(pair.client, { version: Version.DRAFT_06 }); const server = await Stream.accept(pair.server, Version.DRAFT_06); @@ -2731,9 +2710,8 @@ test("lite draft-07: a fetch whose budget gives up partway resets as too old", a const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); const frame = (ms: number) => ({ payload: new TextEncoder().encode("x"), timestamp: Timestamp.fromMillis(ms) }); // Left open, so the fetch is still serving when the track runs on. - const open = new GroupProducer(0); + const open = track.createGroup(0); open.writeFrame(frame(0)); - track.writeGroup(open); const client = await Stream.open(pair.client, { version: Version.DRAFT_07 }); const server = await Stream.accept(pair.server, Version.DRAFT_07); @@ -2752,10 +2730,9 @@ test("lite draft-07: a fetch whose budget gives up partway resets as too old", a // The first frame is on the wire before the track runs a second past its successor. await client.reader.u8(); for (const ms of [1000, 2000]) { - const group = new GroupProducer(ms / 1000); + const group = track.createGroup(ms / 1000); group.writeFrame(frame(ms)); group.finish(); - track.writeGroup(group); } await serving; @@ -2777,10 +2754,9 @@ test.each([0, 1])("lite draft-07 reports the cached largest position when starti const publisher = new Publisher(pair.server, version, randomHop(), origin.consume()); const broadcast = publish(origin, Path.from("quiet")); const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); - const group = new GroupProducer(0); + const group = track.createGroup(0); group.writeFrame(textFrame("cached")); group.finish(); - track.writeGroup(group); const client = await Stream.open(pair.client, { version }); const server = await Stream.accept(pair.server, version); if (!server) throw new Error("missing subscribe stream"); @@ -2822,10 +2798,9 @@ test("lite draft-07 reports the source's largest position past what a relay hold const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); // The source answered with group 4 as its largest; only group 0 has landed. hooks.reportedLargest(track, { group: 4, frame: 0 }); - const group = new GroupProducer(0); + const group = track.createGroup(0); group.writeFrame(textFrame("oldest")); group.finish(); - track.writeGroup(group); const client = await Stream.open(pair.client, { version }); const server = await Stream.accept(pair.server, version); if (!server) throw new Error("missing subscribe stream"); diff --git a/js/net/src/lite/subscriber.ts b/js/net/src/lite/subscriber.ts index aaf2753c419..ad2eadb3a70 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -1663,7 +1663,7 @@ export class Subscriber { } const { track, timescale, tail } = entry; - const producer = new netGroup.Producer(group.sequence); + let producer: netGroup.Producer | undefined; const read = tail.open(group.sequence); try { @@ -1683,7 +1683,7 @@ export class Subscriber { track.abort(violation); throw violation; } - track.writeGroup(producer); + producer = track.createGroup(group.sequence); // Block until the timescale is known; the group's stream can arrive before // TRACK_INFO (or implicit defaults) resolves it on the subscribe stream. @@ -1707,11 +1707,11 @@ export class Subscriber { // A violation ends the session, which the connection does once it escapes; anything // else ends only this group. if (err instanceof ProtocolViolation) { - producer.abort(err); + producer?.abort(err); throw err; } const e = await sessionCause(this.#quic, err); - producer.abort(e); + producer?.abort(e); stream.stop(e); } finally { read(); diff --git a/js/net/src/origin.test.ts b/js/net/src/origin.test.ts index e49cb50cad2..8d0d18706fa 100644 --- a/js/net/src/origin.test.ts +++ b/js/net/src/origin.test.ts @@ -4,7 +4,6 @@ import { announcedView } from "./announced.test-util"; import { type Consumer as BroadcastConsumer, Producer as BroadcastProducer } from "./broadcast.ts"; import * as Epoch from "./epoch.ts"; import { StreamCode, StreamError } from "./error.ts"; -import { Producer as GroupProducer } from "./group.ts"; import { HopSchema, Route } from "./hop.ts"; import { hooks, spreadHash } from "./internal.ts"; import { SessionBroadcast, textFrame } from "./mock.ts"; @@ -2254,7 +2253,7 @@ test("demand held across an epoch change asks again, unless it named the old epo const track = next.createTrack("video"); hooks.acceptRequest((await it.next()).value, next); const subscription = (await unpinned)?.track("video").subscribe(); - track.writeGroup(new GroupProducer(7)); + track.createGroup(7); expect((await subscription?.recvGroup())?.sequence).toBe(7); subscription?.close(); @@ -2302,7 +2301,7 @@ test("demand held across an epoch round trip still asks again", async () => { const track = next.createTrack("video"); hooks.acceptRequest((await it.next()).value, next); const subscription = (await demanded)?.track("video").subscribe(); - track.writeGroup(new GroupProducer(7)); + track.createGroup(7); expect((await subscription?.recvGroup())?.sequence).toBe(7); subscription?.close(); @@ -2467,7 +2466,7 @@ test.each([ expect(fresh.active.peek()?.epoch).toBe(to); const subscription = fresh.active.peek()?.track("video").subscribe(); const forwarded = (await demanded)?.track("video").subscribe(); - nextTrack.writeGroup(new GroupProducer(7)); + nextTrack.createGroup(7); expect((await subscription?.recvGroup())?.sequence).toBe(7); expect((await forwarded?.recvGroup())?.sequence).toBe(7); @@ -2562,7 +2561,7 @@ test("a session's re-request after an epoch update asks the handler again", asyn const track = next.createTrack("video"); hooks.acceptRequest((await requests.next()).value, next); const subscription = (await after)?.track("video").subscribe(); - track.writeGroup(new GroupProducer(7)); + track.createGroup(7); expect((await subscription?.recvGroup())?.sequence).toBe(7); subscription?.close(); @@ -2599,7 +2598,7 @@ test("an update does not override route selection: another claim at the epoch ke expect(held.active.peek()?.epoch).toBe(EPOCH); expect(fresh.active.peek()?.epoch).toBe(EPOCH); const subscription = fresh.active.peek()?.track("video").subscribe(); - track.writeGroup(new GroupProducer(7)); + track.createGroup(7); expect((await subscription?.recvGroup())?.sequence).toBe(7); subscription?.close(); diff --git a/js/net/src/parked-expiry.test.ts b/js/net/src/parked-expiry.test.ts index 427c55d7741..91b66955810 100644 --- a/js/net/src/parked-expiry.test.ts +++ b/js/net/src/parked-expiry.test.ts @@ -1,7 +1,6 @@ import { expect, spyOn, test } from "bun:test"; import { Manual, Milli, Nano } from "@moq/clock"; import { StreamCode } from "./error.ts"; -import { Producer as Group } from "./group.ts"; import { randomHop } from "./hop.ts"; import { NativeSession } from "./ietf/adapter.ts"; import { Publisher as IetfPublisher } from "./ietf/publisher.ts"; @@ -36,10 +35,9 @@ for (const protocol of protocols) { broadcastPublication.announce(); const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); const write = (sequence: number) => { - const group = new Group(sequence); + const group = track.createGroup(sequence); group.writeFrame({ payload: new Uint8Array([1]), timestamp: Timestamp.fromMillis(0) }); group.finish(); - track.writeGroup(group); }; write(0); @@ -160,12 +158,11 @@ for (const protocol of protocols) { broadcastPublication.announce(); const track = broadcast.createTrack("video", { timescale: Timescale.MILLI }); const write = (sequence: number, frames: number) => { - const group = new Group(sequence); + const group = track.createGroup(sequence); for (let frame = 0; frame < frames; frame++) { group.writeFrame({ payload: new Uint8Array([frame]), timestamp: Timestamp.fromMillis(0) }); } group.finish(); - track.writeGroup(group); }; // Two frames, so the second is still unread while the stream's first write waits on credit. diff --git a/js/net/src/resume.test.ts b/js/net/src/resume.test.ts index cb91ff7b195..ace4019787b 100644 --- a/js/net/src/resume.test.ts +++ b/js/net/src/resume.test.ts @@ -51,8 +51,7 @@ function copy(source: BroadcastProducer) { return { producer, write(sequence: number, frames = 1, close = true) { - const group = new GroupProducer(sequence); - producer.writeGroup(group); + const group = producer.createGroup(sequence); for (let frame = 0; frame < frames; frame++) group.writeFrame({ payload: enc.encode(`${sequence}.${frame}`) }); if (close) group.finish(); @@ -349,8 +348,7 @@ test("a lagging same-epoch replica resumes from one publisher's bytes exactly on for (;;) { const group = await input.recvGroup(); if (!group) return; - const copy = new GroupProducer(group.sequence); - output.writeGroup(copy); + const copy = output.createGroup(group.sequence); try { for (let index = 0; ; index++) { const frame = await group.readFrame(); @@ -616,12 +614,10 @@ test("a fetched group continued from an empty, already-closed copy releases that const sub = front.consumer.track("seq").subscribe(); // Group 5 is empty: the first route fails it, the next holds it closed. - const failing = new GroupProducer(5); - a.createTrack("fetch").writeGroup(failing); + const failing = a.createTrack("fetch").createGroup(5); const group = await front.consumer.track("fetch").fetchGroup(5); const read = group.readFrame(); - const whole = new GroupProducer(5); - b.createTrack("fetch").writeGroup(whole); + const whole = b.createTrack("fetch").createGroup(5); whole.finish(); front.serve(b.consume()); await settle(); @@ -660,8 +656,7 @@ test("a fetched group failing as it is handed out releases its route once", asyn expect(drain(sub)).toEqual([0]); const fa = a.createTrack("fetch"); - const failing = new GroupProducer(5); - fa.writeGroup(failing); + const failing = fa.createGroup(5); failing.writeFrame({ payload: enc.encode("5.0") }); const fetching = front.consumer.track("fetch").fetchGroup(5); for (let turn = 0; turn < turns; turn++) await Promise.resolve(); @@ -671,8 +666,7 @@ test("a fetched group failing as it is handed out releases its route once", asyn // The next route holds the fetched group whole; the old one still feeds the reader a // group the new route never has. const fb = b.createTrack("fetch"); - const whole = new GroupProducer(5); - fb.writeGroup(whole); + const whole = fb.createGroup(5); whole.writeFrame({ payload: enc.encode("5.0") }); whole.writeFrame({ payload: enc.encode("5.1") }); whole.finish(); @@ -1258,8 +1252,7 @@ test("a failed group on a route whose replacement was refused ends with the refu b.createTrack("seq", { priority: 2 }); front.serve(a.consume()); const sub = front.consumer.track("seq").subscribe(); - const stalled = new GroupProducer(0); - ta.writeGroup(stalled); + const stalled = ta.createGroup(0); stalled.writeFrame({ payload: enc.encode("0.0") }); const group = sub.tryRecvGroup(); if (!group) throw new Error("expected group 0"); @@ -1377,8 +1370,7 @@ test("a fetch never reads a replacement refused for its track properties", async const b = new BroadcastProducer(); a.createTrack("seq", { priority: 1 }); const tb = b.createTrack("seq", { priority: 2 }); - const group = new GroupProducer(0); - tb.writeGroup(group); + const group = tb.createGroup(0); group.writeFrame({ payload: enc.encode("b") }); group.finish(); front.serve(a.consume()); @@ -1400,8 +1392,7 @@ test("the first fetch of a track says what the track is for later routes", async [b, 2], ] as const) { const producer = source.createTrack("seq", { priority }); - const group = new GroupProducer(0); - producer.writeGroup(group); + const group = producer.createGroup(0); group.writeFrame({ payload: enc.encode(`${priority}`) }); group.finish(); } @@ -1799,8 +1790,7 @@ test("a fetch waits for the copy being read to say what the track is", async () // a answers what the track is only when told to. const requests = wireOf(a).requested(); const tb = b.createTrack("seq", { priority: 2 }); - const group = new GroupProducer(0); - tb.writeGroup(group); + const group = tb.createGroup(0); group.writeFrame({ payload: enc.encode("b") }); group.finish(); front.serve(a.consume()); diff --git a/js/net/src/track.test.ts b/js/net/src/track.test.ts index a00b70088e4..72448a85cd0 100644 --- a/js/net/src/track.test.ts +++ b/js/net/src/track.test.ts @@ -4,7 +4,7 @@ import { race } from "@moq/signals"; import { ProtocolViolation, StreamCode, StreamError, TimestampMismatch, TooFarBehind } from "./error.ts"; import { Decoder } from "./flate/decoder.ts"; import { Encoder } from "./flate/encoder.ts"; -import { type Consumer as GroupConsumer, Producer as GroupProducer, MAX_GROUP_FRAMES } from "./group.ts"; +import { type Consumer as GroupConsumer, type Producer as GroupProducer, MAX_GROUP_FRAMES } from "./group.ts"; import { Version as IetfVersion } from "./ietf/version.ts"; import { hooks } from "./internal.ts"; import { textFrame } from "./mock.ts"; @@ -325,8 +325,8 @@ test("recvDatagram leaves the ordered group cursor alone", async () => { producer.insertDatagram(5, Timestamp.fromMillis(5), enc.encode("x")); expect((await datagrams.recvDatagram())?.sequence).toBe(5); - producer.writeGroup(new GroupProducer(3)); - producer.writeGroup(new GroupProducer(6)); + producer.createGroup(3); + producer.createGroup(6); expect((await track.nextGroup())?.sequence).toBe(3); expect((await track.nextGroup())?.sequence).toBe(6); }); @@ -557,15 +557,15 @@ test("nextGroup skips late arrivals", async () => { const producer = new TrackProducer("test"); const track = producer.subscribe().ordered(); - producer.writeGroup(new GroupProducer(5)); + producer.createGroup(5); const first = await track.nextGroup(); expect(first?.sequence).toBe(5); // Late arrivals with sequence <= last returned are skipped. - producer.writeGroup(new GroupProducer(3)); - producer.writeGroup(new GroupProducer(4)); - producer.writeGroup(new GroupProducer(7)); + producer.createGroup(3); + producer.createGroup(4); + producer.createGroup(7); const next = await track.nextGroup(); expect(next?.sequence).toBe(7); @@ -575,8 +575,8 @@ test("nextGroup returns buffered groups in sequence", async () => { const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); - producer.writeGroup(new GroupProducer(3)); - producer.writeGroup(new GroupProducer(5)); + producer.createGroup(3); + producer.createGroup(5); expect((await track.nextGroup())?.sequence).toBe(3); expect((await track.nextGroup())?.sequence).toBe(5); @@ -627,7 +627,7 @@ test("the ordered handle carries datagrams", async () => { const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); producer.insertDatagram(5, Timestamp.fromMillis(5), enc.encode("x")); - producer.writeGroup(new GroupProducer(3)); + producer.createGroup(3); expect((await track.recvDatagram())?.sequence).toBe(5); // The datagram did not consume the group cursor. @@ -683,10 +683,9 @@ test("a late-arriving successor bounds a group's reach", async () => { [2, 3000], [1, 200], ]) { - const group = new GroupProducer(sequence); + const group = producer.createGroup(sequence); group.writeFrame({ payload: enc.encode(`${ms}`), timestamp: Timestamp.fromMillis(ms) }); group.finish(); - producer.writeGroup(group); } // Group 0 reaches at most 200ms, where group 1 starts, so it is past the budget. @@ -721,21 +720,18 @@ for (const take of ["nextGroup", "tryNextGroup"] as const) { const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); - const zero = new GroupProducer(0); + const zero = producer.createGroup(0); zero.writeFrame(textFrame("0.0")); zero.writeFrame(textFrame("0.1")); zero.finish(); - producer.writeGroup(zero); - const one = new GroupProducer(1); + const one = producer.createGroup(1); one.writeFrame(textFrame("1.0")); one.finish(); - producer.writeGroup(one); - const two = new GroupProducer(2); + const two = producer.createGroup(2); two.writeFrame(textFrame("2.0")); two.finish(); - producer.writeGroup(two); // The frame path enters group 0; a direct take then claims group 1. expect((await track.readFrame())?.group).toBe(0); @@ -754,21 +750,18 @@ test("ordered frame reads skip a late lower-sequence group", async () => { const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); - const five = new GroupProducer(5); + const five = producer.createGroup(5); five.writeFrame(textFrame("five", Timestamp.fromMillis(5))); five.finish(); - producer.writeGroup(five); expect(await track.readString()).toBe("five"); - const three = new GroupProducer(3); + const three = producer.createGroup(3); three.writeFrame(textFrame("three", Timestamp.fromMillis(3))); three.finish(); - producer.writeGroup(three); - const six = new GroupProducer(6); + const six = producer.createGroup(6); six.writeFrame(textFrame("six", Timestamp.fromMillis(6))); six.finish(); - producer.writeGroup(six); expect(await track.readString()).toBe("six"); }); @@ -808,8 +801,7 @@ test("a late lower group within the budget is delivered", async () => { [6, 2000], [7, 3000], ]) { - const group = new GroupProducer(sequence); - producer.writeGroup(group); + const group = producer.createGroup(sequence); group.writeFrame({ payload: enc.encode(`${timestamp}`), timestamp: Timestamp.fromMillis(timestamp) }); group.finish(); } @@ -822,8 +814,7 @@ test("a late lower group within the budget is delivered", async () => { // Arriving below everything already delivered is not what makes content stale: the // budget is the only gate, and this straggler's timestamp is within it. A consumer // that needs sequence order reorders (or drops) it itself. - const late = new GroupProducer(4); - producer.writeGroup(late); + const late = producer.createGroup(4); late.writeFrame({ payload: enc.encode("late"), timestamp: Timestamp.fromMillis(500) }); late.finish(); @@ -1178,32 +1169,6 @@ test("frozen timestamps still age out by wall clock", () => { } }); -// Arrival is per track: a group joining a second track later doesn't restart the first -// track's clock. -test("a group shared by two tracks ages each from its own arrival", () => { - const clock = manualTime(10_000); - const first = new TrackProducer("first").accept({}); - const second = new TrackProducer("second").accept({}); - try { - first.writeFrame({ payload: enc.encode("0") }); - const shared = new GroupProducer(1); - shared.writeFrame({ payload: enc.encode("1") }); - shared.finish(); - first.writeGroup(shared); - clock.set(11_000); - second.writeGroup(shared); - - // Group 0's successor joined the first track a full budget ago. - expect(drain(first.subscribe({ maxDelay: Milli(1000) }))).toEqual([1]); - } finally { - first.finish(); - first.close(); - second.finish(); - second.close(); - clock.installed.close(); - } -}); - // Groups that arrive at once are judged by media time, which convicts them before the wall // clock can. test("a startup burst ages out by media time", () => { @@ -1381,10 +1346,9 @@ test("a live track retains its newest closed group through idle expiry", async ( try { // A late older group must not replace the protected newest snapshot. for (const sequence of [2, 1]) { - const group = new GroupProducer(sequence); + const group = producer.createGroup(sequence); group.writeFrame({ payload: enc.encode("snapshot"), timestamp: Timestamp.fromMillis(0) }); group.finish(); - producer.writeGroup(group); } await clock.advance(10_000 + CACHE_WINDOW_MS + 200); const replay = producer.subscribe({ maxDelay: Milli(100) }); @@ -1613,16 +1577,14 @@ test("latency budget retains a consumed live-edge anchor", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); const track = producer.subscribe(); - const edge = new GroupProducer(2); + const edge = producer.createGroup(2); edge.writeFrame({ payload: enc.encode("edge"), timestamp: Timestamp.fromMillis(2000) }); edge.finish(); - producer.writeGroup(edge); expect((await track.recvGroup())?.sequence).toBe(2); - const late = new GroupProducer(1); + const late = producer.createGroup(1); late.writeFrame({ payload: enc.encode("late"), timestamp: Timestamp.fromMillis(0) }); late.finish(); - producer.writeGroup(late); producer.finish(); producer.close(); @@ -1633,15 +1595,13 @@ test("an aborted live-edge anchor does not make older content stale", async () = const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(5000) }); const track = producer.subscribe(); - const edge = new GroupProducer(2); + const edge = producer.createGroup(2); edge.writeFrame({ payload: enc.encode("edge"), timestamp: Timestamp.fromMillis(2000) }); edge.abort(new Error("aborted")); - producer.writeGroup(edge); - const older = new GroupProducer(1); + const older = producer.createGroup(1); older.writeFrame({ payload: enc.encode("older"), timestamp: Timestamp.fromMillis(0) }); older.finish(); - producer.writeGroup(older); expect((await track.recvGroup())?.sequence).toBe(1); track.close(); @@ -1657,7 +1617,7 @@ test.each(["arrival", "ordered"] as const)("subscription bounds stay reader-loca const ordered = order === "ordered" ? subscriber.ordered() : undefined; const read = () => (ordered ? ordered.nextGroup() : subscriber.recvGroup()); try { - for (let sequence = 0; sequence < 5; sequence++) producer.writeGroup(new GroupProducer(sequence)); + for (let sequence = 0; sequence < 5; sequence++) producer.createGroup(sequence); expect((await everything.recvGroup())?.sequence).toBe(0); expect((await read())?.sequence).toBe(1); expect((await read())?.sequence).toBe(2); @@ -1687,7 +1647,7 @@ test("subscription updates narrow the cursor before its first read", async () => const everything = producer.subscribe({ maxDelay: Milli(5000) }); const track = producer.subscribe({ maxDelay: Milli(5000) }); try { - for (let sequence = 0; sequence < 5; sequence++) producer.writeGroup(new GroupProducer(sequence)); + for (let sequence = 0; sequence < 5; sequence++) producer.createGroup(sequence); track.update({ maxDelay: Milli(5000), groups: { start: { excluded: 2 }, end: { included: 3 } } }); expect((await track.recvGroup())?.sequence).toBe(3); const pending = track.recvGroup(); @@ -1754,7 +1714,7 @@ test("withRange with an excluded end of 0 is the empty range and does not ride a const empty = producer.subscribe({ maxDelay: Milli(5000), groups: { end: { excluded: 0 } } }); empty.withRange({ end: { excluded: 0 } }); - for (let sequence = 0; sequence < 3; sequence++) producer.writeGroup(new GroupProducer(sequence)); + for (let sequence = 0; sequence < 3; sequence++) producer.createGroup(sequence); expect((await everything.recvGroup())?.sequence).toBe(0); const pending = empty.recvGroup(); @@ -1811,7 +1771,7 @@ test("local cursor bounds can skip, pause, and release buffered groups", async ( const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); - for (let sequence = 0; sequence < 5; sequence++) producer.writeGroup(new GroupProducer(sequence)); + for (let sequence = 0; sequence < 5; sequence++) producer.createGroup(sequence); track.withRange({ start: { included: 1 }, end: { excluded: 3 } }); expect((await track.nextGroup())?.sequence).toBe(1); @@ -1831,11 +1791,11 @@ test("recvGroup serves a late arrival after a newer group", async () => { const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000) }); - producer.writeGroup(new GroupProducer(2)); + producer.createGroup(2); expect((await track.recvGroup())?.sequence).toBe(2); // Group 1 lands after group 2 was already served. - producer.writeGroup(new GroupProducer(1)); + producer.createGroup(1); expect((await track.recvGroup())?.sequence).toBe(1); // Staleness is the latency window's job, not arrival order's: the track @@ -1851,7 +1811,7 @@ test("withRange parks recvGroup beyond the cap and a raised cap re-offers", asyn const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000) }); - for (let sequence = 0; sequence < 3; sequence++) producer.writeGroup(new GroupProducer(sequence)); + for (let sequence = 0; sequence < 3; sequence++) producer.createGroup(sequence); track.withRange({ end: { excluded: 2 } }); expect((await track.recvGroup())?.sequence).toBe(0); @@ -1881,9 +1841,9 @@ test("recvGroup serves in-range groups that arrive behind a capped one", async ( track.withRange({ end: { excluded: 2 } }); // Reordered burst: the beyond-cap group arrives first. - producer.writeGroup(new GroupProducer(2)); - producer.writeGroup(new GroupProducer(0)); - producer.writeGroup(new GroupProducer(1)); + producer.createGroup(2); + producer.createGroup(0); + producer.createGroup(1); expect((await track.recvGroup())?.sequence).toBe(0); expect((await track.recvGroup())?.sequence).toBe(1); @@ -1902,42 +1862,39 @@ test("withRange drops groups recvGroup parked at the cap", async () => { const track = producer.subscribe(); track.withRange({ end: { excluded: 1 } }); - producer.writeGroup(new GroupProducer(1)); + producer.createGroup(1); const pending = track.recvGroup(); expect(await Promise.race([pending, Promise.resolve("pending")])).toBe("pending"); track.withRange({ start: { included: 2 } }); - producer.writeGroup(new GroupProducer(2)); + producer.createGroup(2); // The overtaken parked group is dropped, not re-offered. expect((await pending)?.sequence).toBe(2); }); // A live duplicate would fan out to every subscriber twice (recvGroup has no sequence -// cursor to hide it), so writeGroup rejects it like Rust's claim_sequence. An aborted +// cursor to hide it), so createGroup rejects it like Rust's claim_sequence. An aborted // incarnation is evicted so a fresh group can serve the sequence again. -test("writeGroup rejects a duplicate live sequence", async () => { +test("createGroup rejects a duplicate live sequence", async () => { const producer = new TrackProducer("test"); const track = producer.subscribe(); - const first = new GroupProducer(7); + const first = producer.createGroup(7); first.writeFrame(textFrame("first")); first.finish(); - producer.writeGroup(first); // A peer re-sending a live sequence is rejected, not fanned out again. - expect(() => producer.writeGroup(new GroupProducer(7))).toThrow("duplicate group"); + expect(() => producer.createGroup(7)).toThrow("duplicate group"); expect((await track.recvGroup())?.sequence).toBe(7); // An aborted incarnation is replaceable: the retry serves the sequence fresh. - const aborted = new GroupProducer(8); - producer.writeGroup(aborted); + const aborted = producer.createGroup(8); aborted.abort(new Error("upstream reset")); - const retry = new GroupProducer(8); + const retry = producer.createGroup(8); retry.writeFrame(textFrame("retry")); retry.finish(); - producer.writeGroup(retry); const got = await track.recvGroup(); expect(got?.sequence).toBe(8); @@ -1952,7 +1909,7 @@ test("closing the subscriber releases a recvGroup parked after a clean close", a const track = producer.subscribe(); track.withRange({ end: { excluded: 1 } }); - producer.writeGroup(new GroupProducer(1)); + producer.createGroup(1); const pending = track.recvGroup(); expect(await Promise.race([pending, Promise.resolve("pending")])).toBe("pending"); @@ -1970,7 +1927,7 @@ test("closing the subscriber releases a recvGroup parked while the producer is l const track = producer.subscribe(); track.withRange({ end: { excluded: 1 } }); - producer.writeGroup(new GroupProducer(1)); + producer.createGroup(1); const pending = track.recvGroup(); expect(await Promise.race([pending, Promise.resolve("pending")])).toBe("pending"); @@ -1984,12 +1941,12 @@ test("the ordered and arrival cursors are independent", async () => { const ordered = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); const arrival = producer.subscribe({ maxDelay: Milli(5000) }); - producer.writeGroup(new GroupProducer(5)); + producer.createGroup(5); expect((await ordered.nextGroup())?.sequence).toBe(5); // A late seq 3 is skipped by the ordered cursor, which has already passed it, but the // arrival cursor has both buffered and still delivers each exactly once. - producer.writeGroup(new GroupProducer(3)); + producer.createGroup(3); expect((await arrival.recvGroup())?.sequence).toBe(3); expect((await arrival.recvGroup())?.sequence).toBe(5); }); @@ -2001,13 +1958,13 @@ test("the first group read commits the cursor and refuses the other order", asyn // An arrival read commits to arrival order; ordered() is refused afterwards. const arrival = producer.subscribe({ maxDelay: Milli(5000) }); - producer.writeGroup(new GroupProducer(5)); + producer.createGroup(5); expect((await arrival.recvGroup())?.sequence).toBe(5); expect(() => arrival.ordered()).toThrow("arrival order"); // The commitment refuses the other cursor without poisoning this one: a late // lower sequence still flows in arrival order. - producer.writeGroup(new GroupProducer(3)); + producer.createGroup(3); expect((await arrival.recvGroup())?.sequence).toBe(3); // The other direction: ordered() takes the subscription and arrival reads throw. @@ -2030,7 +1987,7 @@ test("recvDatagram does not commit the group cursor", async () => { // Still uncommitted: the subscription can go sequence-ordered. const ordered = track.ordered(); - producer.writeGroup(new GroupProducer(1)); + producer.createGroup(1); expect((await ordered.nextGroup())?.sequence).toBe(1); }); @@ -2050,10 +2007,9 @@ test("a closed track still delivers a group parked above the cap once the cap is const track = producer.subscribe({ maxDelay: Milli(5000) }).ordered(); for (let sequence = 0; sequence < 3; sequence++) { - const group = new GroupProducer(sequence); + const group = producer.createGroup(sequence); group.writeFrame(textFrame(`frame-${sequence}`)); group.finish(); - producer.writeGroup(group); } track.withRange({ end: { excluded: 2 } }); @@ -2085,7 +2041,7 @@ test("end reports the head after the highest produced sequence, datagrams includ const track = producer.subscribe(); expect(hooks.subscriberEnd(track)).toBeUndefined(); - producer.writeGroup(new GroupProducer(0)); + producer.createGroup(0); producer.appendDatagram(Timestamp.fromMillis(1), enc.encode("x")); producer.finish(); producer.close(); @@ -2200,12 +2156,10 @@ test("a late group below the largest changes nothing", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI }); const subscriber = producer.subscribe(); - const framed = new GroupProducer(2); - producer.writeGroup(framed); + const framed = producer.createGroup(2); framed.writeFrame({ payload: enc.encode("a"), timestamp: Timestamp.now() }); framed.finish(); - const empty = new GroupProducer(5); - producer.writeGroup(empty); + const empty = producer.createGroup(5); empty.finish(); producer.finishAt({ group: 6, frame: 0 }); @@ -2213,8 +2167,7 @@ test("a late group below the largest changes nothing", async () => { expect(await subscriber.largest()).toBeUndefined(); // Late content below the end is still admitted; it just isn't the largest. - const late = new GroupProducer(4); - producer.writeGroup(late); + const late = producer.createGroup(4); late.writeFrame({ payload: enc.encode("b"), timestamp: Timestamp.now() }); expect(await subscriber.largest()).toBeUndefined(); expect(await producer.subscribe().largest()).toEqual({ group: 5, frame: 0 }); @@ -2229,8 +2182,7 @@ test("a recreated largest group is reported before the end", async () => { const subscriber = producer.subscribe(); // The recreated group carries the same content, timestamps included. const timestamp = Timestamp.now(); - const first = new GroupProducer(0); - producer.writeGroup(first); + const first = producer.createGroup(0); first.writeFrame({ payload: enc.encode("a"), timestamp }); first.abort(new Error("cut")); producer.finishAt({ group: 1, frame: 0 }); @@ -2244,8 +2196,7 @@ test("a recreated largest group is reported before the end", async () => { await settle(); expect(advanced).toBe(false); - const again = new GroupProducer(0); - producer.writeGroup(again); + const again = producer.createGroup(0); for (const payload of ["a", "b"]) again.writeFrame({ payload: enc.encode(payload), timestamp }); expect(await next).toEqual({ group: 0, frame: 1 }); again.finish(); @@ -2266,8 +2217,7 @@ test("a datagram raises the largest", async () => { /** Write untimed group `sequence` with `frames` frames, left open. */ function framedGroup(producer: TrackProducer, sequence: number, frames: number): GroupProducer { - const group = new GroupProducer(sequence); - producer.writeGroup(group); + const group = producer.createGroup(sequence); for (let i = 0; i < frames; i++) group.writeFrame({ payload: enc.encode("x") }); return group; } @@ -2403,7 +2353,7 @@ test("group ranges preserve progress and spell out inclusion", async () => { const track = producer .subscribe({ maxDelay: Milli(5000) }) .withRange({ start: { included: 1 }, end: { included: 1 } }); - for (let sequence = 0; sequence < 4; sequence++) producer.writeGroup(new GroupProducer(sequence)); + for (let sequence = 0; sequence < 4; sequence++) producer.createGroup(sequence); expect(track.tryRecvGroup()?.sequence).toBe(1); expect(track.tryRecvGroup()).toBeUndefined(); track.withRange({ start: { included: 1 }, end: { excluded: 3 } }); @@ -2418,7 +2368,7 @@ test("group ranges preserve progress and spell out inclusion", async () => { test("a lowered range re-offers the unread cached groups", () => { const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000), groups: { start: { included: 10 } } }); - for (const sequence of [5, 6, 10]) producer.writeGroup(new GroupProducer(sequence)); + for (const sequence of [5, 6, 10]) producer.createGroup(sequence); expect(track.tryRecvGroup()?.sequence).toBe(10); expect(track.tryRecvGroup()).toBeUndefined(); @@ -2428,7 +2378,7 @@ test("a lowered range re-offers the unread cached groups", () => { expect(track.tryRecvGroup()?.sequence).toBe(5); track.withRange({}); expect(track.tryRecvGroup()).toBeUndefined(); - producer.writeGroup(new GroupProducer(11)); + producer.createGroup(11); expect(track.tryRecvGroup()?.sequence).toBe(11); track.close(); }); @@ -2436,11 +2386,10 @@ test("a lowered range re-offers the unread cached groups", () => { test("a lowered range re-offers a cached cut with its error", async () => { const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000), groups: { start: { included: 1 } } }); - const cut = new GroupProducer(0); - producer.writeGroup(cut); + const cut = producer.createGroup(0); const error = new StreamError(StreamCode(70), { message: "cut" }); cut.abort(error); - producer.writeGroup(new GroupProducer(1)); + producer.createGroup(1); expect(track.tryRecvGroup()?.sequence).toBe(1); track.withRange({}); @@ -2455,7 +2404,7 @@ test("a lowered range re-offers a cached cut with its error", async () => { test("a lowered range still re-offers after the producer closes", () => { const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000), groups: { start: { included: 1 } } }); - for (const sequence of [0, 1]) producer.writeGroup(new GroupProducer(sequence)); + for (const sequence of [0, 1]) producer.createGroup(sequence); expect(track.tryRecvGroup()?.sequence).toBe(1); producer.finish(); producer.close(); @@ -2470,7 +2419,7 @@ for (const abort of [undefined, new Error("gone")]) { test(`a lowered range offers nothing to a reader that ${abort ? "aborted" : "closed"}`, () => { const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000), groups: { start: { included: 1 } } }); - for (const sequence of [0, 1]) producer.writeGroup(new GroupProducer(sequence)); + for (const sequence of [0, 1]) producer.createGroup(sequence); expect(track.tryRecvGroup()?.sequence).toBe(1); track.close(abort); @@ -2484,7 +2433,7 @@ for (const abort of [undefined, new Error("gone")]) { test("malformed group bounds do not partially advance the cursor", () => { const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(5000) }); - producer.writeGroup(new GroupProducer(0)); + producer.createGroup(0); expect(() => track.withRange({ start: { included: 3 }, end: { excluded: -1 } })).toThrow(); expect(track.tryRecvGroup()?.sequence).toBe(0); track.close(); @@ -2492,7 +2441,7 @@ test("malformed group bounds do not partially advance the cursor", () => { test("finishAt refuses an end at or below a produced sequence", () => { const producer = new TrackProducer("test"); - producer.writeGroup(new GroupProducer(5)); + producer.createGroup(5); // Exclusive, so it must be above the highest produced sequence. expect(() => producer.finishAt({ group: 5, frame: 0 })).toThrow(); @@ -2501,7 +2450,7 @@ test("finishAt refuses an end at or below a produced sequence", () => { // A second end is refused, as is any group at or past the first. expect(() => producer.finishAt({ group: 7, frame: 0 })).toThrow(); - expect(() => producer.writeGroup(new GroupProducer(6))).toThrow(); + expect(() => producer.createGroup(6)).toThrow(); expect(() => producer.appendGroup()).toThrow(); expect(() => producer.insertDatagram(6, Timestamp.now(), new Uint8Array(1))).toThrow(); producer.finish(); @@ -2511,7 +2460,7 @@ test("finishAt refuses an end at or below a produced sequence", () => { test("finishAt declares an end ahead of the live edge without ending the track", async () => { const producer = new TrackProducer("test"); const track = producer.subscribe({ maxDelay: Milli(60_000) }); - producer.writeGroup(new GroupProducer(5)); + producer.createGroup(5); const first = await track.recvGroup(); expect(first?.sequence).toBe(5); @@ -2520,12 +2469,10 @@ test("finishAt declares an end ahead of the live edge without ending the track", expect(await track.finished()).toEqual({ group: 8, frame: 0 }); // Not terminal: groups below the end still arrive, including a straggler. - const late = new GroupProducer(7); + const late = producer.createGroup(7); late.finish(); - producer.writeGroup(late); - const straggler = new GroupProducer(6); + const straggler = producer.createGroup(6); straggler.finish(); - producer.writeGroup(straggler); expect((await track.recvGroup())?.sequence).toBe(6); expect((await track.recvGroup())?.sequence).toBe(7); @@ -2548,9 +2495,8 @@ for (const ordered of [false, true]) { try { producer.finishAt({ group: 3, frame: 0 }); const waiting = receive(); - const group = new GroupProducer(2); + const group = producer.createGroup(2); group.writeFrame(textFrame("tail")); - producer.writeGroup(group); const received = await waiting; expect(received?.sequence).toBe(2); expect(await received?.readString()).toBe("tail"); @@ -2589,9 +2535,8 @@ for (const channel of ["group", "datagram"]) { const groupRead = track.recvGroup(); const datagramRead = track.recvDatagram(); if (channel === "group") { - const group = new GroupProducer(2); + const group = producer.createGroup(2); group.finish(); - producer.writeGroup(group); } else { producer.insertDatagram(2, Timestamp.fromMillis(0), enc.encode("tail")); } @@ -2797,14 +2742,13 @@ test("an abort after the declared end reached by a datagram ends clean", () => { test("a settled end survives a late group and an abort", async () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI }); const subscriber = producer.subscribe(); - const last = new GroupProducer(5); - producer.writeGroup(last); + const last = producer.createGroup(5); last.finish(); producer.finishAt({ group: 6, frame: 0 }); await settle(); expect(producer.closed.peek()).toBeNull(); - producer.writeGroup(new GroupProducer(4)); + producer.createGroup(4); producer.abort(new Error("boom")); expect(producer.closed.peek()).toBeNull(); expect((await subscriber.recvGroup())?.sequence).toBe(5); @@ -2967,23 +2911,6 @@ test("a frame whose timedness disagrees with its track is refused", async () => expect(frame?.timestamp).toBeUndefined(); }); -test("a group joining a track it disagrees with is refused", () => { - const producer = new TrackProducer("test").accept({}); - const group = new GroupProducer(0); - group.writeFrame({ payload: enc.encode("x"), timestamp: Timestamp.fromMillis(1) }); - expect(() => producer.writeGroup(group)).toThrow(TimestampMismatch); -}); - -test("an empty group bound to a timed track can't join an untimed one", () => { - const timed = new TrackProducer("timed").accept({ timescale: Timescale.MILLI }); - const untimed = new TrackProducer("untimed").accept({}); - const group = timed.appendGroup(); - expect(() => untimed.writeGroup(group)).toThrow(TimestampMismatch); - // Still held to the timed track it was bound to first. - expect(() => group.writeFrame({ payload: enc.encode("x") })).toThrow(TimestampMismatch); - group.writeFrame({ payload: enc.encode("x"), timestamp: Timestamp.fromMillis(1) }); -}); - test("a datagram whose timedness disagrees with its track is refused", async () => { const timed = new TrackProducer("timed").accept({ timescale: Timescale.MILLI }); expect(() => timed.appendDatagram(undefined, enc.encode("x"))).toThrow(TimestampMismatch); @@ -3101,8 +3028,7 @@ test("explicit and producer-cut drops survive outside the group cache", async () hooks.dropTrackGroups(producer, 3, 4, DROPPED); expect(hooks.tryRecvGroup(reader, true)).toEqual({ kind: "drop", start: 3, end: 4, error: DROPPED }); - const group = new GroupProducer(4); - producer.writeGroup(group); + const group = producer.createGroup(4); const cut = new Error("cut"); group.abort(cut); await settle(); @@ -3124,8 +3050,7 @@ test("a group ended by a cancel or cache policy is a hole, not a drop", async () new TooFarBehind(), ]; for (const [sequence, hole] of holes.entries()) { - const group = new GroupProducer(sequence); - producer.writeGroup(group); + const group = producer.createGroup(sequence); group.abort(hole); } await settle(); @@ -3139,11 +3064,9 @@ test("a group ended by a cancel or cache policy is a hole, not a drop", async () test("an upstream drop ends a group still arriving with its error", async () => { const producer = new TrackProducer("video").accept({}); const reader = producer.subscribe({ maxDelay: Milli(60_000) }); - const arriving = new GroupProducer(3); - producer.writeGroup(arriving); + const arriving = producer.createGroup(3); arriving.writeFrame({ payload: enc.encode("3") }); - const finished = new GroupProducer(4); - producer.writeGroup(finished); + const finished = producer.createGroup(4); finished.writeFrame({ payload: enc.encode("4") }); finished.finish(); @@ -3180,13 +3103,11 @@ test("a drop below the window is reported once the window lowers to it", () => { test("a re-created cut group is served, not dropped", async () => { const producer = new TrackProducer("video").accept({}); const reader = producer.subscribe({ maxDelay: Milli(60_000) }); - const cut = new GroupProducer(4); - producer.writeGroup(cut); + const cut = producer.createGroup(4); cut.abort(new Error("cut")); await settle(); - const retry = new GroupProducer(4); - producer.writeGroup(retry); + producer.createGroup(4); await settle(); const recv = hooks.tryRecvGroup(reader, true); expect(recv.kind === "group" ? recv.group.sequence : recv).toBe(4); @@ -3245,8 +3166,7 @@ test("a mid-group end survives eviction and a filtered late reader", async () => const producer = new TrackProducer("video").accept({}); try { producer.finishAt({ group: 5, frame: 5 }); - const group = new GroupProducer(5); - producer.writeGroup(group); + const group = producer.createGroup(5); for (let i = 0; i < 5; i++) group.writeFrame({ payload: new Uint8Array([i]) }); group.finish(); producer.finish(); @@ -3287,8 +3207,7 @@ test("a wire end repeats or refines but never moves", () => { // end says does not exist. test("a mid-group end refuses to cut existing frames", () => { const producer = new TrackProducer("video").accept({}); - const group = new GroupProducer(5); - producer.writeGroup(group); + const group = producer.createGroup(5); for (let i = 0; i < 6; i++) group.writeFrame({ payload: new Uint8Array([i]) }); expect(() => producer.finishAt({ group: 5, frame: 5 })).toThrow(ProtocolViolation); expect(hooks.subscriberEnd(producer.subscribe())).toBeUndefined(); @@ -3302,19 +3221,13 @@ test.each([true, false])("a mid-group end caps later writes (declared first: %s) const producer = new TrackProducer("video").accept({}); const end = { group: 5, frame: 2 }; if (early) producer.finishAt(end); - const group = new GroupProducer(5); + const group = producer.createGroup(5); group.writeFrame({ payload: new Uint8Array([0]) }); - producer.writeGroup(group); if (!early) producer.finishAt(end); group.writeFrame({ payload: new Uint8Array([1]) }); expect(() => group.writeFrame({ payload: new Uint8Array([2]) })).toThrow("past the track's end"); expect(group.consume().frameCount).toBe(2); - expect(() => producer.writeGroup(new GroupProducer(6))).toThrow(); - // A group handed over already past the end is refused before it is cached. - const overfull = new GroupProducer(5); - for (let i = 0; i < 3; i++) overfull.writeFrame({ payload: new Uint8Array([i]) }); - group.abort(new Error("replaced")); - expect(() => producer.writeGroup(overfull)).toThrow(ProtocolViolation); + expect(() => producer.createGroup(6)).toThrow(); producer.finish(); producer.close(); }); @@ -3322,8 +3235,7 @@ test.each([true, false])("a mid-group end caps later writes (declared first: %s) // A closed group `sequence` written into `producer` whose one frame starts at `ms`, aborted // as ingest does when that frame is refused. function stampGroup(producer: TrackProducer, sequence: number, ms: number): GroupProducer { - const group = new GroupProducer(sequence); - producer.writeGroup(group); + const group = producer.createGroup(sequence); try { group.writeFrame({ payload: enc.encode(`${ms}`), timestamp: Timestamp.fromMillis(ms) }); } catch (err) { @@ -3345,8 +3257,7 @@ test("a re-created group is handed out once", () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI, maxAge: Milli(30_000) }); const subscriber = producer.subscribe({ maxDelay: Milli(30_000) }); stampGroup(producer, 0, 0); - const aborted = new GroupProducer(1); - producer.writeGroup(aborted); + const aborted = producer.createGroup(1); expect(drainGroups(subscriber)).toEqual([0, 1]); aborted.abort(new Error("aborted")); @@ -3451,14 +3362,12 @@ test("a rewind is refused whichever group lands first", () => { // that start as the watermark, and no later group can start before it. test("a replaced aborted group still bounds later ones", () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI }); - const first = new GroupProducer(0); - producer.writeGroup(first); + const first = producer.createGroup(0); first.writeFrame({ payload: enc.encode("1000"), timestamp: Timestamp.fromMillis(1000) }); first.abort(new Error("aborted")); - const replacement = new GroupProducer(0); + const replacement = producer.createGroup(0); replacement.writeFrame({ payload: enc.encode("500"), timestamp: Timestamp.fromMillis(500) }); - producer.writeGroup(replacement); replacement.finish(); expect(() => stampGroup(producer, 1, 600)).toThrow(TimestampMismatch); stampGroup(producer, 1, 1000); @@ -3481,12 +3390,13 @@ test("a rewind across large timescales is refused", () => { ).toThrow(TimestampMismatch); }); -test("a group stamped before it is written is checked on write", () => { +test("a group's first frame is checked against the group below it", () => { const producer = new TrackProducer("test").accept({ timescale: Timescale.MILLI }); stampGroup(producer, 1, 6000); - const group = new GroupProducer(2); - group.writeFrame({ payload: enc.encode("early"), timestamp: Timestamp.fromMillis(5000) }); - expect(() => producer.writeGroup(group)).toThrow(TimestampMismatch); + const group = producer.createGroup(2); + expect(() => group.writeFrame({ payload: enc.encode("early"), timestamp: Timestamp.fromMillis(5000) })).toThrow( + TimestampMismatch, + ); }); test("an evicted group still bounds, and a late group below it is unverified", async () => { @@ -3532,8 +3442,7 @@ test("an evicted group still bounds, and a late group below it is unverified", a test("an untimed track takes groups in any order", () => { const producer = new TrackProducer("test").accept({}); for (const sequence of [5, 3, 4]) { - const group = new GroupProducer(sequence); - producer.writeGroup(group); + const group = producer.createGroup(sequence); group.writeFrame({ payload: enc.encode(`${sequence}`) }); group.finish(); } @@ -3547,9 +3456,8 @@ function pendingTail(end: number, maxDelay = Milli(60_000)) { hooks.startTrack(producer, { start: 0 }); hooks.endTrack(producer, { group: end, frame: 0 }); const write = (sequence: number) => { - const group = new GroupProducer(sequence); + const group = producer.createGroup(sequence); group.finish(); - producer.writeGroup(group); }; return { producer, reader, write }; } @@ -3566,21 +3474,21 @@ async function settled(read: Promise): Promise { } // The end arrives after a higher group did, with lower ones still owed: it must not settle. -test("a received end behind a hole settles only once the hole fills", () => { +test("a received end behind a hole settles only once the hole fills", async () => { const producer = new TrackProducer("test"); const reader = producer.subscribe({ maxDelay: Milli(60_000) }); hooks.startTrack(producer, { start: 0 }); - const late = new GroupProducer(2); + const late = producer.createGroup(2); late.finish(); - producer.writeGroup(late); hooks.endTrack(producer, { group: 3, frame: 0 }); + await settle(); expect(producer.closed.peek()).toBeUndefined(); for (const sequence of [0, 1]) { - const group = new GroupProducer(sequence); + const group = producer.createGroup(sequence); group.finish(); - producer.writeGroup(group); } + await settle(); expect(producer.closed.peek()).toBeNull(); reader.close(); }); @@ -3622,9 +3530,8 @@ test("without a declared start, the first arrival stands in for it", async () => const producer = new TrackProducer("test"); const reader = producer.subscribe({ maxDelay: Milli(60_000) }); hooks.endTrack(producer, { group: 3, frame: 0 }); - const group = new GroupProducer(2); + const group = producer.createGroup(2); group.finish(); - producer.writeGroup(group); expect((await reader.recvGroup())?.sequence).toBe(2); expect(await reader.recvGroup()).toBeUndefined(); producer.finish(); @@ -3665,9 +3572,8 @@ test("a pending tail owes from SUBSCRIBE_START while the demand keeps its floor" const reader = producer.subscribe({ maxDelay: Milli(60_000), groups: { start: { included: 1 } } }); hooks.startTrack(producer, { start: 3, requested: 1 }); hooks.endTrack(producer, { group: 4, frame: 0 }); - const group = new GroupProducer(3); + const group = producer.createGroup(3); group.finish(); - producer.writeGroup(group); expect((await reader.recvGroup())?.sequence).toBe(3); expect(await reader.recvGroup()).toBeUndefined(); @@ -3685,18 +3591,16 @@ test("an end after the highest group holds the reader at the hole", async () => const producer = new TrackProducer("test"); const reader = producer.subscribe({ maxDelay: Milli(60_000) }); hooks.startTrack(producer, { start: 0 }); - const high = new GroupProducer(2); + const high = producer.createGroup(2); high.finish(); - producer.writeGroup(high); expect((await reader.recvGroup())?.sequence).toBe(2); const next = reader.recvGroup(); hooks.endTrack(producer, { group: 3, frame: 0 }); expect(await settled(next)).toBe(false); for (const sequence of [0, 1]) { - const low = new GroupProducer(sequence); + const low = producer.createGroup(sequence); low.finish(); - producer.writeGroup(low); } expect((await next)?.sequence).toBe(0); expect((await reader.recvGroup())?.sequence).toBe(1); diff --git a/js/net/src/track.ts b/js/net/src/track.ts index 530af000e97..ab9b5af33c3 100644 --- a/js/net/src/track.ts +++ b/js/net/src/track.ts @@ -1294,10 +1294,9 @@ export class Producer { this.#pruneTimerAt = at; } - // Retain a source group and fan it out to every live sink. A group that already holds - // frame 0 passes its checked `start` and whether it is `late`; any other checks frame 0 + // Retain a source group and fan it out to every live sink; its frame 0 is checked // against this track when it lands. - #publish(group: GroupProducer, start?: Timestamp, late = false): void { + #publish(group: GroupProducer): void { this.#settle(); const entry: CachedGroup = { group, mirrors: new Map(), arrived: now() }; this.#undrop(group.sequence); @@ -1311,8 +1310,6 @@ export class Producer { const sequence = group.sequence; if (this.#unchecked()) { // Its timestamps may rewind, so they are not checked. - } else if (start) { - this.#record(entry, start, late); } else { hooks.admitGroupStart(group, (start) => { const late = this.#admit(sequence, start); @@ -1397,7 +1394,7 @@ export class Producer { * * The broadcast remembers nothing of an earlier producer of the name, so a replacement * starts at 0. Since a name always means the same content, a replacement continues past - * its predecessor's groups with {@link writeGroup}. + * its predecessor's groups with {@link createGroup}. * * Its frames must match the track's {@link Info.timescale}: a timestamp on every frame of * a timed track and none on an untimed one, or the write throws {@link TimestampMismatch}. @@ -1413,35 +1410,31 @@ export class Producer { } /** - * Insert an existing group into the track. + * Create a new group with the given sequence number. * * Throws on a sequence that is still cached: a live duplicate would fan out to every * subscriber twice. An aborted incarnation is evicted so a fresh group can serve the * sequence again. Best effort (mirrors Rust): nothing remembers a sequence whose cache - * entry is already gone, so a long-evicted sequence is accepted as new. Throws - * {@link TimestampMismatch} if the group already holds a frame whose timedness - * disagrees with the track's {@link Info.timescale}, or whose first frame starts before - * the group below it or after the one above it. + * entry is already gone, so a long-evicted sequence is accepted as new. Its frames are + * checked like {@link appendGroup}'s. */ - writeGroup(group: GroupProducer) { - this.#writable(group.sequence); - this.#bind(group); - this.#cap(group); - const existing = this.#cached.get(group.sequence); + createGroup(sequence: number): GroupProducer { + this.#writable(sequence); + const existing = this.#cached.get(sequence); if (existing) { if (!(existing.group.closed.peek() instanceof Error)) { - throw new Error(`duplicate group: sequence=${group.sequence}`); + throw new Error(`duplicate group: sequence=${sequence}`); } // Subscribers may have seen the aborted incarnation's start, so it stays a watermark. this.#evict(existing); this.#uncache(existing, true); } - // A group written before it joined is checked here, before it is cached or fanned out. - const start = this.#unchecked() ? undefined : hooks.groupStart(group); - const late = start !== undefined && this.#admit(group.sequence, start); - - this.#publish(group, start, late); + const group = new GroupProducer(sequence); + this.#bind(group); + this.#cap(group); + this.#publish(group); + return group; } // Whether this track's timestamps may rewind (see {@link Info.ietf}). diff --git a/js/publish/src/element.ts b/js/publish/src/element.ts index 29fbdf596e2..f02e774fcc2 100644 --- a/js/publish/src/element.ts +++ b/js/publish/src/element.ts @@ -230,7 +230,7 @@ export default class MoqPublish extends HTMLElement { broadcast: this.broadcast, capture: this.#capture, enabled: this.#videoEnabled, - bandwidth: this.connection.bandwidth, + bandwidth: this.connection.allocator, }); this.signals.cleanup(() => this.video.close()); @@ -238,7 +238,7 @@ export default class MoqPublish extends HTMLElement { broadcast: this.broadcast, enabled: this.#audioEnabled, capture: audioCapture, - bandwidth: this.connection.bandwidth, + bandwidth: this.connection.allocator, }); this.signals.cleanup(() => this.audio.close()); diff --git a/js/publish/src/video/encoder.ts b/js/publish/src/video/encoder.ts index 1b5f2faebfd..22fb12cb899 100644 --- a/js/publish/src/video/encoder.ts +++ b/js/publish/src/video/encoder.ts @@ -700,7 +700,7 @@ export class Encoder { const reservation = effect.get(this.#reservation); if (reservation) { const grant = reservation.peek(); - effect.get(reservation.grant); + effect.get(reservation.rate); if (grant != null) bitrate = Math.min(bitrate, grant); } diff --git a/js/room/src/local.test.ts b/js/room/src/local.test.ts index 63325dce7fe..77d609cbd8b 100644 --- a/js/room/src/local.test.ts +++ b/js/room/src/local.test.ts @@ -40,7 +40,7 @@ test("screen capture stays enabled while pending and resets after a live share e const local = new Local({ connection: { origin: new Signal(undefined), - bandwidth, + allocator: bandwidth, } as never, identity: Path.from("alice"), }); diff --git a/js/room/src/local.ts b/js/room/src/local.ts index ccfe047598f..aea6db869a0 100644 --- a/js/room/src/local.ts +++ b/js/room/src/local.ts @@ -102,7 +102,7 @@ export class Local { this.user = userFields(props.user); const origin = props.connection.origin; - const bandwidth = props.connection.bandwidth; + const bandwidth = props.connection.allocator; this.webcam = new Publish.Source.Camera({ enabled: this.cameraEnabled, diff --git a/js/watch/src/audio/decoder.test.ts b/js/watch/src/audio/decoder.test.ts index ab2df5e2c88..49f72ccd810 100644 --- a/js/watch/src/audio/decoder.test.ts +++ b/js/watch/src/audio/decoder.test.ts @@ -964,10 +964,9 @@ async function livePlayback(burst: number) { held.push(frame * FRAME); if (held.length < burst) continue; for (const timestamp of held) { - const group = new Moq.Group.Producer(sequence++); + const group = track.createGroup(sequence++); group.writeFrame(legacyFrame(Micro.fromMilli(Milli(timestamp)))); group.finish(); - track.writeGroup(group); } held = []; } diff --git a/js/watch/src/audio/playout.test.ts b/js/watch/src/audio/playout.test.ts index 5ee4387f408..2623442105c 100644 --- a/js/watch/src/audio/playout.test.ts +++ b/js/watch/src/audio/playout.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, spyOn } from "bun:test"; import { Micro, Milli } from "@moq/clock"; import * as Container from "@moq/hang/container"; -import { Group, Time, Track, Varint } from "@moq/net"; +import { Time, Track, Varint } from "@moq/net"; import { AUTO_MAX_DELAY, target } from "./latency"; import { AudioRingBuffer } from "./ring-buffer"; @@ -98,10 +98,9 @@ async function measure(t: Arrival[], budget: (target: Milli) => Milli): Promise< clock = t[next].arrival; for (; next < t.length && t[next].arrival === clock; next++) { const media = Micro.fromMilli(t[next].media as Milli); - const group = new Group.Producer(next); + const group = track.createGroup(next); group.writeFrame({ payload: encode(media), timestamp: Time.Timestamp.fromMicros(media) }); group.finish(); - track.writeGroup(group); } // A macrotask boundary, so the group readers have observed everything written above. diff --git a/js/watch/src/audio/replay.ts b/js/watch/src/audio/replay.ts index d164695f3a1..bc1123ad79a 100644 --- a/js/watch/src/audio/replay.ts +++ b/js/watch/src/audio/replay.ts @@ -19,7 +19,7 @@ import { Manual, type Micro, Milli, Nano, type Second } from "@moq/clock"; import type * as Catalog from "@moq/hang/catalog"; import * as Container from "@moq/hang/container"; -import { Group, Time, Track } from "@moq/net"; +import { type Group, Time, Track } from "@moq/net"; import { Effect, Signal } from "@moq/signals"; import { type Arrival as Diagnostic, gap } from "../arrivals"; import { type Delay, Sync } from "../sync"; @@ -236,9 +236,8 @@ export async function* replay(trace: Arrival[], options: Options): AsyncGenerato } let group = groups.get(arrival.group); if (!group) { - group = new Group.Producer(arrival.group); + group = track.createGroup(arrival.group); groups.set(arrival.group, group); - track.writeGroup(group); } const timestamp = micros(arrival.timestamp); group.writeFrame({ diff --git a/js/watch/src/video/decoder.test.ts b/js/watch/src/video/decoder.test.ts index 0618cff1547..ed93899e50e 100644 --- a/js/watch/src/video/decoder.test.ts +++ b/js/watch/src/video/decoder.test.ts @@ -900,10 +900,9 @@ function liveVideo(clock: ReturnType, track: Moq.Track.Producer held.push(frame * FRAME); if (held.length < this.burst) continue; for (const media of held) { - const group = new Moq.Group.Producer(sequence++); + const group = track.createGroup(sequence++); group.writeFrame(legacyFrame(Micro.fromMilli(Milli(media)))); group.finish(); - track.writeGroup(group); } held = []; } @@ -1017,9 +1016,8 @@ it("a video track read from another path does not inherit the outgoing delay", a it("buffered video holds its poster until its own span reaches the floor", async () => { const clock = manualAt(0); const playback = await guardedPlayback("legacy", [], [], true, 1000); - const group = new Moq.Group.Producer(0); if (!playback.track) throw new Error("missing video track"); - playback.track.writeGroup(group); + const group = playback.track.createGroup(0); try { group.writeFrame(legacyFrame(Micro(0))); group.writeFrame(legacyFrame(Micro(40_000))); diff --git a/kt/moq/MIGRATE.md b/kt/moq/MIGRATE.md index d6372846093..747ce1a5343 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 +### `Allocator` ([#6751](https://github.com/moq-dev/moq/pull/6751)) + +`Bandwidth` is `Allocator`, `bandwidth()` is `allocator()`, and `Reservation.grant()` is `rate()`. The producers' `bandwidth` option keeps its name. + ### Decoders read gaps and ends `dev.moq.audio.Consumer.next()` and `dev.moq.video.Consumer.next()` return a `Read` instead of a frame, and their `frames()` flows become `reads()`. Take `(read as? ReadFrame)?.frame` where you used the frame; `ReadGap` marks lost media and `ReadEnd` where the publisher stopped its encoder, and what follows either does not continue what came before. diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index acfe9167017..7ad1b9f750e 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -150,10 +150,10 @@ typealias VideoEncoderOutput = uniffi.moq.MoqVideoEncoderOutput /** Which encoder implementation to use: automatic, hardware, software, or one named backend. */ typealias VideoEncoderKind = uniffi.moq.MoqVideoEncoderKind /** Divides one connection's send estimate among the tracks sharing it. */ -typealias Bandwidth = uniffi.moq.MoqBandwidth +typealias Allocator = uniffi.moq.MoqAllocator /** An owned bandwidth estimate; release it to stop receive PROBE demand. */ typealias BandwidthConsumer = uniffi.moq.MoqBandwidthConsumer -/** One track's standing claim on a [Bandwidth]. */ +/** One track's standing claim on an [Allocator]. */ typealias Reservation = uniffi.moq.MoqReservation /** A snapshot of transport connection statistics. */ typealias ConnectionStats = uniffi.moq.MoqConnectionStats diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt index f2e4fe1c8e6..98b3f114505 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt @@ -54,11 +54,11 @@ class Moq internal constructor( /** * The session's bandwidth allocator. * - * Every call returns a handle to the same registry. [Bandwidth.reserve] a + * Every call returns a handle to the same registry. [Allocator.reserve] a * share for an app-owned encoder, or pass the handle to an audio or video * producer. */ - fun bandwidth(): Bandwidth = session.bandwidth() + fun allocator(): Allocator = session.allocator() /** * Follow the grant the peer gave this session. diff --git a/py/moq-rs/MIGRATE.md b/py/moq-rs/MIGRATE.md index 615ba80caaa..1340c48bad7 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 +### `Allocator` ([#6751](https://github.com/moq-dev/moq/pull/6751)) + +`moq.Bandwidth` is `moq.Allocator`, `Session.bandwidth()` is `allocator()`, and `Reservation.grant()` is `rate()`. `Bandwidth.Consumer`, returned by `recv_bandwidth()`, is the top-level `moq.BandwidthConsumer`. The producers' `bandwidth=` argument keeps its name. + ### Decoders read gaps and ends `audio.Consumer` yields `audio.Read` (`audio.Frame | audio.Gap | audio.End`) and `video.Consumer` yields `video.Read` (`VideoDecodedFrame | video.Gap | video.End`). Check `isinstance(read, audio.Frame)` (or `VideoDecodedFrame`) where you used each item as a frame; a `Gap` marks lost media and an `End` where the publisher stopped its encoder, and what follows either does not continue what came before. diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index cfc6ee312c2..7755e3b4eaa 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -158,7 +158,7 @@ client = moq.Client( - `.publish() → OriginProducer`, `.consume() → OriginConsumer`. The wired origin sides. - `.stats() → ConnectionStats`. Snapshot RTT, bandwidth estimates, and byte/packet counters. - `.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. + - `.allocator() → Allocator`. Divide the send estimate between encoders and app-owned tracks. - `.grants() → GrantConsumer`. On `moq-lite-07-wip` and on moq-transport draft-17+ with the MoQ Auth extension, `.grant()` reads the peer's `Grant` and `async for grant in session.grants()` follows it. - `.tokens() → Tokens | None`. A client session's credentials: `.set([...])` replaces them without reconnecting and `await .answered()` raises the relay's refusal. diff --git a/py/moq-rs/moq/__init__.py b/py/moq-rs/moq/__init__.py index d44c9beb711..239fc062969 100644 --- a/py/moq-rs/moq/__init__.py +++ b/py/moq-rs/moq/__init__.py @@ -41,7 +41,7 @@ TrackRequest, ) from .server import Request, Server, Transport -from .session import Bandwidth, GrantConsumer, Reservation, Session, Tokens +from .session import Allocator, BandwidthConsumer, GrantConsumer, Reservation, Session, Tokens from .subscribe import ( BroadcastConsumer, GroupConsumer, @@ -81,6 +81,7 @@ ) __all__ = [ + "Allocator", "Anchor", "Announce", "AnnounceConsumer", @@ -95,7 +96,7 @@ "AudioEncoderInput", "AudioSampleFormat", "Backoff", - "Bandwidth", + "BandwidthConsumer", "BroadcastConsumer", "BroadcastDynamic", "BroadcastPrepared", diff --git a/py/moq-rs/moq/audio.py b/py/moq-rs/moq/audio.py index decf78c9ccb..9e397de044b 100644 --- a/py/moq-rs/moq/audio.py +++ b/py/moq-rs/moq/audio.py @@ -23,7 +23,7 @@ from ._stream import _Stream from .media import Audio, AudioInit, CatalogProducer from .publish import TrackDemand -from .session import Bandwidth, Reservation +from .session import Allocator, Reservation from .subscribe import BroadcastConsumer from .types import AudioCodec as Codec from .types import AudioEncoderInput as EncoderInput @@ -118,7 +118,7 @@ def __init__( output: EncoderOutput, *, track: str | None = None, - bandwidth: Bandwidth | None = None, + bandwidth: Allocator | None = None, ) -> None: """Open an audio track on the catalog's broadcast and register its rendition.""" self._inner = MoqAudioProducer( diff --git a/py/moq-rs/moq/session.py b/py/moq-rs/moq/session.py index 576cef4ec10..33619e8ff04 100644 --- a/py/moq-rs/moq/session.py +++ b/py/moq-rs/moq/session.py @@ -5,7 +5,7 @@ from collections.abc import Sequence from moq_ffi import ( - MoqBandwidth, + MoqAllocator, MoqBandwidthConsumer, MoqGrantConsumer, MoqReservation, @@ -116,12 +116,12 @@ def tokens(self) -> Tokens | None: inner = self._inner.tokens() return None if inner is None else Tokens(inner) - def recv_bandwidth(self) -> Bandwidth.Consumer | None: + def recv_bandwidth(self) -> BandwidthConsumer | None: """Hold an owned receive-estimate consumer; releasing the last one stops PROBE.""" inner = self._inner.recv_bandwidth() - return None if inner is None else Bandwidth.Consumer(inner) + return None if inner is None else BandwidthConsumer(inner) - def bandwidth(self) -> Bandwidth: + def allocator(self) -> Allocator: """The session's bandwidth allocator. Every call returns a handle to the same registry, so reservations made @@ -129,7 +129,7 @@ def bandwidth(self) -> Bandwidth: reconnects: the grant is ``None`` while disconnected and resumes on the next connection. """ - return Bandwidth(self._inner.bandwidth()) + return Allocator(self._inner.allocator()) class GrantConsumer: @@ -213,31 +213,32 @@ async def answered(self) -> None: await self._inner.answered() -class Bandwidth: - """Divides one connection's send estimate among the tracks sharing it. +class BandwidthConsumer: + """An owned bandwidth estimate, in bits per second, returned by :meth:`Session.recv_bandwidth`.""" - Minted by :meth:`Session.bandwidth`. Clones share one reservation registry. - """ + def __init__(self, inner: MoqBandwidthConsumer) -> None: + self._inner = inner + + def rate(self) -> int | None: + """The current estimate, or None while unavailable.""" + return self._inner.rate() - class Consumer: - """An owned bandwidth estimate, in bits per second.""" + async def rate_changed(self) -> int | None: + """Wait for the estimate to change and return the new rate, raising when its producer closes.""" + return await self._inner.rate_changed() - def __init__(self, inner: MoqBandwidthConsumer) -> None: - self._inner = inner + def cancel(self) -> None: + """Release this consumer's demand, including a pending wait.""" + self._inner.cancel() - def rate(self) -> int | None: - """The current estimate, or None while unavailable.""" - return self._inner.rate() - async def rate_changed(self) -> int | None: - """Wait for the estimate to change and return the new rate, raising when its producer closes.""" - return await self._inner.rate_changed() +class Allocator: + """Divides one connection's send estimate among the tracks sharing it. - def cancel(self) -> None: - """Release this consumer's demand, including a pending wait.""" - self._inner.cancel() + Minted by :meth:`Session.allocator`. Clones share one reservation registry. + """ - def __init__(self, inner: MoqBandwidth) -> None: + def __init__(self, inner: MoqAllocator) -> None: self._inner = inner def reserve(self, demand: TrackDemand, max_bps: int) -> Reservation: @@ -251,19 +252,19 @@ def reserve(self, demand: TrackDemand, max_bps: int) -> Reservation: class Reservation: - """One track's standing claim on a :class:`Bandwidth`. + """One track's standing claim on an :class:`Allocator`. - :meth:`grant` is a snapshot: ``None`` means no estimate, so hold the - current rate, and ``0`` is a real zero grant. While nothing subscribes it + :meth:`rate` is a snapshot: ``None`` means no estimate, so hold the + current rate, and ``0`` is a real zero rate. While nothing subscribes it is the share the track would get. """ def __init__(self, inner: MoqReservation) -> None: self._inner = inner - def grant(self) -> int | None: + def rate(self) -> int | None: """This reservation's slice right now, in bits per second.""" - return self._inner.grant() + return self._inner.rate() def update(self, max_bps: int) -> None: """Change the ceiling, keeping the same claim.""" diff --git a/py/moq-rs/moq/video.py b/py/moq-rs/moq/video.py index 9689b0371d0..7b821d52a6d 100644 --- a/py/moq-rs/moq/video.py +++ b/py/moq-rs/moq/video.py @@ -23,7 +23,7 @@ from ._stream import _Stream from .media import CatalogProducer, Dimensions, Video from .publish import TrackDemand -from .session import Bandwidth, Reservation +from .session import Allocator, Reservation from .subscribe import BroadcastConsumer from .types import VideoCodec as Codec from .types import VideoDecodedFrame @@ -92,7 +92,7 @@ def __init__( output: EncoderOutput, *, track: str | None = None, - bandwidth: Bandwidth | None = None, + bandwidth: Allocator | None = None, lower: Producer | None = None, ) -> None: """Open a video track on the catalog's broadcast and register its rendition. diff --git a/quest/m1/api-audit/README.md b/quest/m1/api-audit/README.md index 756f4710d42..ff9a774268a 100644 --- a/quest/m1/api-audit/README.md +++ b/quest/m1/api-audit/README.md @@ -78,7 +78,6 @@ Rejected in planning: - [Binding publications](/quest/m1/api-audit/binding-publication.md) - moq-ffi, the C ABI, and every wrapper hand out a publication handle that announces, replacing the private adapters - [Encoded consumers read gaps and ends](/quest/m1/api-audit/encoded-read-bindings.md) - moq-ffi, moq-c, and every wrapper read encoded media with the tagged-record shape the decoded consumers use - [One lifecycle vocabulary in @moq/e2ee](/quest/m1/api-audit/lifecycle.md) - @moq/e2ee ends tracks and groups with finish and abort, as @moq/net does -- [moq-net names say one thing](/quest/m1/api-audit/net-names.md) - demand says `wanted`, colliding stats and transport names are renamed, and Rust and JS info lookups mirror - [Request handlers are named requests](/quest/m1/api-audit/requests.md) - `dynamic()` and `Dynamic` become `requests()` and `Requests` at every layer - [Demand is wanted, everywhere](/quest/m1/api-audit/wanted.md) - every `used`/`unused` pair becomes `wanted()` and `wanted_changed()`, and unused ones go - [One meaning for Credential](/quest/m1/api-audit/dial-credential.md) - the internal dial type gets its own name in JS and moq-tokio, and the `Presented` alias goes diff --git a/quest/m1/api-audit/net-names.md b/quest/m1/api-audit/net-names.md deleted file mode 100644 index 51603569645..00000000000 --- a/quest/m1/api-audit/net-names.md +++ /dev/null @@ -1,45 +0,0 @@ -# [L] moq-net names say one thing - -## Goal - -moq-net and `@moq/net` names don't collide with other items, don't describe -the wrong shape, and mirror each other. Each rename reaches the bindings and -docs that expose it. - -## Plan - -Decided 2026-10-23 (API audit follow-up, maintainer): - -- **Demand says `wanted`.** `group::Demand` drops - `is_used`/`used`/`unused`/`poll_used`/`poll_unused` for `track::Demand`'s - `wanted()` snapshot plus `wanted_changed()` (and its poll). - `broadcast::Demand` is already deleted. -- **Allocator.** `Session::bandwidth()` returns the send allocator beside - `send_bandwidth()`/`recv_bandwidth()` estimates: rename it `allocator()`, and - `Client::with_bandwidth` `with_allocator`. -- **Stats and transport collisions.** `stats::Control` (vs `track::Control`) - becomes `stats::Message`; `stats::Bytes` (vs `bytes::Bytes`) becomes - `stats::Totals`; the trait `transport::Stats` (vs `session::Stats` and the - `stats` module) becomes `transport::Metrics`. -- **Wire owns bytes.** `transport::Metrics` drops `bytes_sent` and - `bytes_received`: `transport::Wire` already counts them, and - `session::Stats` reads them from it. `StatsUnavailable` goes; the trait - method gets a default. -- **Credential.** `auth::Auth` (JS `Auth.Auth`) is one presented credential: - `auth::Credential` in Rust, JS, and the FFI. -- **Info.** `track::Consumer::query() -> Pending` becomes - `info() -> Pending`, mirroring JS `Track.Consumer.info()`. - `Pending` stays generic over the task so poll callers and `track()` keep - working; awaiting it still yields `Result`. -- **Reservation.** `bandwidth::Reservation::consumer()` becomes `consume()`; - JS `Reservation.grant` (vs `Auth.Grant`) becomes `rate`, as the bindings - name it. -- **JS groups.** `Track.Producer.writeGroup` becomes `createGroup`, Rust's name. - -Kept, so the next audit skips them: `largest()` stays a snapshot on -`track::Producer` and a stream on readers, and `subscription()` stays the -aggregate on producers and requests: the receiver type tells them apart. -`server::Activity` and `stats::RefusalKind` stay in moq-net. - -Public API: moq-net, `@moq/net`, moq-tokio, moq-ffi and its wrappers renamed. -Wire: none. diff --git a/quest/m1/api-audit/wanted.md b/quest/m1/api-audit/wanted.md index e0c4d573bd2..9cc828e03b9 100644 --- a/quest/m1/api-audit/wanted.md +++ b/quest/m1/api-audit/wanted.md @@ -10,8 +10,8 @@ instead of renamed. ## Plan -Decided 2026-10-25 (maintainer), extending -[moq-net names](/quest/m1/api-audit/net-names.md)'s "Demand says `wanted`": +Decided 2026-10-25 (maintainer), extending the `wanted` shape that +[#6751](https://github.com/moq-dev/moq/pull/6751) gave `group::Demand`: - Yes/no demand returns `bool`; `track::Demand::wanted() -> Option` keeps its meaning. @@ -20,9 +20,7 @@ Decided 2026-10-25 (maintainer), extending `Broadcast.Demand` (read only by tests and a bench) goes too. The origin closes a superseded producer explicitly instead of a publisher watching demand. -- `group::Demand` has no production consumer in Rust; delete it rather than - convert it, unless net-names lands the conversion first. The JS group - demand stays internal. +- `group::Demand` already says `wanted`. The JS group demand stays internal. - `bandwidth::Producer` gets a `demand()` handle with `wanted() -> bool` and `wanted_changed()`, like track. - `track::Fill` merges `is_used()` and `next()` into @@ -43,5 +41,4 @@ Public API: breaking renames and deletions in every language. Wire: none. ## Required -- [moq-net names say one thing](/quest/m1/api-audit/net-names.md) - lands group demand's first `wanted` shape - [One lifecycle vocabulary](/quest/m1/api-audit/lifecycle.md) - settles close and demand semantics this renames diff --git a/rs/moq-archive/src/consumer/tests.rs b/rs/moq-archive/src/consumer/tests.rs index 63707ff281d..505ad2ad613 100644 --- a/rs/moq-archive/src/consumer/tests.rs +++ b/rs/moq-archive/src/consumer/tests.rs @@ -220,7 +220,7 @@ async fn a_recording_round_trips() { let (broadcast, _run) = serve(&store).await; let served = broadcast.consume().track("video").unwrap(); - let info = served.query().await.unwrap(); + let info = served.info().await.unwrap(); assert_eq!(info.priority, 3); assert_eq!(info.timescale, Some(Timescale::MILLI)); assert_eq!(info.max_age, None); @@ -240,7 +240,7 @@ async fn a_recording_round_trips() { assert_eq!(reader.finished().await.unwrap(), Position::group(6)); // The untimed track keeps its datagram a datagram. - let info = broadcast.consume().track("log").unwrap().query().await.unwrap(); + let info = broadcast.consume().track("log").unwrap().info().await.unwrap(); assert_eq!((info.priority, info.timescale), (9, None)); assert_eq!(fetch(&broadcast, "log", 0).await.unwrap(), ["a"]); assert!(matches!( @@ -431,7 +431,7 @@ async fn a_growing_archive_is_followed() { assert_eq!(next(&mut b).await.unwrap(), (51, expected(true, 51, 0..2))); assert!(matches!( - broadcast.consume().track("c").unwrap().query().await, + broadcast.consume().track("c").unwrap().info().await, Err(moq_net::Error::NotFound) )); archive.track("c", 0, false).await; diff --git a/rs/moq-c/MIGRATE.md b/rs/moq-c/MIGRATE.md index 6d1b1632012..b2a27577807 100644 --- a/rs/moq-c/MIGRATE.md +++ b/rs/moq-c/MIGRATE.md @@ -4,11 +4,15 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Session allocator ([#6751](https://github.com/moq-dev/moq/pull/6751)) + +`moq_session_bandwidth` is `moq_session_allocator`, `moq_bandwidth_reserve` is `moq_allocator_reserve`, and `moq_bandwidth_close` is `moq_allocator_close`, matching `moq_net::bandwidth::Allocator`. `moq_reservation_grant` is `moq_reservation_rate`, matching `moq_net::bandwidth::Reservation::rate()`. Signatures are unchanged. The receive estimate keeps its names (`moq_session_recv_bandwidth`, `moq_bandwidth_consumer_*`). + ### `moq_encode_video` takes a `moq_video_encode_options` `moq_encode_video`'s fourth argument is a `const moq_video_encode_options *` instead of a `uint32_t bandwidth`: pass `NULL` where you passed `0`, or `&(moq_video_encode_options){.bandwidth = bandwidth}`. Its `lower` field takes the handle of the next lower rendition's encoder, to disable this one while its bandwidth grant cannot fund it; that needs a `bandwidth` and a bitrate above the lower encoder's. -`moq_reservation_grant` reports the slice the track would get back while nothing subscribes to it, instead of no grant. +`moq_reservation_rate` reports the slice the track would get back while nothing subscribes to it, instead of no grant. ### Decoders deliver reads diff --git a/rs/moq-c/README.md b/rs/moq-c/README.md index a9d616eb56a..3c0e691e569 100644 --- a/rs/moq-c/README.md +++ b/rs/moq-c/README.md @@ -33,10 +33,10 @@ int32_t moq_log_level(const char *level, uintptr_t level_len); 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); -int32_t moq_bandwidth_reserve(uint32_t bandwidth, uint32_t track, uint64_t max_bps); -int32_t moq_bandwidth_close(uint32_t bandwidth); -int32_t moq_reservation_grant(uint32_t reservation, uint64_t *bps, bool *present); +int32_t moq_session_allocator(uint32_t session); +int32_t moq_allocator_reserve(uint32_t allocator, uint32_t track, uint64_t max_bps); +int32_t moq_allocator_close(uint32_t allocator); +int32_t moq_reservation_rate(uint32_t reservation, uint64_t *bps, bool *present); int32_t moq_reservation_update(uint32_t reservation, uint64_t max_bps); int32_t moq_reservation_close(uint32_t reservation); diff --git a/rs/moq-c/src/audio.rs b/rs/moq-c/src/audio.rs index 7bcdfab4fc9..0e6dad0265f 100644 --- a/rs/moq-c/src/audio.rs +++ b/rs/moq-c/src/audio.rs @@ -362,7 +362,7 @@ impl Audio { /// - `name` must point to `name_len` bytes of UTF-8. /// - `input` / `output` must point to fully populated structs. /// - `output->codec` must point to `output->codec_len` bytes of UTF-8. -/// - `bandwidth` is a handle from [`crate::moq_session_bandwidth`], or 0 to leave the +/// - `allocator` is a handle from [`crate::moq_session_allocator`], or 0 to leave the /// configured bitrate unclaimed. #[unsafe(no_mangle)] pub unsafe extern "C" fn moq_encode_audio( @@ -371,7 +371,7 @@ pub unsafe extern "C" fn moq_encode_audio( name_len: usize, input: *const moq_audio_encoder_input, output: *const moq_audio_encoder_output, - bandwidth: u32, + allocator: u32, ) -> i32 { ffi::enter(move || { let broadcast = ffi::parse_id(broadcast)?; @@ -403,13 +403,13 @@ pub unsafe extern "C" fn moq_encode_audio( options.config.frame_duration = Duration::from_micros(micros.into()); } - let bandwidth = ffi::parse_id_optional(bandwidth)?; + let allocator = ffi::parse_id_optional(allocator)?; let mut state = State::lock(); - if let Some(id) = bandwidth { + if let Some(id) = allocator { options.bandwidth = state.bandwidth.allocator(id)?; } let State { publish, audio, .. } = &mut *state; - audio.publish(publish.target(broadcast)?, encoder_input, options, bandwidth.is_some()) + audio.publish(publish.target(broadcast)?, encoder_input, options, allocator.is_some()) }) } diff --git a/rs/moq-c/src/bandwidth.rs b/rs/moq-c/src/bandwidth.rs index 7d120605ab9..36ad3239642 100644 --- a/rs/moq-c/src/bandwidth.rs +++ b/rs/moq-c/src/bandwidth.rs @@ -51,22 +51,22 @@ impl Bandwidth { /// /// Returns a non-zero handle, or a negative error if the session is unknown. #[unsafe(no_mangle)] -pub extern "C" fn moq_session_bandwidth(session: u32) -> i32 { +pub extern "C" fn moq_session_allocator(session: u32) -> i32 { ffi::enter(move || { let session = ffi::parse_id(session)?; let mut state = State::lock(); - let allocator = state.session.bandwidth(session)?; + let allocator = state.session.allocator(session)?; state.bandwidth.insert(allocator) }) } -/// Release a bandwidth handle. Reservations taken against it stay until they +/// Release an allocator handle. Reservations taken against it stay until they /// themselves are closed (or the session's allocator is gone). #[unsafe(no_mangle)] -pub extern "C" fn moq_bandwidth_close(bandwidth: u32) -> i32 { +pub extern "C" fn moq_allocator_close(allocator: u32) -> i32 { ffi::enter(move || { - let bandwidth = ffi::parse_id(bandwidth)?; - State::lock().bandwidth.close(bandwidth) + let allocator = ffi::parse_id(allocator)?; + State::lock().bandwidth.close(allocator) }) } @@ -76,31 +76,31 @@ pub extern "C" fn moq_bandwidth_close(bandwidth: u32) -> i32 { /// ever send. Drop the reservation with [`moq_reservation_close`] to hand the /// room back. #[unsafe(no_mangle)] -pub extern "C" fn moq_bandwidth_reserve(bandwidth: u32, track: u32, max_bps: u64) -> i32 { +pub extern "C" fn moq_allocator_reserve(allocator: u32, track: u32, max_bps: u64) -> i32 { ffi::enter(move || { - let bandwidth = ffi::parse_id(bandwidth)?; + let allocator = ffi::parse_id(allocator)?; let track = ffi::parse_id(track)?; let mut state = State::lock(); let demand = state.publish.track_demand(track)?; - state.bandwidth.reserve(bandwidth, &demand, max_bps) + state.bandwidth.reserve(allocator, &demand, max_bps) }) } /// This reservation's slice right now, in bits per second. /// /// `present` is false when there is no estimate: hold the current rate. `present` -/// true and `bps` 0 is a real zero grant. While nothing subscribes to the track, +/// true and `bps` 0 is a real zero rate. While nothing subscribes to the track, /// `bps` is the slice it would get back, without claiming it from the others. /// /// # Safety /// - `bps` and `present` must be valid pointers. #[unsafe(no_mangle)] -pub unsafe extern "C" fn moq_reservation_grant(reservation: u32, bps: *mut u64, present: *mut bool) -> i32 { +pub unsafe extern "C" fn moq_reservation_rate(reservation: u32, bps: *mut u64, present: *mut bool) -> i32 { ffi::enter(move || { let reservation = ffi::parse_id(reservation)?; let bps = unsafe { bps.as_mut() }.ok_or(Error::InvalidPointer)?; let present = unsafe { present.as_mut() }.ok_or(Error::InvalidPointer)?; - match State::lock().bandwidth.reservation(reservation)?.peek() { + match State::lock().bandwidth.reservation(reservation)?.rate() { Some(rate) => { *bps = rate.as_bps(); *present = true; diff --git a/rs/moq-c/src/session.rs b/rs/moq-c/src/session.rs index 56118ff82c1..7841b8552e7 100644 --- a/rs/moq-c/src/session.rs +++ b/rs/moq-c/src/session.rs @@ -287,10 +287,10 @@ impl Session { /// which the session probes for. /// /// Errors with [`Error::Offline`] for an accepted session still in SETUP. - pub fn bandwidth(&self, id: Id) -> Result { + pub fn allocator(&self, id: Id) -> Result { match self.link(id)? { - Link::Dialed { connection, .. } => Ok(connection.bandwidth()), - Link::Accepted(accepted) => Ok(accepted.as_ref().ok_or(Error::Offline)?.session.bandwidth()), + Link::Dialed { connection, .. } => Ok(connection.allocator()), + Link::Accepted(accepted) => Ok(accepted.as_ref().ok_or(Error::Offline)?.session.allocator()), } } diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index 94b901fa2d4..a60a47b61dc 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -5747,25 +5747,25 @@ fn test_allocator() -> (u32, moq_net::bandwidth::Producer) { (bandwidth, estimate) } -fn grant(reservation: u32) -> Option { +fn rate(reservation: u32) -> Option { let mut bps = 0; let mut present = false; - assert_eq!(unsafe { moq_reservation_grant(reservation, &mut bps, &mut present) }, 0); + assert_eq!(unsafe { moq_reservation_rate(reservation, &mut bps, &mut present) }, 0); present.then_some(bps) } /// Wait for `reservation`'s grant to reach `bps`, since a subscription reaches the /// allocator asynchronously and an unwatched track already reads a would-be share. -fn wait_grant(reservation: u32, bps: u64) { +fn wait_rate(reservation: u32, bps: u64) { let deadline = std::time::Instant::now() + TIMEOUT; loop { - let last = grant(reservation); + let last = rate(reservation); if last == Some(bps) { return; } assert!( std::time::Instant::now() < deadline, - "timed out waiting for a {bps} bps grant, last {last:?}" + "timed out waiting for a {bps} bps rate, last {last:?}" ); std::thread::sleep(Duration::from_millis(10)); } @@ -5804,25 +5804,25 @@ fn bandwidth_reservations_split_the_estimate() { let (first_sub, first_cb) = subscribe_named_track(consume, b"a"); let (second_sub, second_cb) = subscribe_named_track(consume, b"b"); - let first = id(moq_bandwidth_reserve(bandwidth, first_track, 4_000_000)); - let second = id(moq_bandwidth_reserve(bandwidth, second_track, 2_000_000)); + let first = id(moq_allocator_reserve(bandwidth, first_track, 4_000_000)); + let second = id(moq_allocator_reserve(bandwidth, second_track, 2_000_000)); estimate .set(Some(moq_net::bandwidth::Rate::from_bps(3_000_000))) .unwrap(); - wait_grant(first, 1_500_000); - wait_grant(second, 1_500_000); - let a = grant(first).expect("first grant"); - let b = grant(second).expect("second grant"); + wait_rate(first, 1_500_000); + wait_rate(second, 1_500_000); + let a = rate(first).expect("first rate"); + let b = rate(second).expect("second rate"); assert!(a + b <= 3_000_000, "{a} + {b} oversubscribed"); assert_eq!(a, 1_500_000); assert_eq!(b, 1_500_000); assert_eq!(moq_reservation_close(first), 0); - assert_eq!(grant(second), Some(2_000_000)); + assert_eq!(rate(second), Some(2_000_000)); assert_eq!(moq_reservation_close(second), 0); - assert_eq!(moq_bandwidth_close(bandwidth), 0); + assert_eq!(moq_allocator_close(bandwidth), 0); assert_eq!(moq_consume_track_cancel(first_sub), 0); assert_eq!(moq_consume_track_cancel(second_sub), 0); let _ = first_cb.recv_terminal(); @@ -5856,16 +5856,16 @@ fn bandwidth_handles_share_the_registry() { let (first_sub, first_cb) = subscribe_named_track(consume, b"a"); let (second_sub, second_cb) = subscribe_named_track(consume, b"b"); - let reserved = id(moq_bandwidth_reserve(first, first_track, 4_000_000)); - wait_grant(reserved, 3_000_000); - let other = id(moq_bandwidth_reserve(second, second_track, 4_000_000)); - wait_grant(other, 1_500_000); - wait_grant(reserved, 1_500_000); + let reserved = id(moq_allocator_reserve(first, first_track, 4_000_000)); + wait_rate(reserved, 3_000_000); + let other = id(moq_allocator_reserve(second, second_track, 4_000_000)); + wait_rate(other, 1_500_000); + wait_rate(reserved, 1_500_000); assert_eq!(moq_reservation_close(reserved), 0); assert_eq!(moq_reservation_close(other), 0); - assert_eq!(moq_bandwidth_close(first), 0); - assert_eq!(moq_bandwidth_close(second), 0); + assert_eq!(moq_allocator_close(first), 0); + assert_eq!(moq_allocator_close(second), 0); assert_eq!(moq_consume_track_cancel(first_sub), 0); assert_eq!(moq_consume_track_cancel(second_sub), 0); let _ = first_cb.recv_terminal(); @@ -5915,21 +5915,21 @@ fn encode_video_bitrate_caps_the_reservation() { estimate .set(Some(moq_net::bandwidth::Rate::from_bps(4_000_000))) .unwrap(); - wait_grant(reservation, 4_000_000); + wait_rate(reservation, 4_000_000); assert_eq!(moq_encode_video_bitrate(producer, 1_000_000), 0); - assert_eq!(grant(reservation), Some(1_000_000)); + assert_eq!(rate(reservation), Some(1_000_000)); estimate .set(Some(moq_net::bandwidth::Rate::from_bps(3_000_000))) .unwrap(); - assert_eq!(grant(reservation), Some(1_000_000)); + assert_eq!(rate(reservation), Some(1_000_000)); assert_eq!(moq_reservation_close(reservation), 0); assert_eq!(moq_consume_track_cancel(sub), 0); let _ = cb.recv_terminal(); assert_eq!(moq_encode_video_finish(producer), 0); - assert_eq!(moq_bandwidth_close(bandwidth), 0); + assert_eq!(moq_allocator_close(bandwidth), 0); assert_eq!(moq_consume_close(consume), 0); assert_eq!(moq_publish_close(broadcast), 0); assert_eq!(moq_origin_close(origin), 0); @@ -5967,7 +5967,7 @@ fn encode_video_rung_needs_a_grant_and_a_band() { assert_eq!(moq_encode_video_finish(high), 0); assert_eq!(moq_encode_video_finish(low), 0); - assert_eq!(moq_bandwidth_close(bandwidth), 0); + assert_eq!(moq_allocator_close(bandwidth), 0); assert_eq!(moq_publish_close(broadcast), 0); assert_eq!(moq_origin_close(origin), 0); } @@ -6143,8 +6143,8 @@ fn server_accepts_a_session() { let mut stats: moq_connection_stats = unsafe { std::mem::zeroed() }; assert_eq!(unsafe { moq_session_stats(session, &mut stats) }, 0); - let bandwidth = id(moq_session_bandwidth(session)); - assert_eq!(moq_bandwidth_close(bandwidth), 0); + let bandwidth = id(moq_session_allocator(session)); + assert_eq!(moq_allocator_close(bandwidth), 0); // The broadcast the server publishes reaches the client. A client only asks the // server about what it watches, so wait on the path rather than request it once. diff --git a/rs/moq-c/src/video.rs b/rs/moq-c/src/video.rs index 1496a3f9a3c..1e67a2201ef 100644 --- a/rs/moq-c/src/video.rs +++ b/rs/moq-c/src/video.rs @@ -125,7 +125,7 @@ pub struct moq_video_encoder_output { #[repr(C)] #[derive(Clone, Copy, Default)] pub struct moq_video_encode_options { - /// A handle from [`crate::moq_session_bandwidth`] whose grant the encoder follows, + /// A handle from [`crate::moq_session_allocator`] whose grant the encoder follows, /// or 0 to hold the configured bitrate. pub bandwidth: u32, /// The [`moq_encode_video`] handle of the next lower rendition of the same source, @@ -717,7 +717,7 @@ impl Video { tokio::select! { biased; _ = closed => {} - _ = follow_reservation(follower, lower, reservation.consumer(), ceiling) => {} + _ = follow_reservation(follower, lower, reservation.consume(), ceiling) => {} } Ok(()) }); diff --git a/rs/moq-cli/src/main.rs b/rs/moq-cli/src/main.rs index 7f655fd722a..7018a403f5c 100644 --- a/rs/moq-cli/src/main.rs +++ b/rs/moq-cli/src/main.rs @@ -476,7 +476,7 @@ async fn spawn_moq( // Read before the handle moves into the task. This allocator is persistent: it // survives reconnects, granting `None` while down, so it can be wired up before // anything connects, and every session probes for its reservations. - bandwidth = reconnect.bandwidth(); + bandwidth = reconnect.allocator(); let closed = reconnect.clone(); tasks.spawn(async move { Ok(closed.closed().await?) }); connection = Some(reconnect); diff --git a/rs/moq-cli/tests/integration/epochs.rs b/rs/moq-cli/tests/integration/epochs.rs index cabf046269c..9997d8eaa23 100644 --- a/rs/moq-cli/tests/integration/epochs.rs +++ b/rs/moq-cli/tests/integration/epochs.rs @@ -240,7 +240,7 @@ async fn replacement(version: &str) { let mut cached = media.fetch_group(0, None).await.unwrap(); assert_eq!(cached.read_frame().await.unwrap().unwrap().payload.as_ref(), b"A:0"); if let Ok(late) = pinned.track("late") - && let Ok(info) = late.query().await + && let Ok(info) = late.info().await { assert_ne!(info.priority, 17, "retired handle resolved B's metadata"); } diff --git a/rs/moq-e2ee/src/tests.rs b/rs/moq-e2ee/src/tests.rs index ee925dd21e1..fba81a5fc01 100644 --- a/rs/moq-e2ee/src/tests.rs +++ b/rs/moq-e2ee/src/tests.rs @@ -808,7 +808,7 @@ fn grouped_failure_wakes_pending_reads_and_releases_demand() { let mut good = recv_group(&mut pair.consumer); assert_eq!(read_frame(&mut good).plaintext, &b"ok"[..]); let mut forged = recv_group(&mut pair.consumer); - assert!(bad_demand.is_used()); + assert!(bad_demand.wanted()); // Sibling frame, next group, and datagram reads are already parked. Nothing // further is published. @@ -840,7 +840,7 @@ fn grouped_failure_wakes_pending_reads_and_releases_demand() { !demand.wanted().is_some(), "track demand stayed live after authentication failure" ); - assert!(!bad_demand.is_used(), "failed group demand stayed live"); + assert!(!bad_demand.wanted(), "failed group demand stayed live"); assert!(!pair.net.is_closed(), "publisher must stay open"); assert_eq!( @@ -850,7 +850,7 @@ fn grouped_failure_wakes_pending_reads_and_releases_demand() { Poll::Ready("authentication".to_string()) ); assert!( - !open_demand.is_used(), + !open_demand.wanted(), "sibling group demand stayed live after its woken read" ); assert_eq!( diff --git a/rs/moq-ffi/MIGRATE.md b/rs/moq-ffi/MIGRATE.md index d97c35c5e71..7180e7123a9 100644 --- a/rs/moq-ffi/MIGRATE.md +++ b/rs/moq-ffi/MIGRATE.md @@ -5,9 +5,13 @@ These are the UniFFI names; each language wrapper has its own `MIGRATE.md` in it ## Unreleased +### `MoqAllocator` ([#6751](https://github.com/moq-dev/moq/pull/6751)) + +`MoqBandwidth` is `MoqAllocator`, and `MoqSession::bandwidth()` is `allocator()`, matching `moq_net::bandwidth::Allocator`. `MoqReservation::grant()` is `rate()`, matching `moq_net::bandwidth::Reservation::rate()`. The `bandwidth` option field on audio and video producers keeps its name. + ### An idle reservation reads the share it would get -`MoqReservation::grant` reports the slice the track would get back while nothing subscribes to it, instead of `None`; it still claims nothing from the other tracks. +`MoqReservation::rate` reports the slice the track would get back while nothing subscribes to it, instead of `None`; it still claims nothing from the other tracks. A sender that relied on `None` to hold its rate while unwatched should check the track's demand instead. ### Decoders read gaps and ends diff --git a/rs/moq-ffi/src/audio.rs b/rs/moq-ffi/src/audio.rs index 328872470ab..dfa5dce5332 100644 --- a/rs/moq-ffi/src/audio.rs +++ b/rs/moq-ffi/src/audio.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; -use crate::bandwidth::{MoqBandwidth, MoqReservation}; +use crate::bandwidth::{MoqAllocator, MoqReservation}; use crate::consumer::MoqBroadcastConsumer; use crate::demand::MoqTrackDemand; use crate::error::MoqError; @@ -138,7 +138,7 @@ pub struct MoqAudioProducerOptions { pub track: Option, /// Session bandwidth allocator; absent reserves no share. #[uniffi(default = None)] - pub bandwidth: Option>, + pub bandwidth: Option>, } impl MoqAudioEncoderOutput { @@ -395,7 +395,7 @@ pub struct MoqAudioProducer { inner: std::sync::Mutex>, reservation: std::sync::Mutex>>, /// Held so the reservation's registry outlives extra bandwidth handles. - _bandwidth: Option>, + _bandwidth: Option>, children: crate::producer::Children, } @@ -454,7 +454,7 @@ impl MoqAudioProducer { } /// This encoder's bandwidth reservation, if it was published against a - /// [`MoqBandwidth`]. Dropping the handle does not release the claim; the + /// [`MoqAllocator`]. Dropping the handle does not release the claim; the /// producer holds it until [`finish`](Self::finish). pub fn reservation(&self) -> Option> { self.reservation.lock().unwrap().clone() @@ -530,7 +530,7 @@ impl MoqAudioProducer { moq_audio::encode::Config::from_input(moq_audio::encode::Codec::Aac, &rated).frame_duration; } if let Some(bandwidth) = &bandwidth { - options.bandwidth = bandwidth.allocator().clone(); + options.bandwidth = bandwidth.inner().clone(); } let (producer, children) = broadcast.with_state(|state| { diff --git a/rs/moq-ffi/src/bandwidth.rs b/rs/moq-ffi/src/bandwidth.rs index 0d5f34a959a..bc0d22e1f61 100644 --- a/rs/moq-ffi/src/bandwidth.rs +++ b/rs/moq-ffi/src/bandwidth.rs @@ -8,21 +8,21 @@ use crate::error::MoqError; /// Divides one connection's send estimate among the tracks sharing it. /// -/// Minted by [`MoqSession::bandwidth`](crate::session::MoqSession::bandwidth). +/// Minted by [`MoqSession::allocator`](crate::session::MoqSession::allocator). /// Clones share one reservation registry, so two handles from the same session /// see each other's claims. #[derive(uniffi::Object)] -pub struct MoqBandwidth { +pub struct MoqAllocator { allocator: moq_net::bandwidth::Allocator, } -impl MoqBandwidth { +impl MoqAllocator { pub(crate) fn new(allocator: moq_net::bandwidth::Allocator) -> Self { Self { allocator } } #[cfg(all(feature = "audio", not(target_arch = "wasm32")))] - pub(crate) fn allocator(&self) -> &moq_net::bandwidth::Allocator { + pub(crate) fn inner(&self) -> &moq_net::bandwidth::Allocator { &self.allocator } @@ -35,7 +35,7 @@ impl MoqBandwidth { } #[uniffi::export] -impl MoqBandwidth { +impl MoqAllocator { /// Reserve up to `max_bps` for the track `demand` watches, returning the reservation. /// /// Every track producer hands out its `demand()`, so raw, media, and JSON @@ -49,10 +49,10 @@ impl MoqBandwidth { } } -/// One track's standing claim on a [`MoqBandwidth`]. +/// One track's standing claim on a [`MoqAllocator`]. /// -/// [`grant`](Self::grant) is [`moq_net::bandwidth::Reservation::peek`]: `None` -/// means no estimate, so hold the current rate, and `Some(0)` is a real zero grant. +/// [`rate`](Self::rate) is [`moq_net::bandwidth::Reservation::rate`]: `None` +/// means no estimate, so hold the current rate, and `Some(0)` is a real zero rate. #[derive(uniffi::Object)] pub struct MoqReservation { inner: moq_net::bandwidth::Reservation, @@ -64,8 +64,8 @@ impl MoqReservation { } #[cfg(all(feature = "video", not(target_arch = "wasm32")))] - pub(crate) fn consumer(&self) -> moq_net::bandwidth::Consumer { - self.inner.consumer() + pub(crate) fn consume(&self) -> moq_net::bandwidth::Consumer { + self.inner.consume() } } @@ -74,11 +74,11 @@ impl MoqReservation { /// This reservation's slice right now, in bits per second. /// /// `None` means no estimate: hold the current rate. `Some(0)` is a real zero - /// grant. While nothing subscribes to the track, this is the slice it would get + /// rate. While nothing subscribes to the track, this is the slice it would get /// back, without claiming it from the others. - pub fn grant(&self) -> Option { + pub fn rate(&self) -> Option { let _guard = crate::ffi::enter(); - self.inner.peek().map(moq_net::bandwidth::Rate::as_bps) + self.inner.rate().map(moq_net::bandwidth::Rate::as_bps) } /// Change the ceiling, keeping the same claim. @@ -94,8 +94,8 @@ mod tests { use crate::producer::{MoqBroadcastProducer, MoqTrackProducer}; - fn bandwidth(estimate: &moq_net::bandwidth::Producer) -> Arc { - Arc::new(MoqBandwidth::new(moq_net::bandwidth::Allocator::new( + fn allocator(estimate: &moq_net::bandwidth::Producer) -> Arc { + Arc::new(MoqAllocator::new(moq_net::bandwidth::Allocator::new( estimate.consume(), ))) } @@ -108,7 +108,7 @@ mod tests { #[test] fn concurrent_reservations_split_the_estimate() { let estimate = moq_net::bandwidth::Producer::new(); - let bandwidth = bandwidth(&estimate); + let bandwidth = allocator(&estimate); let broadcast = MoqBroadcastProducer::new().unwrap(); let first = named_track(&broadcast, "a"); @@ -123,8 +123,8 @@ mod tests { .set(Some(moq_net::bandwidth::Rate::from_bps(3_000_000))) .unwrap(); - let a = first.grant().unwrap(); - let b = second.grant().unwrap(); + let a = first.rate().unwrap(); + let b = second.rate().unwrap(); assert!(a + b <= 3_000_000, "{a} + {b} oversubscribed"); assert_eq!(a, 1_500_000); assert_eq!(b, 1_500_000); @@ -139,20 +139,20 @@ mod tests { .set(Some(moq_net::bandwidth::Rate::from_bps(3_000_000))) .unwrap(); let allocator = moq_net::bandwidth::Allocator::new(estimate.consume()); - let first = Arc::new(MoqBandwidth::new(allocator.clone())); - let second = Arc::new(MoqBandwidth::new(allocator)); + let first = Arc::new(MoqAllocator::new(allocator.clone())); + let second = Arc::new(MoqAllocator::new(allocator)); let broadcast = MoqBroadcastProducer::new().unwrap(); let track = named_track(&broadcast, "a"); let _sub = track.consume(None).unwrap(); let reserved = first.reserve(&track.demand().unwrap(), 4_000_000); - assert_eq!(reserved.grant(), Some(3_000_000)); + assert_eq!(reserved.rate(), Some(3_000_000)); let other = named_track(&broadcast, "b"); let _other_sub = other.consume(None).unwrap(); let other = second.reserve(&other.demand().unwrap(), 4_000_000); - assert_eq!(reserved.grant(), Some(1_500_000)); - assert_eq!(other.grant(), Some(1_500_000)); + assert_eq!(reserved.rate(), Some(1_500_000)); + assert_eq!(other.rate(), Some(1_500_000)); } #[test] @@ -161,7 +161,7 @@ mod tests { estimate .set(Some(moq_net::bandwidth::Rate::from_bps(3_000_000))) .unwrap(); - let bandwidth = bandwidth(&estimate); + let bandwidth = allocator(&estimate); let broadcast = MoqBroadcastProducer::new().unwrap(); let first = named_track(&broadcast, "a"); @@ -171,10 +171,10 @@ mod tests { let second = named_track(&broadcast, "b"); let _second_sub = second.consume(None).unwrap(); let second = bandwidth.reserve(&second.demand().unwrap(), 2_000_000); - assert_eq!(second.grant(), Some(1_500_000)); + assert_eq!(second.rate(), Some(1_500_000)); drop(first); - assert_eq!(second.grant(), Some(2_000_000)); + assert_eq!(second.rate(), Some(2_000_000)); } /// A missing estimate (disconnected) reports `None`; a later value is a grant @@ -182,7 +182,7 @@ mod tests { #[test] fn a_reservation_reports_none_while_disconnected() { let estimate = moq_net::bandwidth::Producer::new(); - let bandwidth = bandwidth(&estimate); + let bandwidth = allocator(&estimate); let broadcast = MoqBroadcastProducer::new().unwrap(); let track = named_track(&broadcast, "a"); @@ -192,15 +192,15 @@ mod tests { estimate .set(Some(moq_net::bandwidth::Rate::from_bps(2_000_000))) .unwrap(); - assert_eq!(reserved.grant(), Some(2_000_000)); + assert_eq!(reserved.rate(), Some(2_000_000)); estimate.set(None).unwrap(); - assert_eq!(reserved.grant(), None); + assert_eq!(reserved.rate(), None); estimate .set(Some(moq_net::bandwidth::Rate::from_bps(1_000_000))) .unwrap(); - assert_eq!(reserved.grant(), Some(1_000_000)); + assert_eq!(reserved.rate(), Some(1_000_000)); } #[cfg(all(feature = "video", not(target_arch = "wasm32")))] @@ -209,11 +209,11 @@ mod tests { use std::sync::atomic::Ordering; let estimate = moq_net::bandwidth::Producer::new(); - let bandwidth = bandwidth(&estimate); + let bandwidth = allocator(&estimate); let broadcast = MoqBroadcastProducer::new().unwrap(); let track = named_track(&broadcast, "a"); let reserved = bandwidth.reserve(&track.demand().unwrap(), 4_000_000); - let mut consumer = reserved.consumer(); + let mut consumer = reserved.consume(); let parked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let parked_flag = parked.clone(); diff --git a/rs/moq-ffi/src/producer.rs b/rs/moq-ffi/src/producer.rs index 7acd7809c97..6b44d445ccb 100644 --- a/rs/moq-ffi/src/producer.rs +++ b/rs/moq-ffi/src/producer.rs @@ -925,10 +925,11 @@ impl MoqGroupProducer { #[cfg(test)] impl MoqGroupProducer { - /// Wait until a consumer has this group. - pub(crate) async fn used(&self) -> Result<(), MoqError> { - let demand = self.inner.lock().unwrap().as_ref().ok_or(MoqError::Closed)?.demand(); - Ok(demand.used().await?) + /// Wait until a consumer wants this group. + pub(crate) async fn wanted(&self) -> Result<(), MoqError> { + let mut demand = self.inner.lock().unwrap().as_ref().ok_or(MoqError::Closed)?.demand(); + while !demand.wanted_changed().await? {} + Ok(()) } } diff --git a/rs/moq-ffi/src/session.rs b/rs/moq-ffi/src/session.rs index 37532de90de..aa7bbbdeec2 100644 --- a/rs/moq-ffi/src/session.rs +++ b/rs/moq-ffi/src/session.rs @@ -6,7 +6,7 @@ use std::time::Duration; use url::Url; use crate::auth::MoqGrantConsumer; -use crate::bandwidth::MoqBandwidth; +use crate::bandwidth::MoqAllocator; use crate::error::MoqError; use crate::ffi::Task; use crate::origin::{MoqOriginConsumer, MoqOriginProducer}; @@ -1061,9 +1061,9 @@ pub struct MoqSession { closed: Task, publisher: Arc, consumer: Arc, - /// One allocator for the session. Every [`bandwidth`](Self::bandwidth) handle + /// One allocator for the session. Every [`allocator`](Self::allocator) handle /// clones it, so they share one reservation registry. - bandwidth: Arc, + allocator: Arc, } impl MoqSession { @@ -1092,12 +1092,12 @@ impl MoqSession { // Persistent across reconnects: `None` while disconnected, then a grant // again on the next connection. Reservations survive the gap. #[cfg(not(target_arch = "wasm32"))] - Inner::Connection(connection) => connection.bandwidth(), + Inner::Connection(connection) => connection.allocator(), #[cfg(not(target_arch = "wasm32"))] - Inner::Session(session) => session.bandwidth(), + Inner::Session(session) => session.allocator(), // Persistent from before the handshake, so a reservation made while dialing counts. #[cfg(target_arch = "wasm32")] - Inner::Dial(dial) => dial.bandwidth(), + Inner::Dial(dial) => dial.allocator(), } } @@ -1107,14 +1107,14 @@ impl MoqSession { // is where the remote's broadcasts land (read via its consumer view). let publisher = Arc::new(MoqOriginProducer::from_inner(publish)); let consumer = Arc::new(MoqOriginConsumer::from_inner(subscribe)); - let bandwidth = Arc::new(MoqBandwidth::new(Self::mint_allocator(&inner))); + let allocator = Arc::new(MoqAllocator::new(Self::mint_allocator(&inner))); Self { inner: inner.clone(), shutdown: Default::default(), closed: Task::new(inner.clone()), publisher, consumer, - bandwidth, + allocator, } } @@ -1307,8 +1307,8 @@ impl MoqSession { /// reconnects: the grant is `None` while disconnected and resumes on the /// next connection. An accepted session with no congestion estimate mints /// an unlimited allocator, which reports `None` for every reservation. - pub fn bandwidth(&self) -> Arc { - self.bandwidth.clone() + pub fn allocator(&self) -> Arc { + self.allocator.clone() } /// Follow the grant the peer gave this session. diff --git a/rs/moq-ffi/src/session/dial.rs b/rs/moq-ffi/src/session/dial.rs index 29de99511dd..10efb740cb0 100644 --- a/rs/moq-ffi/src/session/dial.rs +++ b/rs/moq-ffi/src/session/dial.rs @@ -67,7 +67,7 @@ impl Dial { let recv = moq_net::bandwidth::Producer::new(); let bandwidth = moq_net::bandwidth::Allocator::new(send.consume()); let auth = moq_net::auth::Handle::new(); - let client = client.with_bandwidth(bandwidth.clone()).with_auth(auth.clone()); + let client = client.with_allocator(bandwidth.clone()).with_auth(auth.clone()); let dial = Self { state: state.clone(), bandwidth, @@ -188,7 +188,7 @@ impl Dial { } } - pub fn bandwidth(&self) -> moq_net::bandwidth::Allocator { + pub fn allocator(&self) -> moq_net::bandwidth::Allocator { self.bandwidth.clone() } diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 4f0291c5cb5..6dff709cd1b 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -129,7 +129,7 @@ async fn wait_for_config_error( /// Wait until `read_frame` has taken `group` off the ordered cursor. async fn wait_group_acquired(group: &MoqGroupProducer) { - tokio::time::timeout(TIMEOUT, group.used()) + tokio::time::timeout(TIMEOUT, group.wanted()) .await .expect("timed out waiting for the group to be acquired") .unwrap(); @@ -493,7 +493,7 @@ async fn media_track_reserves_through_its_demand() { estimate .set(Some(moq_net::bandwidth::Rate::from_bps(3_000_000))) .unwrap(); - let bandwidth = crate::bandwidth::MoqBandwidth::new(moq_net::bandwidth::Allocator::new(estimate.consume())); + let bandwidth = crate::bandwidth::MoqAllocator::new(moq_net::bandwidth::Allocator::new(estimate.consume())); let broadcast = MoqBroadcastProducer::new().unwrap(); let audio = |name: &str| { @@ -514,12 +514,12 @@ async fn media_track_reserves_through_its_demand() { let reservation = bandwidth.reserve(&demand, 4_000_000); let sibling_reservation = bandwidth.reserve(&sibling_demand, 4_000_000); // No subscriber yet: it claims nothing from its sibling, and reads what it would get. - assert_eq!(sibling_reservation.grant(), Some(3_000_000)); - assert_eq!(reservation.grant(), Some(1_500_000)); + assert_eq!(sibling_reservation.rate(), Some(3_000_000)); + assert_eq!(reservation.rate(), Some(1_500_000)); let _sub = subscribe(&broadcast, &demand.name()).await; - assert_eq!(sibling_reservation.grant(), Some(1_500_000)); - assert_eq!(reservation.grant(), Some(1_500_000)); + assert_eq!(sibling_reservation.rate(), Some(1_500_000)); + assert_eq!(reservation.rate(), Some(1_500_000)); } #[tokio::test] @@ -6942,11 +6942,11 @@ async fn cancelled_state_wait_does_not_swallow_the_next_transition() { #[cfg(feature = "video")] #[tokio::test] async fn video_encoder_follows_a_shrinking_grant() { - use crate::bandwidth::MoqBandwidth; + use crate::bandwidth::MoqAllocator; use crate::video::*; let estimate = moq_net::bandwidth::Producer::new(); - let bandwidth = std::sync::Arc::new(MoqBandwidth::new(moq_net::bandwidth::Allocator::new( + let bandwidth = std::sync::Arc::new(MoqAllocator::new(moq_net::bandwidth::Allocator::new( estimate.consume(), ))); @@ -6977,7 +6977,7 @@ async fn video_encoder_follows_a_shrinking_grant() { .unwrap(); let reservation = video.reservation().expect("published against an allocator"); - assert_eq!(reservation.grant(), None, "no estimate yet"); + assert_eq!(reservation.rate(), None, "no estimate yet"); let consumer = broadcast.consume().unwrap(); let _sub = consumer.subscribe_track("camera".into(), None).await.unwrap(); @@ -6985,12 +6985,12 @@ async fn video_encoder_follows_a_shrinking_grant() { estimate .set(Some(moq_net::bandwidth::Rate::from_bps(4_000_000))) .unwrap(); - assert_eq!(reservation.grant(), Some(4_000_000)); + assert_eq!(reservation.rate(), Some(4_000_000)); estimate .set(Some(moq_net::bandwidth::Rate::from_bps(1_000_000))) .unwrap(); - assert_eq!(reservation.grant(), Some(1_000_000)); + assert_eq!(reservation.rate(), Some(1_000_000)); let deadline = moq_clock::Instant::now() + TIMEOUT; loop { @@ -7036,10 +7036,10 @@ fn software_camera(bitrate: u64) -> (crate::video::MoqVideoEncoderInput, crate:: #[cfg(feature = "video")] #[tokio::test] async fn dropping_a_video_producer_stops_the_rate_follower() { - use crate::bandwidth::MoqBandwidth; + use crate::bandwidth::MoqAllocator; let estimate = moq_net::bandwidth::Producer::new(); - let bandwidth = std::sync::Arc::new(MoqBandwidth::new(moq_net::bandwidth::Allocator::new( + let bandwidth = std::sync::Arc::new(MoqAllocator::new(moq_net::bandwidth::Allocator::new( estimate.consume(), ))); let broadcast = MoqBroadcastProducer::new().unwrap(); @@ -7066,10 +7066,10 @@ async fn dropping_a_video_producer_stops_the_rate_follower() { #[cfg(feature = "video")] #[tokio::test] async fn set_bitrate_caps_a_later_bandwidth_grant() { - use crate::bandwidth::MoqBandwidth; + use crate::bandwidth::MoqAllocator; let estimate = moq_net::bandwidth::Producer::new(); - let bandwidth = std::sync::Arc::new(MoqBandwidth::new(moq_net::bandwidth::Allocator::new( + let bandwidth = std::sync::Arc::new(MoqAllocator::new(moq_net::bandwidth::Allocator::new( estimate.consume(), ))); let broadcast = MoqBroadcastProducer::new().unwrap(); @@ -7092,16 +7092,16 @@ async fn set_bitrate_caps_a_later_bandwidth_grant() { estimate .set(Some(moq_net::bandwidth::Rate::from_bps(4_000_000))) .unwrap(); - assert_eq!(reservation.grant(), Some(4_000_000)); + assert_eq!(reservation.rate(), Some(4_000_000)); video.set_bitrate(1_000_000).unwrap(); - assert_eq!(reservation.grant(), Some(1_000_000)); + assert_eq!(reservation.rate(), Some(1_000_000)); assert_eq!(video.applied_bitrate(), 1_000_000); estimate .set(Some(moq_net::bandwidth::Rate::from_bps(3_000_000))) .unwrap(); - assert_eq!(reservation.grant(), Some(1_000_000)); + assert_eq!(reservation.rate(), Some(1_000_000)); assert_eq!(video.applied_bitrate(), 1_000_000); video.finish().unwrap(); diff --git a/rs/moq-ffi/src/transport/adapter.rs b/rs/moq-ffi/src/transport/adapter.rs index 78fc7339a2f..57c338d32ed 100644 --- a/rs/moq-ffi/src/transport/adapter.rs +++ b/rs/moq-ffi/src/transport/adapter.rs @@ -17,14 +17,8 @@ impl moq::Error for Error { } } -struct Stats(S); -impl moq::Stats for Stats { - fn bytes_sent(&self) -> Option { - self.0.bytes_sent() - } - fn bytes_received(&self) -> Option { - self.0.bytes_received() - } +struct Metrics(S); +impl moq::Metrics for Metrics { fn bytes_lost(&self) -> Option { self.0.bytes_lost() } @@ -134,8 +128,8 @@ impl + Clone + 'st fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll { backend::Session::poll_closed(&mut self.0, cx).map(Error) } - fn stats(&self) -> impl moq::Stats { - Stats(backend::Session::stats(&self.0)) + fn metrics(&self) -> impl moq::Metrics { + Metrics(backend::Session::stats(&self.0)) } } /// An outgoing WebTransport stream adapted to moq-net. @@ -306,13 +300,13 @@ mod tests { #[test] fn forwards_thread_local_streams_and_keeps_error_codes() { - use moq_net::transport::Stats as _; + use moq_net::transport::Metrics as _; let state = Rc::new(Cell::new(0)); let mut session = Session::new(Backend(state.clone())); let mut cx = Context::from_waker(std::task::Waker::noop()); assert_eq!(poll::Session::protocol(&session), Some("moq-lite-06")); assert_eq!( - poll::Session::stats(&session).rtt(), + poll::Session::metrics(&session).rtt(), Some(std::time::Duration::from_millis(7)) ); let Poll::Ready(Ok((mut send, mut recv))) = diff --git a/rs/moq-ffi/src/video.rs b/rs/moq-ffi/src/video.rs index d1485a3d22a..3f794b297e8 100644 --- a/rs/moq-ffi/src/video.rs +++ b/rs/moq-ffi/src/video.rs @@ -15,7 +15,7 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use tokio::sync::oneshot; -use crate::bandwidth::{MoqBandwidth, MoqReservation}; +use crate::bandwidth::{MoqAllocator, MoqReservation}; use crate::consumer::MoqBroadcastConsumer; use crate::demand::MoqTrackDemand; use crate::error::MoqError; @@ -151,7 +151,7 @@ pub struct MoqVideoProducerOptions { pub track: Option, /// Session bandwidth allocator; absent keeps the configured bitrate. #[uniffi(default = None)] - pub bandwidth: Option>, + pub bandwidth: Option>, /// The next lower rendition of the same source, when this one is encoded beside it. /// /// Makes this rendition a simulcast rung: when the bandwidth grant can no longer fund @@ -507,7 +507,7 @@ pub struct MoqVideoProducer { /// Last bitrate applied by the follow loop or [`set_bitrate`](Self::set_bitrate). applied: Arc, /// Held so the reservation's registry outlives extra bandwidth handles. - _bandwidth: Option>, + _bandwidth: Option>, children: crate::producer::Children, } @@ -616,7 +616,7 @@ impl MoqVideoProducer { /// [`bitrate`](MoqVideoEncoderOutput::bitrate) to the highest you will ask for /// and adapt downwards from there. /// - /// When this producer was published against a [`MoqBandwidth`], the reservation + /// When this producer was published against a [`MoqAllocator`], the reservation /// and follower ceiling move with it, so a later grant cannot retune above this /// value. /// @@ -648,7 +648,7 @@ impl MoqVideoProducer { } /// This encoder's bandwidth reservation, if it was published against a - /// [`MoqBandwidth`]. Dropping the handle does not release the claim; the + /// [`MoqAllocator`]. Dropping the handle does not release the claim; the /// producer holds it until [`finish`](Self::finish). pub fn reservation(&self) -> Option> { self.reservation.lock().unwrap().clone() @@ -802,7 +802,7 @@ impl MoqVideoProducer { spawn_follow(Followed { inner: inner.clone(), lower, - consumer: reservation.consumer(), + consumer: reservation.consume(), ceiling, applied: applied.clone(), }) @@ -1416,7 +1416,7 @@ mod finish_tests { #[tokio::test] async fn finish_ends_the_track_after_a_rate_follower_panic() { let estimate = moq_net::bandwidth::Producer::new(); - let bandwidth = Arc::new(MoqBandwidth::new(moq_net::bandwidth::Allocator::new( + let bandwidth = Arc::new(MoqAllocator::new(moq_net::bandwidth::Allocator::new( estimate.consume(), ))); let broadcast = crate::producer::MoqBroadcastProducer::new().unwrap(); @@ -1646,7 +1646,7 @@ mod rung_tests { fn ladder() -> Ladder { let estimate = moq_net::bandwidth::Producer::new(); - let bandwidth = Arc::new(MoqBandwidth::new(moq_net::bandwidth::Allocator::new( + let bandwidth = Arc::new(MoqAllocator::new(moq_net::bandwidth::Allocator::new( estimate.consume(), ))); let broadcast = crate::producer::MoqBroadcastProducer::new().unwrap(); @@ -1706,7 +1706,7 @@ mod rung_tests { input: input(), output: output(400_000), track: Some("below".into()), - bandwidth: Some(Arc::new(MoqBandwidth::new(moq_net::bandwidth::Allocator::unlimited()))), + bandwidth: Some(Arc::new(MoqAllocator::new(moq_net::bandwidth::Allocator::unlimited()))), lower: Some(ladder.low.clone()), }, ); diff --git a/rs/moq-hls/src/export/rendition.rs b/rs/moq-hls/src/export/rendition.rs index f08de3d2c24..1f5e0251ec1 100644 --- a/rs/moq-hls/src/export/rendition.rs +++ b/rs/moq-hls/src/export/rendition.rs @@ -125,7 +125,7 @@ struct Media { struct Handle { binding: Arc, /// The query holding the track instance alive without subscribing to its media. - track: Option, + track: Option, /// The bound sibling ended, so only its retained rows drain. ended: bool, } @@ -137,7 +137,7 @@ impl Handle { { // The lookup is lazy: the query installs the instance, and reads pin to it through // the query, since End may refuse any lookup made after this one. - self.track = Some(track.query().into_inner()); + self.track = Some(track.info().into_inner()); } } } diff --git a/rs/moq-mux/src/catalog/producer.rs b/rs/moq-mux/src/catalog/producer.rs index 72bd1ba2b6d..218f826fbfd 100644 --- a/rs/moq-mux/src/catalog/producer.rs +++ b/rs/moq-mux/src/catalog/producer.rs @@ -1582,7 +1582,7 @@ mod test { "video.timeline.z", ] { let track = consumer.track(name).expect("track"); - let info = track.query().await.expect("info"); + let info = track.info().await.expect("info"); assert_eq!(info.priority, PRIORITY.catalog, "{name} should rank with the catalog"); } } diff --git a/rs/moq-mux/src/container/consumer.rs b/rs/moq-mux/src/container/consumer.rs index a182f9b8bf2..1c010612bec 100644 --- a/rs/moq-mux/src/container/consumer.rs +++ b/rs/moq-mux/src/container/consumer.rs @@ -2815,8 +2815,8 @@ mod tests { let read = read_past_frames(&mut consumer).await; assert!(matches!(read, Err(crate::Error::UnknownFormat(_))), "{read:?}"); assert!(track.demand().wanted().is_none(), "the ended reader still subscribes"); - assert!(!malformed.demand().is_used(), "the ended reader still holds its group"); - assert!(!later.demand().is_used(), "the ended reader still holds a later group"); + assert!(!malformed.demand().wanted(), "the ended reader still holds its group"); + assert!(!later.demand().wanted(), "the ended reader still holds a later group"); } /// A malformed object mid-group, found while looking ahead past a blocked group, ends the diff --git a/rs/moq-mux/src/container/producer.rs b/rs/moq-mux/src/container/producer.rs index c8e9648db1b..c5e7e98a521 100644 --- a/rs/moq-mux/src/container/producer.rs +++ b/rs/moq-mux/src/container/producer.rs @@ -992,7 +992,7 @@ mod tests { let _encoder_sub = encoder_track.subscribe(None); let encoder = allocator.reserve(&encoder_track.demand(), moq_net::bandwidth::Rate::from_bps(8_000_000)); assert_eq!( - encoder.peek(), + encoder.rate(), Some(moq_net::bandwidth::Rate::from_bps(6_000_000)), "alone, the encoder takes the whole estimate" ); @@ -1005,14 +1005,14 @@ mod tests { producer.write(sized_frame(0, true, 100_000)).unwrap(); producer.write(sized_frame(500_000, false, 100_000)).unwrap(); assert_eq!( - encoder.peek(), + encoder.rate(), Some(moq_net::bandwidth::Rate::from_bps(6_000_000)), "nothing claimed before the first window" ); producer.cut(Some(Timestamp::from_micros(1_000_000).unwrap())).unwrap(); assert_eq!( - encoder.peek(), + encoder.rate(), Some(moq_net::bandwidth::Rate::from_bps(4_400_000)), "the encoder's grant drops by the passthrough peak (1.6 Mbps)" ); diff --git a/rs/moq-mux/src/container/test_util.rs b/rs/moq-mux/src/container/test_util.rs index e68924d0524..bf81eeb7d9f 100644 --- a/rs/moq-mux/src/container/test_util.rs +++ b/rs/moq-mux/src/container/test_util.rs @@ -549,7 +549,7 @@ impl moq_net::transport::poll::Session for Gated { self.inner.poll_closed(cx) } - fn stats(&self) -> impl moq_net::transport::Stats { - self.inner.stats() + fn metrics(&self) -> impl moq_net::transport::Metrics { + self.inner.metrics() } } diff --git a/rs/moq-mux/src/import/track.rs b/rs/moq-mux/src/import/track.rs index 2df16450b0a..227d8fe09e0 100644 --- a/rs/moq-mux/src/import/track.rs +++ b/rs/moq-mux/src/import/track.rs @@ -1145,10 +1145,10 @@ mod tests { let request = broadcast.reserve_track("video").unwrap(); let _video = Track::video(request, catalog.reserve(), VideoInit::new(VideoFormat::Vp8, Vec::new())).unwrap(); - let audio = consumer.track("audio").unwrap().query().await.unwrap(); + let audio = consumer.track("audio").unwrap().info().await.unwrap(); assert_eq!(audio.priority, PRIORITY.audio); - let video = consumer.track("video").unwrap().query().await.unwrap(); + let video = consumer.track("video").unwrap().info().await.unwrap(); assert_eq!(video.priority, PRIORITY.video); } diff --git a/rs/moq-mux/src/rate.rs b/rs/moq-mux/src/rate.rs index 376778eaf48..113f2031d53 100644 --- a/rs/moq-mux/src/rate.rs +++ b/rs/moq-mux/src/rate.rs @@ -1305,7 +1305,7 @@ mod tests { .iter_mut() .zip(&reservations) .map(|(control, reservation)| { - control.update(reservation.peek(), at); + control.update(reservation.rate(), at); control.target() }) .collect() diff --git a/rs/moq-net-tests/tests/integration/restart.rs b/rs/moq-net-tests/tests/integration/restart.rs index f41bfe7bf22..6e5f300a1dc 100644 --- a/rs/moq-net-tests/tests/integration/restart.rs +++ b/rs/moq-net-tests/tests/integration/restart.rs @@ -483,12 +483,12 @@ async fn retired_fetch(version: &str, explicit: bool) { write(&old_track, "old:1"); assert_eq!(read(&mut subscription).await, "old:1"); if let Ok(late) = held.track("late") - && let Ok(info) = late.query().await + && let Ok(info) = late.info().await { assert_ne!(info.priority, 17, "{version}: late track resolved replacement"); } // A held query keeps reading the retired instance; a bare handle would not. - let _reading = track.query(); + let _reading = track.info(); drop(subscription); settle().await; let resumed = track.subscribe(None).await; diff --git a/rs/moq-net/MIGRATE.md b/rs/moq-net/MIGRATE.md index 6b40978fa36..445d0636ff6 100644 --- a/rs/moq-net/MIGRATE.md +++ b/rs/moq-net/MIGRATE.md @@ -4,6 +4,26 @@ How to update your code for each breaking change, newest first. ## Unreleased +### Names say one thing ([#6751](https://github.com/moq-dev/moq/pull/6751)) + +Rename these, which kept their behavior: + +| Before | After | +|---|---| +| `Session::bandwidth()` | `Session::allocator()` | +| `Client::with_bandwidth` | `Client::with_allocator` | +| `auth::Auth` | `auth::Credential` | +| `track::Consumer::query()`, `track::Querying` | `track::Consumer::info()`, `track::Resolving` | +| `bandwidth::Reservation::consumer()` | `bandwidth::Reservation::consume()` | +| `bandwidth::Reservation::peek()` | `bandwidth::Reservation::rate()` | +| `stats::Control` | `stats::Message` | +| `stats::Bytes` | `stats::Totals` | +| `transport::Stats`, `transport::poll::Session::stats()` | `transport::Metrics`, `transport::poll::Session::metrics()` | + +`group::Demand` reads like `track::Demand`: replace `is_used()` with `wanted()`, and `used()`, `unused()`, `poll_used`, and `poll_unused` with a loop over `wanted_changed()` (or `poll_wanted_changed`), which returns the new value each time it changes and errors once the group closes. +`transport::Metrics` drops `bytes_sent` and `bytes_received`: a transport reports them through the `transport::Wire` it returns from `wire()`, which `session::Stats` now reads. +`transport::StatsUnavailable` is gone: `metrics()` defaults to reporting nothing, so delete an implementation that returned it. + ### One lifecycle vocabulary ([#6750](https://github.com/moq-dev/moq/pull/6750)) `closed()` on `group::Producer`, `group::Demand`, `track::Producer`, and `track::Demand` now waits for the outcome and returns `Result<()>`: `Ok(())` once the end settles (a finished group; a track whose declared end was reached with every group below it finished), or the abort error. Match on the result where you awaited `()` or treated `Error::Dropped` as a clean end; `poll_closed` returns `Poll>`. @@ -13,7 +33,7 @@ A session closing locally aborts its copies with `Error::Stream(StreamError::Ses ### An idle reservation reads the share it would get -`bandwidth::Reservation::peek` and its `consumer()` report the slice the track would get back while nothing subscribes to it, instead of `None`; it still claims nothing from the other tracks. +`bandwidth::Reservation::rate()` and its `consume()` report the slice the track would get back while nothing subscribes to it, instead of `None`; it still claims nothing from the other tracks. `None` now means only that the connection has no estimate or the reservation is gone. A sender that relied on `None` to hold its rate while unwatched should check its track's demand instead. diff --git a/rs/moq-net/benches/auth.rs b/rs/moq-net/benches/auth.rs index 584fbdefece..586bd3ced01 100644 --- a/rs/moq-net/benches/auth.rs +++ b/rs/moq-net/benches/auth.rs @@ -188,7 +188,7 @@ fn renewal(c: &mut Criterion) { let broadcasts: Vec<_> = (0..routes) .map(|route| origin.create_broadcast(format!("room/{route}").as_str()).unwrap()) .collect(); - let mut swap = |auth: &auth::Auth, touched: usize| { + let mut swap = |auth: &auth::Credential, touched: usize| { for broadcast in broadcasts.iter().take(touched) { broadcast .announce(origin::Route::default().with_auth(auth.clone())) diff --git a/rs/moq-net/src/auth.rs b/rs/moq-net/src/auth.rs index 820062916dc..cb82eaf0e5b 100644 --- a/rs/moq-net/src/auth.rs +++ b/rs/moq-net/src/auth.rs @@ -5,12 +5,12 @@ //! setup, and learns the [`Grant`] it earned. `Session::auth` //! returns the [`Handle`]: [`grant`](Handle::grant) is the union of every token //! this side presented, and `add` presents another without -//! reconnecting. The returned [`Auth`] is cloneable; dropping its last clone withdraws it. +//! reconnecting. The returned [`Credential`] is cloneable; dropping its last clone withdraws it. //! A [`Route`](crate::origin::Route) can name it, so the request advertising the route //! carries it too, and swapping it renews that request in place. //! //! A handle passed to `Client::with_auth` outlives its sessions: each session built on it -//! presents every token it holds, so a route naming one of its [`Auth`]s keeps it across a +//! presents every token it holds, so a route naming one of its [`Credential`]s keeps it across a //! reconnect. Only the peer's verdict ends such a token; a session ending leaves it for the //! next. It backs one active session at a time, plus the ones draining after a GOAWAY. //! @@ -255,7 +255,7 @@ struct Slot { retry: Option, /// Why the token ended on this session, once it has. ended: Option, - /// The last [`Auth`] clone dropped: the driver closes the stream. + /// The last [`Credential`] clone dropped: the driver closes the stream. withdrawn: bool, } @@ -353,7 +353,7 @@ impl Attached { self.recompute(); } - /// The last [`Auth`] clone for token `id` dropped. + /// The last [`Credential`] clone for token `id` dropped. fn withdraw(&mut self, id: u64) { let Some(slot) = self.slots.get_mut(&id) else { return; @@ -558,7 +558,7 @@ impl Permit { /// /// A session made without one creates its own, returned by `Session::auth`, which ends /// with that session. Pass one to `Client::with_auth` instead and it outlives its -/// sessions: each presents every token the handle holds, so an [`Auth`] it issued keeps +/// sessions: each presents every token the handle holds, so a [`Credential`] it issued keeps /// riding a route's announcements across a reconnect. It backs one active session at a /// time, plus the ones draining after a GOAWAY. /// @@ -584,7 +584,7 @@ impl Handle { /// Present another token on every session of this handle, resolving once a peer accepts it /// with how it did. /// - /// The grant joins the union while any clone of the returned [`Auth`] lives. With no + /// The grant joins the union while any clone of the returned [`Credential`] lives. With no /// session live it waits for the next one. A refusal that may pass, such as an /// unreachable auth server, is presented again after a backoff, and so is a token whose /// stream the peer drops without a verdict. On moq-transport @@ -598,14 +598,14 @@ impl Handle { /// (moq-lite without AUTH, or a peer that takes no tokens in band), the peer's refusal /// as [`Error::Session`], or the handle's end. #[cfg(feature = "async")] - pub async fn add(&self, token: impl Into) -> Result<(Auth, Answer)> { + pub async fn add(&self, token: impl Into) -> Result<(Credential, Answer)> { let auth = self.present(token.into())?; let answer = kio::wait(|waiter| auth.poll_answered(waiter)).await?; Ok((auth, answer)) } /// Register a token and queue it on every open session. - pub(crate) fn present(&self, token: Bytes) -> Result { + pub(crate) fn present(&self, token: Bytes) -> Result { let mut guard = self.state.lock(); let state = &mut *guard; if let Some(err) = &state.closed { @@ -616,7 +616,7 @@ impl Handle { return Err(Error::GoingAway); } let id = state.present(token); - Ok(Auth { + Ok(Credential { presented: std::sync::Arc::new(Presented { state: self.state.clone(), id, @@ -879,7 +879,7 @@ impl Link { /// Present a token: the session's own credential at setup, presented on this session /// alone, or else one of the handle's, presented on every session. - pub(crate) fn present(&self, token: Bytes, setup: bool) -> Result { + pub(crate) fn present(&self, token: Bytes, setup: bool) -> Result { if !setup { return self.handle.present(token); } @@ -901,7 +901,7 @@ impl Link { state.next_id += 1; Ok(id) })?; - Ok(Auth { + Ok(Credential { presented: std::sync::Arc::new(Presented { state: self.state().clone(), id, @@ -913,7 +913,7 @@ impl Link { /// The token a request carries for `auth`, or `None` when the request goes out unnamed /// under the session's scope: `auth` came from another handle, it ended here, or /// requests carry no token on this version. - pub(crate) fn token(&self, auth: &Auth) -> Option { + pub(crate) fn token(&self, auth: &Credential) -> Option { if !auth.presented.state.same_channel(self.state()) { return None; } @@ -1347,19 +1347,19 @@ fn attached(links: &mut BTreeMap, id: u64) -> &mut Attached { /// removes its grant from the union. A [`Route`](crate::origin::Route) holding one keeps /// it presented while the route stands, across the handle's sessions. #[derive(Clone)] -pub struct Auth { +pub struct Credential { presented: std::sync::Arc, } #[cfg(test)] -impl Auth { +impl Credential { /// The id the session presents this credential under. pub(crate) fn id(&self) -> u64 { self.presented.id } } -/// The token every clone of one [`Auth`] shares, withdrawn when the last drops. +/// The token every clone of one [`Credential`] shares, withdrawn when the last drops. struct Presented { state: kio::Shared, id: u64, @@ -1377,7 +1377,7 @@ impl Presented { } } -impl Auth { +impl Credential { /// This credential's own grant on the live session: `None` until its peer answers, /// while no session is live, forever on moq-transport without AUTH, and again once /// the credential ends. @@ -1419,18 +1419,18 @@ impl Auth { } } -impl PartialEq for Auth { +impl PartialEq for Credential { fn eq(&self, other: &Self) -> bool { std::sync::Arc::ptr_eq(&self.presented, &other.presented) } } -impl Eq for Auth {} +impl Eq for Credential {} -impl std::fmt::Debug for Auth { +impl std::fmt::Debug for Credential { // Never the token: routes are logged, and a credential must not be. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_tuple("Auth").field(&self.presented.id).finish() + f.debug_tuple("Credential").field(&self.presented.id).finish() } } @@ -1490,7 +1490,7 @@ impl Selector { /// Watches a grant: the live session's union, or one credential's. /// -/// Created by [`Handle::grant`] and [`Auth::grant`]. +/// Created by [`Handle::grant`] and [`Credential::grant`]. pub struct Watch { state: kio::Shared, selector: Selector, diff --git a/rs/moq-net/src/auth/tokens.rs b/rs/moq-net/src/auth/tokens.rs index e4dcd789100..c857662c849 100644 --- a/rs/moq-net/src/auth/tokens.rs +++ b/rs/moq-net/src/auth/tokens.rs @@ -193,7 +193,7 @@ impl Tokens { } } - fn connect(&self, credential: Option<&super::Auth>) { + fn connect(&self, credential: Option<&super::Credential>) { let mut state = self.handle.state.lock(); state.record(); let connected = match credential { @@ -530,7 +530,7 @@ mod tests { use super::*; use crate::{ SessionError, - auth::{Auth, Grant, Link}, + auth::{Credential, Grant, Link}, }; fn tokens(names: &[&str]) -> Vec { @@ -549,7 +549,7 @@ mod tests { /// requests when `requests`. struct Session { link: Link, - credential: Option, + credential: Option, } fn dial(set: &Tokens, supported: bool, requests: bool) -> Session { diff --git a/rs/moq-net/src/client.rs b/rs/moq-net/src/client.rs index d8b3b71773d..f65f6edae12 100644 --- a/rs/moq-net/src/client.rs +++ b/rs/moq-net/src/client.rs @@ -23,7 +23,7 @@ pub struct Client { limits: crate::session::Limits, extensions: setup::Extensions, auth: Option, - bandwidth: Option, + allocator: Option, implementation: Option, } @@ -72,20 +72,20 @@ impl Client { self } - /// Share `bandwidth`'s reservations with every session this client dials. + /// Share `allocator`'s reservations with every session this client dials. /// /// Each session probes for what they add up to, and its - /// [`Session::bandwidth`](crate::Session::bandwidth) reserves into the same registry, + /// [`Session::allocator`](crate::Session::allocator) reserves into the same registry, /// so a reservation taken on one session still counts after a reconnect. Without /// one, each session starts an empty registry of its own. - pub fn with_bandwidth(mut self, bandwidth: crate::bandwidth::Allocator) -> Self { - self.bandwidth = Some(bandwidth); + pub fn with_allocator(mut self, allocator: crate::bandwidth::Allocator) -> Self { + self.allocator = Some(allocator); self } /// The registry the next session probes for. - fn bandwidth(&self) -> crate::bandwidth::Allocator { - self.bandwidth.clone().unwrap_or_default() + fn allocator(&self) -> crate::bandwidth::Allocator { + self.allocator.clone().unwrap_or_default() } /// Restrict which protocol versions to offer, in preference order. @@ -170,7 +170,7 @@ impl Client { } /// Build every session on `auth`, so each presents the tokens it holds and a route - /// naming one of its [`Auth`](crate::auth::Auth)s keeps it across a reconnect. Omit to + /// naming one of its [`Credential`](crate::auth::Credential)s keeps it across a reconnect. Omit to /// give each session a handle of its own, which ends with it. /// /// The handle backs one active session at a time, plus the ones draining after a @@ -344,7 +344,7 @@ impl Client { auth: start.auth, credential: start.credential, estimate: Some(start.estimate), - bandwidth: self.bandwidth(), + bandwidth: self.allocator(), peer_implementation: start.peer_implementation, }, )) @@ -423,7 +423,7 @@ impl Client { auth, credential, estimate: None, - bandwidth: self.bandwidth(), + bandwidth: self.allocator(), peer_implementation, }, )); @@ -638,7 +638,7 @@ impl Client { auth, credential, estimate, - bandwidth: self.bandwidth(), + bandwidth: self.allocator(), peer_implementation, }, )) @@ -698,7 +698,7 @@ mod tests { close_events: kio::Shared>, control_writes: Arc>>, send_rate: Mutex>, - bytes_sent: Mutex>, + wire: crate::transport::Wire, } fn any_close(events: &kio::Ref<'_, Vec<(u32, String)>>) -> Poll<()> { @@ -722,7 +722,7 @@ mod tests { close_events: kio::Shared::default(), control_writes: writes, send_rate: Mutex::new(None), - bytes_sent: Mutex::new(None), + wire: crate::transport::Wire::new(), }; Self { state: Arc::new(state), @@ -746,8 +746,8 @@ mod tests { self.probe.as_ref().expect("built with_probe").target().as_bps() } - fn set_bytes_sent(&self, bytes: Option) { - *self.state.bytes_sent.lock().unwrap() = bytes; + fn set_sent_bytes(&self, bytes: u64) { + self.state.wire.set_sent_bytes(bytes); } fn control_writes(&self) -> Vec { @@ -846,31 +846,29 @@ mod tests { Poll::Ready(FakeError) } - fn stats(&self) -> impl crate::transport::Stats { - FakeStats { + fn metrics(&self) -> impl crate::transport::Metrics { + FakeMetrics { send_rate: *self.state.send_rate.lock().unwrap(), - bytes_sent: *self.state.bytes_sent.lock().unwrap(), } } + fn wire(&self) -> Option { + Some(self.state.wire.clone()) + } + fn probe(&self) -> Option { self.probe.clone() } } - struct FakeStats { + struct FakeMetrics { send_rate: Option, - bytes_sent: Option, } - impl crate::transport::Stats for FakeStats { + impl crate::transport::Metrics for FakeMetrics { fn estimated_send_rate(&self) -> Option { self.send_rate } - - fn bytes_sent(&self) -> Option { - self.bytes_sent - } } #[derive(Clone, Default)] @@ -1346,7 +1344,7 @@ mod tests { async fn stats_capture_the_final_counters() { let fake = FakeSession::new(Some(ALPN_LITE_04), Vec::new()); fake.set_send_rate(None); - fake.set_bytes_sent(Some(0)); + fake.set_sent_bytes(0); let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into()); let (session, driver) = client.connect(moq_clock::now(), fake.clone()).await.unwrap(); @@ -1356,7 +1354,7 @@ mod tests { "no send-rate estimate, so nothing samples on its own" ); - fake.set_bytes_sent(Some(4242)); + fake.set_sent_bytes(4242); session.abort(Error::Cancel); session.closed().await; @@ -1423,7 +1421,7 @@ mod tests { let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into()); let (session, driver) = client.connect(moq_clock::now(), fake.clone()).await.unwrap(); moq_clock::sim::spawn(crate::time::run(driver)); - let bandwidth = session.bandwidth(); + let bandwidth = session.allocator(); let (_watched_broadcast, watched) = reservable(); let _sub = watched.subscribe(None); @@ -1451,7 +1449,7 @@ mod tests { let client = Client::new().with_versions(Version::Lite(lite::Version::Lite04).into()); let (session, driver) = client.connect(moq_clock::now(), fake.clone()).await.unwrap(); moq_clock::sim::spawn(crate::time::run(driver)); - let bandwidth = session.bandwidth(); + let bandwidth = session.allocator(); let (_broadcast, track) = reservable(); let _reserved = bandwidth.reserve(&track.demand(), crate::bandwidth::Rate::from_bps(4_000_000)); @@ -1474,7 +1472,7 @@ mod tests { let bandwidth = crate::bandwidth::Allocator::default(); let client = Client::new() .with_versions(Version::Lite(lite::Version::Lite04).into()) - .with_bandwidth(bandwidth.clone()); + .with_allocator(bandwidth.clone()); let (_broadcast, track) = reservable(); let reserved = bandwidth.reserve(&track.demand(), crate::bandwidth::Rate::from_bps(4_000_000)); diff --git a/rs/moq-net/src/coding/decode.rs b/rs/moq-net/src/coding/decode.rs index bea333498d0..54ca043833e 100644 --- a/rs/moq-net/src/coding/decode.rs +++ b/rs/moq-net/src/coding/decode.rs @@ -130,7 +130,7 @@ pub struct Decoder<'a> { /// See [`Self::need`]. need: usize, /// The control message read, counted once the read is consumed. - pub(crate) control: Option, + pub(crate) control: Option, /// Leading bytes left out of the `control` count: a type selector the sender writes /// apart from the message, and so never counts. pub(crate) uncounted: usize, diff --git a/rs/moq-net/src/coding/encode.rs b/rs/moq-net/src/coding/encode.rs index b84d437e2ba..bbd308a5731 100644 --- a/rs/moq-net/src/coding/encode.rs +++ b/rs/moq-net/src/coding/encode.rs @@ -59,7 +59,7 @@ pub trait Encode { pub struct Encoder<'a> { buf: &'a mut Vec, form: Form, - pub(crate) control: Option, + pub(crate) control: Option, } impl<'a> Encoder<'a> { diff --git a/rs/moq-net/src/coding/reader.rs b/rs/moq-net/src/coding/reader.rs index fd35176776d..dd4fc430321 100644 --- a/rs/moq-net/src/coding/reader.rs +++ b/rs/moq-net/src/coding/reader.rs @@ -504,7 +504,7 @@ mod tests { fn control_counts_consumed_messages_once() { use crate::{ lite, - stats::{Bytes, Control, Registry, Tier}, + stats::{Message, Registry, Tier, Totals}, }; let registry = Registry::new(Default::default()); let session = registry.tier(Tier::default()).session(""); @@ -517,7 +517,7 @@ mod tests { let size = bytes.len() as u64; let (head, tail) = bytes.split_at(2); let counted = || registry.snapshot().control(); - let probes = |n: u64| vec![(Tier::default(), Control::Probe, Bytes { tx: 0, rx: size * n })]; + let probes = |n: u64| vec![(Tier::default(), Message::Probe, Totals { tx: 0, rx: size * n })]; let mut reader = queue(&[bytes, head], version).with_stats(&session); let mut cx = Context::from_waker(std::task::Waker::noop()); @@ -550,8 +550,8 @@ mod tests { )); let auth = ( Tier::default(), - Control::Auth, - Bytes { + Message::Auth, + Totals { tx: 0, rx: reply.len() as u64, }, diff --git a/rs/moq-net/src/coding/writer.rs b/rs/moq-net/src/coding/writer.rs index 2e72773a13d..16101a1f222 100644 --- a/rs/moq-net/src/coding/writer.rs +++ b/rs/moq-net/src/coding/writer.rs @@ -376,7 +376,7 @@ mod tests { impl Encode for Poison { fn encode(&self, w: &mut Encoder<'_>, _: V) -> Result<(), EncodeError> { - w.control = Some(crate::stats::Control::Probe); + w.control = Some(crate::stats::Message::Probe); w.slice(b"junk"); Err(EncodeError::BoundsExceeded) } @@ -413,7 +413,7 @@ mod tests { fn control_body_counts_successful_encodes_once_before_transport_delivery() { use crate::{ lite, - stats::{Bytes, Control, Registry, Tier}, + stats::{Message, Registry, Tier, Totals}, }; let stats = Registry::new(Default::default()); let session = stats.tier(Tier::new("internal")).session(""); @@ -432,7 +432,7 @@ mod tests { assert!(writer.poll_flush(&mut Context::from_waker(Waker::noop())).is_pending()); assert_eq!( stats.snapshot().control(), - vec![(Tier::new("internal"), Control::Probe, Bytes { tx: size, rx: 0 })] + vec![(Tier::new("internal"), Message::Probe, Totals { tx: size, rx: 0 })] ); writer .buffer(&lite::Track { @@ -446,7 +446,7 @@ mod tests { .snapshot() .control() .into_iter() - .find(|(_, class, _)| *class == Control::TrackInfo) + .find(|(_, class, _)| *class == Message::TrackInfo) .unwrap() .2 .tx diff --git a/rs/moq-net/src/fuzz.rs b/rs/moq-net/src/fuzz.rs index 602c78a6034..3a04dc0a8b0 100644 --- a/rs/moq-net/src/fuzz.rs +++ b/rs/moq-net/src/fuzz.rs @@ -299,7 +299,7 @@ pub fn received(track: &track::Producer) { /// Fill the `groups` of `track` its cache misses, a run per FETCH, as a publisher answers a /// range FETCH, for the session bench. The returned guard keeps the filled groups cached. pub async fn fill_groups(track: &track::Consumer, groups: std::ops::Range) -> crate::Result { - track.query().await?; + track.info().await?; Ok(track.fill_groups(groups, 0).await) } diff --git a/rs/moq-net/src/ietf/adapter.rs b/rs/moq-net/src/ietf/adapter.rs index fa970a55a5c..1c27f798016 100644 --- a/rs/moq-net/src/ietf/adapter.rs +++ b/rs/moq-net/src/ietf/adapter.rs @@ -1555,8 +1555,8 @@ impl crate::transport::poll::Session for ControlStreamAdapter { self.inner.poll_closed(cx).map(|_| crate::Error::Closed) } - fn stats(&self) -> impl crate::transport::Stats { - self.inner.stats() + fn metrics(&self) -> impl crate::transport::Metrics { + self.inner.metrics() } } @@ -2428,7 +2428,7 @@ mod tests { use crate::{ coding::{Encode, Stream}, lite::test_transport::{Log, ScriptedSession, SinkSend}, - stats::{Bytes, Control as Class, Registry, Tier}, + stats::{Message as Class, Registry, Tier, Totals}, }; for version in [Version::Draft14, Version::Draft15, Version::Draft16] { let registry = Registry::new(Default::default()); @@ -2465,7 +2465,7 @@ mod tests { physical.write_all(&mut raw.clone()).await.unwrap(); assert_eq!( registry.snapshot().control(), - vec![(Tier::default(), Class::Fetch, Bytes { tx: size, rx: 0 })], + vec![(Tier::default(), Class::Fetch, Totals { tx: size, rx: 0 })], "{version:?}" ); assert_eq!(*log.writes.lock().unwrap(), raw); @@ -2479,7 +2479,7 @@ mod tests { virtual_stream.reader.decode::().await.unwrap(); assert_eq!( registry.snapshot().control(), - vec![(Tier::default(), Class::Fetch, Bytes { tx: size, rx: size })], + vec![(Tier::default(), Class::Fetch, Totals { tx: size, rx: size })], "virtual decode counted a physical frame twice: {version:?}" ); adapter.send_max_request_id(RequestId(123)); diff --git a/rs/moq-net/src/ietf/message.rs b/rs/moq-net/src/ietf/message.rs index 0ff229f5ceb..5458b65945f 100644 --- a/rs/moq-net/src/ietf/message.rs +++ b/rs/moq-net/src/ietf/message.rs @@ -2,16 +2,16 @@ use crate::coding::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder}; use super::Version; -pub(super) fn control(id: u64, version: Version) -> crate::stats::Control { +pub(super) fn control(id: u64, version: Version) -> crate::stats::Message { use super::*; - use crate::stats::Control; + use crate::stats::Message as Class; // Draft 14 reuses later drafts' NAMESPACE_DONE type for TRACK_STATUS_OK. if version == Version::Draft14 && (id == TrackStatusOk::ID_14 || id == TRACK_STATUS_ERROR_14) { - return Control::TrackInfo; + return Class::TrackInfo; } // Before draft 16, 0x02 updates only a subscription; later it is the shared REQUEST_UPDATE. if matches!(version, Version::Draft14 | Version::Draft15) && id == SubscribeUpdate::ID { - return Control::Subscribe; + return Class::Subscribe; } match id { PublishNamespace::ID @@ -23,19 +23,19 @@ pub(super) fn control(id: u64, version: Version) -> crate::stats::Control { | SubscribeNamespaceOk::ID | SubscribeNamespaceError::ID | UnsubscribeNamespace::ID - | NamespaceDone::ID => Control::Announce, - TrackStatus::ID | SubscribeTracks::ID | PublishSkipped::ID => Control::TrackInfo, + | NamespaceDone::ID => Class::Announce, + TrackStatus::ID | SubscribeTracks::ID | PublishSkipped::ID => Class::TrackInfo, Subscribe::ID | SubscribeOk::ID | Unsubscribe::ID | Publish::ID | PublishOk::ID | PublishError::ID - | PublishDone::ID => Control::Subscribe, - Fetch::ID | FetchOk::ID | FetchError::ID | FetchCancel::ID => Control::Fetch, - auth::Auth::ID | auth::AuthOk::ID | auth::AuthError::ID => Control::Auth, - GoAway::ID => Control::Goaway, - _ => Control::Other, + | PublishDone::ID => Class::Subscribe, + Fetch::ID | FetchOk::ID | FetchError::ID | FetchCancel::ID => Class::Fetch, + auth::Auth::ID | auth::AuthOk::ID | auth::AuthError::ID => Class::Auth, + GoAway::ID => Class::Goaway, + _ => Class::Other, } } @@ -121,25 +121,25 @@ impl Decode for T { #[cfg(test)] mod tests { use super::*; - use crate::stats::Control; + use crate::stats::Message as Class; /// Draft 14's track-status replies reuse type IDs later drafts give other classes. #[test] fn draft14_track_status_ids_are_track_info() { for id in [super::super::TrackStatusOk::ID_14, super::super::TRACK_STATUS_ERROR_14] { - assert_eq!(control(id, Version::Draft14), Control::TrackInfo); + assert_eq!(control(id, Version::Draft14), Class::TrackInfo); } assert_eq!( control(super::super::NamespaceDone::ID, Version::Draft16), - Control::Announce + Class::Announce ); assert_eq!( control(super::super::SubscribeUpdate::ID, Version::Draft15), - Control::Subscribe + Class::Subscribe ); // Shared replies and updates identify no request class. for id in [super::super::RequestOk::ID, super::super::SubscribeUpdate::ID] { - assert_eq!(control(id, Version::Draft16), Control::Other); + assert_eq!(control(id, Version::Draft16), Class::Other); } } } diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index 7c02f3f4296..4573e6eea00 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -195,7 +195,7 @@ async fn prepare_fetch( let reason = err.to_string(); (err, reason) }; - track.query().await.map_err(failed)?; + track.info().await.map_err(failed)?; // The cache's newest object is Largest Object while a live feed writes the track, or once // the track ended at its newest group. A fetch-only copy retains its publisher's report // independently. A joining FETCH ends where its subscription starts instead. @@ -393,7 +393,7 @@ async fn read_fetch( priority: i8, compression: bool, ) -> Result { - let info = track.query().await?; + let info = track.info().await?; let cached = track.peek_group(sequence); let wire = cached.as_ref().and_then(|group| group.wire()); if wire.as_ref().is_some_and(|wire| !wire.fetchable) { @@ -3581,7 +3581,7 @@ impl Publisher { // The requester abandoning the request is owed nothing. let info = { - let query = track.query(); + let query = track.info(); let mut finished = false; let mut messages = super::request_stream::Messages::new(self.session.clone(), self.control.client()); kio::wait(|waiter| { @@ -3889,7 +3889,7 @@ impl Publisher { path: &crate::PathOwned, suffix: crate::PathOwned, params: ietf::AdvertParams, - auth: Option, + auth: Option, ) -> Result { // Bounded, because an advertisement holds its stream for as long as the namespace // lives: a peer whose concurrent-stream limit we have filled refuses this open, and @@ -4009,7 +4009,7 @@ impl Publisher { ns: &Namespaces, suffix: &crate::PathOwned, path: &crate::PathOwned, - ) -> Option<(Advert, Option)> { + ) -> Option<(Advert, Option)> { let watch = ns.watched.get(suffix)?; let advert = match ns.permitted(path) { true => self.select(&watch.route, &ns.peer, ns.epochs), @@ -4028,7 +4028,7 @@ impl Publisher { } /// The `AUTHORIZATION TOKEN` a request names `auth` with, by value. - fn request_token(&self, auth: &crate::auth::Auth) -> Option { + fn request_token(&self, auth: &crate::auth::Credential) -> Option { let token = self.auth.token(auth)?; Some(super::token::RequestToken(crate::setup::Token { kind: crate::setup::Token::OUT_OF_BAND, @@ -6330,7 +6330,7 @@ struct NamespaceRequest { messages: super::request_stream::Messages, /// The auth the peer holds the request under: the one it opened with, or the one /// its last update carried. Held, so the credential stays presented while it does. - auth: Option, + auth: Option, /// Waiting in [`Namespaces::updates`] for a request ID. queued: bool, /// When to give up on the update in flight, which has no answer yet. @@ -11882,7 +11882,7 @@ mod serve_tests { let _track = broadcast.create_track("video", info).unwrap(); let (downstream, _sessions) = crate::lite::ietf::test_hop(&upstream, "room", [true, true]).await; let broadcast = downstream.consume().request_broadcast("room", None).await.unwrap(); - broadcast.track("video").unwrap().query().await.unwrap() + broadcast.track("video").unwrap().info().await.unwrap() } /// Draft 22 assigns 0x06 to SUBGROUP_DELIVERY_TIMEOUT, so a track property 0x06 crosses @@ -13782,8 +13782,8 @@ mod serve_tests { /// An auth handle whose session grant covers only `other`, so a SUBSCRIBE for `room` /// falls to its request token. The presented credential is kept alive by the returned - /// [`crate::auth::Auth`]. - fn auth_covering_other() -> (crate::auth::Link, crate::auth::Requests, crate::auth::Auth) { + /// [`crate::auth::Credential`]. + fn auth_covering_other() -> (crate::auth::Link, crate::auth::Requests, crate::auth::Credential) { let auth = crate::auth::Link::new(true); let requests = auth.handle().requests(); let cred = auth.present(bytes::Bytes::from_static(b"cred"), true).unwrap(); diff --git a/rs/moq-net/src/ietf/request_stream.rs b/rs/moq-net/src/ietf/request_stream.rs index ece95b58711..49d4528292b 100644 --- a/rs/moq-net/src/ietf/request_stream.rs +++ b/rs/moq-net/src/ietf/request_stream.rs @@ -592,7 +592,7 @@ mod tests { #[moq_clock::test] async fn request_stream_messages_count_without_their_type() { use crate::lite::test_transport::ScriptedSession; - use crate::stats::{Control, Registry, Tier}; + use crate::stats::{Message, Registry, Tier}; let registry = Registry::new(Default::default()); let stats = registry.tier(Tier::default()).session(""); let version = Version::Draft22; @@ -610,8 +610,8 @@ mod tests { let rows = registry.snapshot().control(); rows.into_iter().find(|row| row.1 == class).map(|row| row.2.rx) }; - assert_eq!(rx(Control::Goaway), Some(4)); - assert_eq!(rx(Control::Other), Some(2)); + assert_eq!(rx(Message::Goaway), Some(4)); + assert_eq!(rx(Message::Other), Some(2)); } #[moq_clock::test] diff --git a/rs/moq-net/src/ietf/session.rs b/rs/moq-net/src/ietf/session.rs index b9b618217f5..44255e53691 100644 --- a/rs/moq-net/src/ietf/session.rs +++ b/rs/moq-net/src/ietf/session.rs @@ -140,7 +140,7 @@ impl std::future::Future for Driver { } } -pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle, Option), Error> { +pub fn start(config: Config) -> Result<(Driver, crate::goaway::Handle, Option), Error> { let Config { runtime, stats, @@ -1494,7 +1494,7 @@ async fn read_goaways( let msg: ietf::GoAway = body.message(version)?; reader .stats() - .control(crate::stats::Control::Goaway, body.0.len() + 2, true); + .control(crate::stats::Message::Goaway, body.0.len() + 2, true); tracing::info!(message = ?msg, "received GOAWAY"); // Draft-18 names the first of our own Request IDs it did not process: even for a diff --git a/rs/moq-net/src/ietf/subscriber.rs b/rs/moq-net/src/ietf/subscriber.rs index 0c91a0c130d..ff359bafc5c 100644 --- a/rs/moq-net/src/ietf/subscriber.rs +++ b/rs/moq-net/src/ietf/subscriber.rs @@ -7809,7 +7809,7 @@ mod tests { Subscriber, crate::lite::test_transport::Log, crate::auth::Link, - Vec, + Vec, crate::util::TaskSet, ) { let session = crate::lite::test_transport::ScriptedSession::new(Vec::new()); @@ -7982,7 +7982,7 @@ mod tests { /// A subscriber whose grant from the peer covers everything until `auth.ended(0, ..)` /// revokes it, with the token handle to hold meanwhile. - fn revocable_auth() -> (crate::auth::Link, crate::auth::Auth) { + fn revocable_auth() -> (crate::auth::Link, crate::auth::Credential) { let auth = crate::auth::Link::new(true); let cred = auth.present(bytes::Bytes::from_static(b"cred"), true).unwrap(); auth.granted(0, crate::auth::Grant::all()); @@ -9168,7 +9168,7 @@ mod tests { if fetching { track.fetch_group(0, None).await.map(|_| ()) } else { - track.query().await.map(|_| ()) + track.info().await.map(|_| ()) } }); assert!(futures::poll!(pending.as_mut()).is_pending()); @@ -9251,7 +9251,7 @@ mod tests { let consumer = producer.consume(); let track = consumer.track("video").unwrap(); // Demand with nobody subscribing learns the track from TRACK_STATUS. - let mut query = std::pin::pin!(track.query()); + let mut query = std::pin::pin!(track.info()); assert!(futures::poll!(query.as_mut()).is_pending()); let request = dynamic.requested_track().await.expect("no track requested"); @@ -11245,7 +11245,7 @@ mod tests { ) -> ( Subscriber, crate::auth::Requests, - crate::auth::Auth, + crate::auth::Credential, origin::Consumer, crate::lite::test_transport::ScriptedSession, ) { @@ -11263,7 +11263,7 @@ mod tests { ) -> ( Subscriber, crate::auth::Requests, - crate::auth::Auth, + crate::auth::Credential, origin::Consumer, S, ) { diff --git a/rs/moq-net/src/lite/announce.rs b/rs/moq-net/src/lite/announce.rs index 834ed8423ac..2257b139852 100644 --- a/rs/moq-net/src/lite/announce.rs +++ b/rs/moq-net/src/lite/announce.rs @@ -244,7 +244,7 @@ impl Decode for Cost { impl Encode for AnnounceBroadcast<'_> { fn encode(&self, w: &mut Encoder<'_>, version: Version) -> Result<(), EncodeError> { - w.control = Some(crate::stats::Control::Announce); + w.control = Some(crate::stats::Message::Announce); if version.has_announce_id() { // Lite06+: outer type discriminator, then a size-prefixed body (like the // subscribe stream). The body varies by type. @@ -333,7 +333,7 @@ impl Encode for AnnounceBroadcast<'_> { impl Decode for AnnounceBroadcast<'_> { fn decode(buf: &mut Decoder<'_>, version: Version) -> Result { - buf.control = Some(crate::stats::Control::Announce); + buf.control = Some(crate::stats::Message::Announce); if version.has_announce_id() { // Lite06+: outer type, then a size-prefixed body decoded within its bounds. let typ = buf.varint()?; @@ -457,7 +457,7 @@ pub struct AnnounceRequest<'a> { } impl Message for AnnounceRequest<'_> { - const CONTROL: Option = Some(crate::stats::Control::Announce); + const CONTROL: Option = Some(crate::stats::Message::Announce); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { let prefix = Path::decode(r, version)?; let exclude_hop = match version.has_exclude_hop() { @@ -502,7 +502,7 @@ enum AnnounceStatus { impl Decode for AnnounceStatus { fn decode(r: &mut Decoder<'_>, _: Version) -> Result { - r.control = Some(crate::stats::Control::Announce); + r.control = Some(crate::stats::Message::Announce); let status = r.u8()?; status.try_into().map_err(|_| DecodeError::InvalidValue) } @@ -510,7 +510,7 @@ impl Decode for AnnounceStatus { impl Encode for AnnounceStatus { fn encode(&self, w: &mut Encoder<'_>, _: Version) -> Result<(), EncodeError> { - w.control = Some(crate::stats::Control::Announce); + w.control = Some(crate::stats::Message::Announce); w.u8(*self as u8); Ok(()) } @@ -559,7 +559,7 @@ impl AnnounceInit<'_> { } impl Message for AnnounceInit<'_> { - const CONTROL: Option = Some(crate::stats::Control::Announce); + const CONTROL: Option = Some(crate::stats::Message::Announce); // Published lite01/02 carry the whole initial set in one message. const MAX_SIZE: usize = 64 * 1024 * 1024; @@ -598,7 +598,7 @@ pub struct AnnounceOk { } impl Message for AnnounceOk { - const CONTROL: Option = Some(crate::stats::Control::Announce); + const CONTROL: Option = Some(crate::stats::Message::Announce); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { if !version.has_announce_ok() { return Err(DecodeError::Version); diff --git a/rs/moq-net/src/lite/auth.rs b/rs/moq-net/src/lite/auth.rs index c9e0ee7efca..0b042b79224 100644 --- a/rs/moq-net/src/lite/auth.rs +++ b/rs/moq-net/src/lite/auth.rs @@ -17,7 +17,7 @@ pub struct Auth { } impl Message for Auth { - const CONTROL: Option = Some(crate::stats::Control::Auth); + const CONTROL: Option = Some(crate::stats::Message::Auth); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { if !version.has_auth() { return Err(DecodeError::Version); @@ -50,7 +50,7 @@ pub struct AuthOk { const MAX_EXPIRES_MS: u64 = (1 << 53) - 1; impl Message for AuthOk { - const CONTROL: Option = Some(crate::stats::Control::Auth); + const CONTROL: Option = Some(crate::stats::Message::Auth); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { if !version.has_auth() { return Err(DecodeError::Version); @@ -99,7 +99,7 @@ pub struct AuthError { const MAX_REASON: usize = 8192; impl Message for AuthError { - const CONTROL: Option = Some(crate::stats::Control::Auth); + const CONTROL: Option = Some(crate::stats::Message::Auth); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { if !version.has_auth() { return Err(DecodeError::Version); diff --git a/rs/moq-net/src/lite/fetch.rs b/rs/moq-net/src/lite/fetch.rs index a793517dd8d..4d63673dfbc 100644 --- a/rs/moq-net/src/lite/fetch.rs +++ b/rs/moq-net/src/lite/fetch.rs @@ -29,7 +29,7 @@ pub struct Fetch<'a> { } impl Message for Fetch<'_> { - const CONTROL: Option = Some(crate::stats::Control::Fetch); + const CONTROL: Option = Some(crate::stats::Message::Fetch); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { match version { Version::Lite01 | Version::Lite02 => { diff --git a/rs/moq-net/src/lite/goaway.rs b/rs/moq-net/src/lite/goaway.rs index 2f93e59842e..27d89a86c9d 100644 --- a/rs/moq-net/src/lite/goaway.rs +++ b/rs/moq-net/src/lite/goaway.rs @@ -13,7 +13,7 @@ pub struct Goaway<'a> { } impl Message for Goaway<'_> { - const CONTROL: Option = Some(crate::stats::Control::Goaway); + const CONTROL: Option = Some(crate::stats::Message::Goaway); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { match version { Version::Lite01 | Version::Lite02 | Version::Lite03 => { diff --git a/rs/moq-net/src/lite/ietf.rs b/rs/moq-net/src/lite/ietf.rs index 7da53fd149f..7af29148219 100644 --- a/rs/moq-net/src/lite/ietf.rs +++ b/rs/moq-net/src/lite/ietf.rs @@ -317,7 +317,7 @@ impl Records { pub struct TrackProperties(pub Option>); impl Message for TrackProperties { - const CONTROL: Option = Some(crate::stats::Control::TrackInfo); + const CONTROL: Option = Some(crate::stats::Message::TrackInfo); fn encode_msg(&self, w: &mut Encoder<'_>, _: Version) -> Result<(), EncodeError> { // A track published over moq-lite is a lone 0. let Some(properties) = &self.0 else { @@ -1238,7 +1238,7 @@ mod hop_tests { let frame = next(&mut received).await.unwrap(); assert_eq!(&frame.payload.contiguous(0)[..], b"b"); assert!(next(&mut received).await.is_none()); - let info = moq_clock::timeout(TIMEOUT, copy.query()).await.unwrap().unwrap(); + let info = moq_clock::timeout(TIMEOUT, copy.info()).await.unwrap().unwrap(); assert_eq!( (info.max_age, info.timescale, info.priority, info.refresh), ( @@ -1391,7 +1391,7 @@ mod hop_tests { .unwrap(); let (downstream, sessions) = test_hop(&upstream, "room", [true, true]).await; let (copy, mut subscriber) = subscribe(&downstream).await; - let info = moq_clock::timeout(TIMEOUT, copy.query()).await.unwrap().unwrap(); + let info = moq_clock::timeout(TIMEOUT, copy.info()).await.unwrap().unwrap(); assert!(info.properties.is_none()); let mut group = track.append_group().unwrap(); @@ -1457,7 +1457,7 @@ mod hop_tests { }; assert_eq!((listed.timescale, listed.ietf()), (None, None), "{offer:?}"); let copy = broadcast.track("video").unwrap(); - let info = moq_clock::timeout(TIMEOUT, copy.query()).await.unwrap().unwrap(); + let info = moq_clock::timeout(TIMEOUT, copy.info()).await.unwrap().unwrap(); assert_eq!(info.timescale, negotiated.then_some(Timescale::MILLI), "{offer:?}"); assert_eq!( info.ietf(), diff --git a/rs/moq-net/src/lite/info.rs b/rs/moq-net/src/lite/info.rs index 687bd675829..d64eb8e9a13 100644 --- a/rs/moq-net/src/lite/info.rs +++ b/rs/moq-net/src/lite/info.rs @@ -8,7 +8,7 @@ pub struct SessionInfo { } impl Message for SessionInfo { - const CONTROL: Option = Some(crate::stats::Control::Session); + const CONTROL: Option = Some(crate::stats::Message::Session); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { match version { Version::Lite01 | Version::Lite02 => {} diff --git a/rs/moq-net/src/lite/message.rs b/rs/moq-net/src/lite/message.rs index 085e1057170..89b53b5a423 100644 --- a/rs/moq-net/src/lite/message.rs +++ b/rs/moq-net/src/lite/message.rs @@ -24,7 +24,7 @@ pub(super) fn decode_size(r: &mut Decoder<'_>, max: usize) -> Result = None; + const CONTROL: Option = None; /// The largest body this receiver accepts for this message. const MAX_SIZE: usize = MAX_MESSAGE_SIZE; diff --git a/rs/moq-net/src/lite/probe.rs b/rs/moq-net/src/lite/probe.rs index 041bd77d188..2ab94c6ec7f 100644 --- a/rs/moq-net/src/lite/probe.rs +++ b/rs/moq-net/src/lite/probe.rs @@ -13,7 +13,7 @@ pub struct Probe { } impl Message for Probe { - const CONTROL: Option = Some(crate::stats::Control::Probe); + const CONTROL: Option = Some(crate::stats::Message::Probe); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { match version { Version::Lite01 | Version::Lite02 => { diff --git a/rs/moq-net/src/lite/publisher.rs b/rs/moq-net/src/lite/publisher.rs index 783ca727a91..9c074712e60 100644 --- a/rs/moq-net/src/lite/publisher.rs +++ b/rs/moq-net/src/lite/publisher.rs @@ -1797,7 +1797,7 @@ impl Drop for RequestServe { /// The open stream is interest in the track: the query that answered it stays until the /// requester closes its side, so demand holds while the requester moves on to SUBSCRIBE. struct TrackInfoServe { - querying: track::Querying, + querying: track::Resolving, } impl Request for TrackInfoServe { @@ -1816,7 +1816,7 @@ impl Request for TrackInfoServe { } fn start(_: &Shared, msg: Self::Message, broadcast: crate::broadcast::Consumer) -> Result { - let querying = broadcast.track(&msg.track)?.query().into_inner(); + let querying = broadcast.track(&msg.track)?.info().into_inner(); Ok(Self { querying }) } @@ -1918,7 +1918,7 @@ enum SubscribeServe { /// Boxed: the request is far larger than the other states' handles. msg: Box>, track: track::Consumer, - querying: track::Querying, + querying: track::Resolving, /// The newest group when the SUBSCRIBE arrived; see [`cursor_floor`]. latest: Option, update: Option, @@ -1967,7 +1967,7 @@ impl Request for SubscribeServe { let track = broadcast.track(&msg.track)?; let latest = track.latest_sequence(); if Bounds::has_time(&msg.ranges) { - let querying = track.query().into_inner(); + let querying = track.info().into_inner(); return Ok(Self::Query { msg: Box::new(msg), track, diff --git a/rs/moq-net/src/lite/session.rs b/rs/moq-net/src/lite/session.rs index 9ed4075379b..41c53bf82b9 100644 --- a/rs/moq-net/src/lite/session.rs +++ b/rs/moq-net/src/lite/session.rs @@ -24,7 +24,7 @@ pub(crate) struct SessionStart { /// The session's AUTH tokens and grants, stored on the public [`crate::Session`]. pub auth: crate::auth::Link, /// The connection credential presented on `auth`, stored on the public [`crate::Session`]. - pub credential: Option, + pub credential: Option, /// The implementation the peer's SETUP advertised, stored on the public [`crate::Session`]. pub peer_implementation: crate::setup::PeerImplementation, } @@ -523,7 +523,7 @@ struct Present { /// Whether the first poll decided who answers the peer's tokens. started: bool, /// The connection's own credential, held for the life of the session. - _setup: Option, + _setup: Option, } impl Present { @@ -1032,7 +1032,7 @@ mod tests { /// Run a client session on a shared handle over `transport` for five simulated seconds, /// presenting one token, and return it after checking the session still runs. - async fn present_on_shared_handle(transport: ScriptedSession) -> crate::auth::Auth { + async fn present_on_shared_handle(transport: ScriptedSession) -> crate::auth::Credential { let handle = crate::auth::Handle::new(); let start = start(Config { runtime: crate::time::sim(), diff --git a/rs/moq-net/src/lite/setup.rs b/rs/moq-net/src/lite/setup.rs index f5c9508ee7f..4268b052d62 100644 --- a/rs/moq-net/src/lite/setup.rs +++ b/rs/moq-net/src/lite/setup.rs @@ -62,10 +62,10 @@ impl ProbeLevel { /// both qualify: their RTT comes from the handshake, which has already happened. #[cfg(feature = "async")] pub fn detect(session: &crate::driver::Transport) -> Self { - use crate::transport::Stats as _; + use crate::transport::Metrics as _; use crate::transport::poll::Session as _; - let stats = session.stats(); - match stats.estimated_send_rate().is_some() || stats.rtt().is_some() { + let metrics = session.metrics(); + match metrics.estimated_send_rate().is_some() || metrics.rtt().is_some() { true => Self::Report, false => Self::None, } @@ -203,7 +203,7 @@ pub struct Setup { } impl Message for Setup { - const CONTROL: Option = Some(crate::stats::Control::Session); + const CONTROL: Option = Some(crate::stats::Message::Session); const MAX_SIZE: usize = crate::setup::MAX_SETUP_SIZE; fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { @@ -267,7 +267,7 @@ pub(super) struct ReceivedSetup { } impl Message for ReceivedSetup { - const CONTROL: Option = Some(crate::stats::Control::Session); + const CONTROL: Option = Some(crate::stats::Message::Session); const MAX_SIZE: usize = Setup::MAX_SIZE; fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { diff --git a/rs/moq-net/src/lite/subscribe.rs b/rs/moq-net/src/lite/subscribe.rs index a7c401f7a18..c71c78eb889 100644 --- a/rs/moq-net/src/lite/subscribe.rs +++ b/rs/moq-net/src/lite/subscribe.rs @@ -105,7 +105,7 @@ impl Version { } impl Message for Subscribe<'_> { - const CONTROL: Option = Some(crate::stats::Control::Subscribe); + const CONTROL: Option = Some(crate::stats::Message::Subscribe); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { let id = r.varint()?; let broadcast = Path::decode(r, version)?; @@ -425,7 +425,7 @@ pub struct SubscribeOk { } impl Message for SubscribeOk { - const CONTROL: Option = Some(crate::stats::Control::Subscribe); + const CONTROL: Option = Some(crate::stats::Message::Subscribe); fn encode_msg(&self, w: &mut Encoder<'_>, version: Version) -> Result<(), EncodeError> { match version { Version::Lite01 => { @@ -495,7 +495,7 @@ pub struct SubscribeStart { } impl Message for SubscribeStart { - const CONTROL: Option = Some(crate::stats::Control::Subscribe); + const CONTROL: Option = Some(crate::stats::Message::Subscribe); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { if !version.has_track_stream() { return Err(DecodeError::Version); @@ -540,7 +540,7 @@ pub struct SubscribeEnd { } impl Message for SubscribeEnd { - const CONTROL: Option = Some(crate::stats::Control::Subscribe); + const CONTROL: Option = Some(crate::stats::Message::Subscribe); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { if !version.has_track_stream() { return Err(DecodeError::Version); @@ -574,7 +574,7 @@ pub struct SubscribeUpdate { } impl Message for SubscribeUpdate { - const CONTROL: Option = Some(crate::stats::Control::Subscribe); + const CONTROL: Option = Some(crate::stats::Message::Subscribe); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { match version { Version::Lite01 | Version::Lite02 => { @@ -670,7 +670,7 @@ impl SubscribeDrop { } impl Message for SubscribeDrop { - const CONTROL: Option = Some(crate::stats::Control::Subscribe); + const CONTROL: Option = Some(crate::stats::Message::Subscribe); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { match version { Version::Lite01 | Version::Lite02 => { diff --git a/rs/moq-net/src/lite/test_transport.rs b/rs/moq-net/src/lite/test_transport.rs index 81d78ccbcf2..7ff0f7b66e1 100644 --- a/rs/moq-net/src/lite/test_transport.rs +++ b/rs/moq-net/src/lite/test_transport.rs @@ -585,7 +585,7 @@ impl poll::Session for DeadStreamSession { self.log.poll_closed(self.park.hold(cx)) } - fn stats(&self) -> impl crate::transport::Stats { + fn metrics(&self) -> impl crate::transport::Metrics { SinkStats::default() } } @@ -842,7 +842,7 @@ impl poll::Session for SinkSession { self.log.poll_closed(self.park.hold(cx)) } - fn stats(&self) -> impl crate::transport::Stats { + fn metrics(&self) -> impl crate::transport::Metrics { *self.stats.lock().unwrap() } @@ -873,7 +873,7 @@ impl SinkStats { } } -impl crate::transport::Stats for SinkStats { +impl crate::transport::Metrics for SinkStats { fn estimated_send_rate(&self) -> Option { self.estimated_send_rate } @@ -1249,7 +1249,7 @@ impl poll::Session for ScriptedSession { self.log.poll_closed(self.park.hold(cx)) } - fn stats(&self) -> impl crate::transport::Stats { + fn metrics(&self) -> impl crate::transport::Metrics { self.stats } } diff --git a/rs/moq-net/src/lite/track.rs b/rs/moq-net/src/lite/track.rs index 0143105cdf5..372324f4f1f 100644 --- a/rs/moq-net/src/lite/track.rs +++ b/rs/moq-net/src/lite/track.rs @@ -24,7 +24,7 @@ pub struct Track<'a> { } impl Message for Track<'_> { - const CONTROL: Option = Some(crate::stats::Control::TrackInfo); + const CONTROL: Option = Some(crate::stats::Message::TrackInfo); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { if !version.has_track_stream() { return Err(DecodeError::Version); @@ -134,7 +134,7 @@ impl Framing { } impl Message for TrackInfo { - const CONTROL: Option = Some(crate::stats::Control::TrackInfo); + const CONTROL: Option = Some(crate::stats::Message::TrackInfo); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { if !version.has_track_stream() { return Err(DecodeError::Version); diff --git a/rs/moq-net/src/lite/tracks.rs b/rs/moq-net/src/lite/tracks.rs index 4287476e211..5b7124386df 100644 --- a/rs/moq-net/src/lite/tracks.rs +++ b/rs/moq-net/src/lite/tracks.rs @@ -24,7 +24,7 @@ pub struct Tracks<'a> { } impl Message for Tracks<'_> { - const CONTROL: Option = Some(crate::stats::Control::TrackInfo); + const CONTROL: Option = Some(crate::stats::Message::TrackInfo); fn decode_msg(r: &mut Decoder<'_>, version: Version) -> Result { if !version.has_tracks() { return Err(DecodeError::Version); @@ -61,7 +61,7 @@ pub enum TracksEvent<'a> { impl Encode for TracksEvent<'_> { fn encode(&self, w: &mut Encoder<'_>, version: Version) -> Result<(), EncodeError> { - w.control = Some(crate::stats::Control::TrackInfo); + w.control = Some(crate::stats::Message::TrackInfo); if !version.has_tracks() { return Err(EncodeError::Version); } @@ -90,7 +90,7 @@ impl Encode for TracksEvent<'_> { impl Decode for TracksEvent<'_> { fn decode(r: &mut Decoder<'_>, version: Version) -> Result { - r.control = Some(crate::stats::Control::TrackInfo); + r.control = Some(crate::stats::Message::TrackInfo); if !version.has_tracks() { return Err(DecodeError::Version); } diff --git a/rs/moq-net/src/model/bandwidth.rs b/rs/moq-net/src/model/bandwidth.rs index 0549e75f69c..ecafcde5693 100644 --- a/rs/moq-net/src/model/bandwidth.rs +++ b/rs/moq-net/src/model/bandwidth.rs @@ -180,7 +180,7 @@ impl Weak { /// The reservations also set the session's probe target: the sum of every live /// reservation's ceiling, demanded or not, so a sender that stopped for lack of /// bandwidth keeps asking the connection for its room. A session probes for its own -/// allocator, so take it from `Session::bandwidth` (with the `async` feature) rather +/// allocator, so take it from `Session::allocator` (with the `async` feature) rather /// than building one: an allocator from [`new`](Self::new) divides an estimate but /// probes for nothing. /// @@ -196,7 +196,7 @@ impl Allocator { /// /// For an estimate that is not a session's, such as a test's or another /// reservation's slice. A session's own comes from - /// `Session::bandwidth` with the `async` feature. + /// `Session::allocator` with the `async` feature. pub fn new(estimate: Consumer) -> Self { Self { estimate, @@ -298,7 +298,7 @@ impl Allocator { /// released when the track closes either way, since a [`track::Demand`] is a weak /// handle and reserving never keeps a track alive. /// - /// Read the current slice through [`Reservation::consumer`], which reports `None` + /// Read the current slice through [`Reservation::consume`], which reports `None` /// while the connection has no estimate, telling a sender to hold its current rate /// rather than encode at zero. While nothing is subscribed to the track it reports /// the slice the track would get back, without claiming it from the others. @@ -363,7 +363,7 @@ impl Reservation { /// /// Stateless, unlike [`Consumer::poll_changed`], which carries a cursor over what it last /// reported and so needs a handle of its own. - pub fn peek(&self) -> Option { + pub fn rate(&self) -> Option { self.share.grant() } @@ -371,7 +371,7 @@ impl Reservation { /// /// Cloneable and independent of the reservation: once the reservation is dropped /// these report `None`, the same "hold your rate" a missing estimate reports. - pub fn consumer(&self) -> Consumer { + pub fn consume(&self) -> Consumer { Consumer { inner: Inner::Share(Box::new(self.share.clone())), last: None, @@ -388,7 +388,7 @@ impl Reservation { /// picture moved again. /// /// Does nothing once every [`Allocator`] is gone, since there is then nothing left - /// dividing anything; a reader learns that from its [`consumer`](Self::consumer). + /// dividing anything; a reader learns that from its [`consumer`](Self::consume). pub fn update(&self, max: Rate) { let Some(registry) = self.registry.upgrade() else { return; @@ -906,7 +906,7 @@ mod tests { let (_first_broadcast, first) = track(VIDEO); let _first_sub = first.subscribe(None); let first = allocator.reserve(&first.demand(), bps(4_000_000)); - let mut first_share = first.consumer(); + let mut first_share = first.consume(); estimate.set(Some(bps(2_000_000))).unwrap(); // Alone, it gets everything it asked for that the link can carry. @@ -919,7 +919,7 @@ mod tests { let second_share = allocator.reserve(&second.demand(), bps(4_000_000)); assert_eq!(first_share.changed().await.unwrap(), Some(bps(1_000_000))); - assert_eq!(second_share.peek(), Some(bps(1_000_000))); + assert_eq!(second_share.rate(), Some(bps(1_000_000))); } /// An unwatched track releases its reservation to the others, since `publish_capture` @@ -938,14 +938,14 @@ mod tests { let (_idle_broadcast, idle) = track(VIDEO); let idle_share = allocator.reserve(&idle.demand(), bps(4_000_000)); - assert_eq!(watched_share.peek(), Some(bps(2_000_000))); + assert_eq!(watched_share.rate(), Some(bps(2_000_000))); // What it would get if a viewer joined: an even split with the watched track. - assert_eq!(idle_share.peek(), Some(bps(1_000_000))); + assert_eq!(idle_share.rate(), Some(bps(1_000_000))); // It joins, and the split happens. let _idle_sub = idle.subscribe(None); - assert_eq!(watched_share.peek(), Some(bps(1_000_000))); - assert_eq!(idle_share.peek(), Some(bps(1_000_000))); + assert_eq!(watched_share.rate(), Some(bps(1_000_000))); + assert_eq!(idle_share.rate(), Some(bps(1_000_000))); } /// Demand transitions have to wake a parked share, not just change what a later @@ -960,7 +960,7 @@ mod tests { let (_mine_broadcast, mine) = track(VIDEO); let _mine_sub = mine.subscribe(None); let mine_share_reserved = allocator.reserve(&mine.demand(), bps(4_000_000)); - let mut mine_share = mine_share_reserved.consumer(); + let mut mine_share = mine_share_reserved.consume(); let (_sibling_broadcast, sibling) = track(VIDEO); let sibling_sub = sibling.subscribe(None); @@ -1020,7 +1020,7 @@ mod tests { let (_broadcast, track) = track(VIDEO); let _sub = track.subscribe(None); let share_reserved = allocator.reserve(&track.demand(), bps(4_000_000)); - let mut share = share_reserved.consumer(); + let mut share = share_reserved.consume(); estimate.set(Some(bps(10_000_000))).unwrap(); assert_eq!(share.changed().await.unwrap(), Some(bps(4_000_000))); @@ -1048,7 +1048,7 @@ mod tests { let (_mine_broadcast, mine) = track(VIDEO); let _mine_sub = mine.subscribe(None); let share_reserved = allocator.reserve(&mine.demand(), bps(4_000_000)); - let mut share = share_reserved.consumer(); + let mut share = share_reserved.consume(); let (_sibling_broadcast, sibling) = track(VIDEO); let sibling_sub = sibling.subscribe(None); @@ -1073,7 +1073,7 @@ mod tests { let (_broadcast, track) = track(VIDEO); let _sub = track.subscribe(None); let share_reserved = allocator.reserve(&track.demand(), bps(4_000_000)); - let mut share = share_reserved.consumer(); + let mut share = share_reserved.consume(); estimate.set(Some(bps(2_000_000))).unwrap(); assert_eq!(share.changed().await.unwrap(), Some(bps(2_000_000))); @@ -1122,16 +1122,16 @@ mod tests { let (_second_broadcast, second) = track(VIDEO); let _second_sub = second.subscribe(None); let second_reserved = allocator.reserve(&second.demand(), bps(4_000_000)); - assert_eq!(second_reserved.peek(), Some(bps(1_000_000))); + assert_eq!(second_reserved.rate(), Some(bps(1_000_000))); // A read handle is not the claim: the reservation outliving it is what keeps the // room, and the reservation going away is what returns it. - let mut orphan = first_reserved.consumer(); + let mut orphan = first_reserved.consume(); assert_eq!(orphan.changed().await.unwrap(), Some(bps(1_000_000))); drop(first_reserved); assert_eq!(allocator.registry.read().entries.len(), 1); - assert_eq!(second_reserved.peek(), Some(bps(2_000_000))); + assert_eq!(second_reserved.rate(), Some(bps(2_000_000))); // The orphaned reader is woken and told, rather than being left parked on a slice // that will never move again. It reports the same "hold your rate" as a missing @@ -1158,19 +1158,19 @@ mod tests { let large_reserved = allocator.reserve(&large.demand(), bps(8_000_000)); // Max-min fair: the small claim is satisfied in full, the rest goes to the other. - assert_eq!(small_reserved.peek(), Some(bps(1_000_000))); - assert_eq!(large_reserved.peek(), Some(bps(5_000_000))); + assert_eq!(small_reserved.rate(), Some(bps(1_000_000))); + assert_eq!(large_reserved.rate(), Some(bps(5_000_000))); // It reopens at a mode that can use much more, and the split follows without a // second entry appearing. small_reserved.update(bps(4_000_000)); assert_eq!(allocator.registry.read().entries.len(), 2); - assert_eq!(small_reserved.peek(), Some(bps(3_000_000))); - assert_eq!(large_reserved.peek(), Some(bps(3_000_000))); + assert_eq!(small_reserved.rate(), Some(bps(3_000_000))); + assert_eq!(large_reserved.rate(), Some(bps(3_000_000))); // And back down, which has to release the difference rather than hold it. small_reserved.update(bps(1_000_000)); - assert_eq!(large_reserved.peek(), Some(bps(5_000_000))); + assert_eq!(large_reserved.rate(), Some(bps(5_000_000))); } /// Collected-language callers can relinquish a ceiling before their retained @@ -1190,20 +1190,20 @@ mod tests { let (_sibling_broadcast, sibling) = track(VIDEO); let _sibling_sub = sibling.subscribe(None); let sibling = allocator.reserve(&sibling.demand(), bps(4_000_000)); - assert_eq!(sibling.peek(), Some(bps(1_000_000))); + assert_eq!(sibling.rate(), Some(bps(1_000_000))); assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(12_000_000))); retired.update(Rate::ZERO); - assert_eq!(retired.peek(), Some(Rate::ZERO)); - assert_eq!(replacement.peek(), Some(bps(1_500_000))); - assert_eq!(sibling.peek(), Some(bps(1_500_000))); + assert_eq!(retired.rate(), Some(Rate::ZERO)); + assert_eq!(replacement.rate(), Some(bps(1_500_000))); + assert_eq!(sibling.rate(), Some(bps(1_500_000))); assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(8_000_000))); retired.update(Rate::ZERO); assert!(target.poll_changed(&waiter).is_pending()); // The registration remains usable, so an encoder may resume in place. retired.update(bps(4_000_000)); - assert_eq!(sibling.peek(), Some(bps(1_000_000))); + assert_eq!(sibling.rate(), Some(bps(1_000_000))); assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(12_000_000))); assert!(encoder.demand().is_used()); } @@ -1220,7 +1220,7 @@ mod tests { let (_broadcast, producer) = track(VIDEO); let _sub = producer.subscribe(None); let reserved = allocator.reserve(&producer.demand(), bps(1_000_000)); - let mut share = reserved.consumer(); + let mut share = reserved.consume(); assert_eq!(share.changed().await.unwrap(), Some(bps(1_000_000))); let (woken, waiter) = Woken::new(); @@ -1242,7 +1242,7 @@ mod tests { let (_broadcast, producer) = track(VIDEO); let _sub = producer.subscribe(None); let share_reserved = allocator.reserve(&producer.demand(), bps(4_000_000)); - let mut share = share_reserved.consumer(); + let mut share = share_reserved.consume(); drop(allocator); drop(estimate); @@ -1326,7 +1326,7 @@ mod tests { let (_broadcast, producer) = track(VIDEO); let _sub = producer.subscribe(None); let reservation = allocator.reserve(&producer.demand(), bps(4_000_000)); - let mut grant = reservation.consumer(); + let mut grant = reservation.consume(); let (woken, waiter) = Woken::new(); assert!(matches!(grant.poll_changed(&waiter), Poll::Ready(Ok(Some(rate))) if rate == bps(2_000_000))); assert!(!grant.probed()); diff --git a/rs/moq-net/src/model/group.rs b/rs/moq-net/src/model/group.rs index 419a7f5d103..6b53f33260d 100644 --- a/rs/moq-net/src/model/group.rs +++ b/rs/moq-net/src/model/group.rs @@ -2177,6 +2177,7 @@ impl Handle { Demand { sequence: self.info.sequence, state: self.state.weak(), + prev: None, } } @@ -2207,11 +2208,24 @@ fn settle(poll: Poll, kio::Ref<'_, GroupState>>>) /// A cloneable, watch-only handle to a group's readers. /// /// Once every handle to a finished group is gone, demand waits end with -/// [`Error::Dropped`]; an aborted group's keep its abort reason. -#[derive(Clone)] +/// [`Error::Dropped`]; an aborted group's keep its abort reason. Each clone watches on +/// its own, so its first [`poll_wanted_changed`](Self::poll_wanted_changed) reports the +/// current value. pub struct Demand { sequence: u64, state: kio::ProducerWeak, + // The value `poll_wanted_changed` last returned, or `None` before it returned any. + prev: Option, +} + +impl Clone for Demand { + fn clone(&self) -> Self { + Self { + sequence: self.sequence, + state: self.state.clone(), + prev: None, + } + } } impl Demand { @@ -2221,30 +2235,34 @@ impl Demand { } /// Whether the group is open and has readers right now. - pub fn is_used(&self) -> bool { + pub fn wanted(&self) -> bool { !self.state.is_closed() && self.state.is_used() } - /// Wait until at least one reader needs the group. - #[cfg(feature = "async")] - pub async fn used(&self) -> Result<()> { - kio::wait(|waiter| self.poll_used(waiter)).await - } - - /// Wait until no reader needs the group. + /// Return [`wanted`](Self::wanted) once it differs from what this handle last returned: + /// immediately on the first call, then on each change. Errors once the group is closed. #[cfg(feature = "async")] - pub async fn unused(&self) -> Result<()> { - kio::wait(|waiter| self.poll_unused(waiter)).await - } - - /// Poll until at least one reader needs the group. - pub fn poll_used(&self, waiter: &kio::Waiter) -> Poll> { - self.state.poll_used(waiter).map_err(|_| self.abort_reason()) + pub async fn wanted_changed(&mut self) -> Result { + kio::wait(|waiter| self.poll_wanted_changed(waiter)).await } - /// Poll until no reader needs the group. - pub fn poll_unused(&self, waiter: &kio::Waiter) -> Poll> { - self.state.poll_unused(waiter).map_err(|_| self.abort_reason()) + /// Poll for [`wanted`](Self::wanted) to differ from what this handle last returned. + pub fn poll_wanted_changed(&mut self, waiter: &kio::Waiter) -> Poll> { + loop { + if self.state.is_closed() { + return Poll::Ready(Err(self.abort_reason())); + } + let wanted = self.state.is_used(); + if self.prev != Some(wanted) { + self.prev = Some(wanted); + return Poll::Ready(Ok(wanted)); + } + // Wait for the opposite; closing fails either wait, which errors above. + let _ = ready!(match wanted { + true => self.state.poll_unused(waiter), + false => self.state.poll_used(waiter), + }); + } } /// Wait until the group's outcome is final: `Ok` once finished, or the abort error. @@ -3513,22 +3531,34 @@ mod test { } #[test] - #[cfg(feature = "async")] fn demand_watches_readers_without_keeping_the_group_alive() { + let waiter = kio::Waiter::noop(); let producer = Info { sequence: 7 }.produce(); - let demand = producer.demand(); + let mut demand = producer.demand(); assert_eq!(demand.sequence(), 7); - assert!(!demand.is_used()); + assert!(!demand.wanted()); + assert!(matches!(demand.poll_wanted_changed(&waiter), Poll::Ready(Ok(false)))); + assert!(demand.poll_wanted_changed(&waiter).is_pending()); + let first = producer.consume(); let second = first.clone(); - assert!(demand.is_used()); + assert!(demand.wanted()); + assert!(matches!(demand.poll_wanted_changed(&waiter), Poll::Ready(Ok(true)))); drop(first); - assert!(demand.poll_unused(&kio::Waiter::noop()).is_pending()); + assert!(demand.poll_wanted_changed(&waiter).is_pending()); + + // A clone reports the current value first, whatever the original last returned. + let mut clone = demand.clone(); + assert!(matches!(clone.poll_wanted_changed(&waiter), Poll::Ready(Ok(true)))); + drop(second); - assert!(matches!(demand.poll_unused(&kio::Waiter::noop()), Poll::Ready(Ok(())))); + assert!(matches!(demand.poll_wanted_changed(&waiter), Poll::Ready(Ok(false)))); drop(producer); - assert!(!demand.is_used()); - assert!(matches!(demand.used().now_or_never(), Some(Err(Error::Dropped)))); + assert!(!demand.wanted()); + assert!(matches!( + demand.poll_wanted_changed(&waiter), + Poll::Ready(Err(Error::Dropped)) + )); } /// The fixed overhead covers the first segment of frame slots, and each later segment @@ -4753,7 +4783,7 @@ mod test { let group = frame.group(); assert_eq!(group.sequence, 3); assert_eq!(group.frame_count(), 2, "the open frame counts"); - assert!(group.demand().is_used()); + assert!(group.demand().wanted()); assert!(group.poll_closed(&kio::Waiter::noop()).is_pending()); frame.write(Bytes::from_static(b"b")).unwrap(); diff --git a/rs/moq-net/src/model/origin.rs b/rs/moq-net/src/model/origin.rs index af40c466e76..cb455f97a14 100644 --- a/rs/moq-net/src/model/origin.rs +++ b/rs/moq-net/src/model/origin.rs @@ -513,7 +513,7 @@ pub struct Route { /// REQUEST_UPDATE from draft 16, or ends and makes it again before. A handle passed to /// `Client::with_auth` presents it on every session it backs, so the route keeps it /// across a reconnect. Local, like [`Self::source`]: a relay never forwards it. - pub auth: Option, + pub auth: Option, /// The announcing session's declared or assigned identity. /// @@ -574,7 +574,7 @@ impl Route { } /// Set the credential the advertising request carries; see [`Self::auth`]. - pub fn with_auth(mut self, auth: crate::auth::Auth) -> Self { + pub fn with_auth(mut self, auth: crate::auth::Credential) -> Self { self.auth = Some(auth); self } @@ -698,7 +698,13 @@ fn route_order<'a>( /// The `(hops, cost, source, epoch, auth)` metadata an announce cursor delivers alongside a /// prefix. -type RouteMeta = (Hops, Cost, Source, Option, Option); +type RouteMeta = ( + Hops, + Cost, + Source, + Option, + Option, +); /// The earlier of two optional deadlines. fn earliest(a: Option, b: Option) -> Option { @@ -1230,7 +1236,7 @@ struct RouteEntry { hops: Hops, cost: Cost, /// The auth the request advertising the route carries; see [`Route::auth`]. - auth: Option, + auth: Option, /// The rank of the link the entry arrived on; see [`Producer::with_preference`]. preference: Preference, /// The announcing session's declared or assigned identity. Split-horizon @@ -3049,7 +3055,7 @@ struct Asked { copy: track::Consumer, /// The front's own demand on the copy, held for as long as the front holds the copy: a /// bare handle is no demand, so this stands in for the readers' queries and fetches. - query: track::Querying, + query: track::Resolving, info: Option, /// Some sessions only learn a track's info by subscribing (moq-transport's /// SUBSCRIBE_OK), and read the demand only then, so the readers' demand rides the @@ -3079,7 +3085,7 @@ struct TrackIo { staged: Option, /// The source whose copy serves the track, the copy, and the query holding it; plus the /// subscription that query made. - copy: Option<(u64, track::Consumer, track::Querying)>, + copy: Option<(u64, track::Consumer, track::Resolving)>, held: Option>, /// The last copy ended because its session closed locally: a close, not an /// error, so the track ends cleanly if nothing takes over. @@ -3150,7 +3156,7 @@ struct InFlight { // Kept for its readers: the logical track, the query holding its copy, and the copy's // subscription. accepted: Option, - _copy: Option, + _copy: Option, _held: Option>, } @@ -3558,8 +3564,8 @@ async fn serve_front(task: FrontTask) -> Vec { lookup.subscribe(io.routes.subscription(demand, subscribers)) }); let query = match &sub { - Some(sub) => sub.query(), - None => lookup.query().into_inner(), + Some(sub) => sub.info(), + None => lookup.info().into_inner(), }; let copy = query.track(); io.query = Some(Asked { @@ -11781,7 +11787,7 @@ mod tests { // Reopening the aborted logical track must not forget the broadcast's metadata. let reopened = rig.resolved.track("video").unwrap(); - assert!(matches!(reopened.query().await, Err(Error::Unsupported))); + assert!(matches!(reopened.info().await, Err(Error::Unsupported))); assert!(matches!(reopened.subscribe(None).await, Err(Error::Unsupported))); } } diff --git a/rs/moq-net/src/model/track.rs b/rs/moq-net/src/model/track.rs index 2dd189c59d7..2f4fb6994f7 100644 --- a/rs/moq-net/src/model/track.rs +++ b/rs/moq-net/src/model/track.rs @@ -4179,8 +4179,8 @@ impl ArrivalRead<'_> { /// A lazy handle to a single track within a broadcast. /// /// Obtained from [`broadcast::Consumer::track`]. Holding it sends nothing and is not -/// [`Demand`]: the track is requested, and counts as demanded, only while a -/// [`query`](Self::query), [`subscribe`](Self::subscribe) (a live, ongoing stream of +/// [`Demand`]: the track is requested, and counts as demanded, only while an +/// [`info`](Self::info), [`subscribe`](Self::subscribe) (a live, ongoing stream of /// groups), or [`fetch_group`](Self::fetch_group) (one group) made from it is held. The /// same handle can be used any number of times, and clones are cheap. #[derive(Clone)] @@ -4771,8 +4771,8 @@ impl Consumer { /// for the producer to [`Request::accept`] the track (a wire TRACK_INFO round-trip /// for a relay), and errors with the track's abort error if it closes first. /// [`Subscriber::info`] is the already-resolved counterpart. - pub fn query(&self) -> kio::Pending { - kio::Pending::new(Querying { + pub fn info(&self) -> kio::Pending { + kio::Pending::new(Resolving { name: self.name.clone(), broadcast: self.broadcast.clone(), state: self.resolve(None).0, @@ -4894,9 +4894,9 @@ pub struct Subscribing { } impl Subscribing { - /// Query the same track with this subscription already registered. - pub(super) fn query(&self) -> Querying { - Querying { + /// Resolve the same track's info with this subscription already registered. + pub(super) fn info(&self) -> Resolving { + Resolving { name: self.name.clone(), broadcast: self.broadcast.clone(), state: self.state.clone(), @@ -4953,19 +4953,19 @@ impl kio::Task for Subscribing { } } -/// The pollable state of a [`Consumer::query`]; awaited via the +/// The pollable state of a [`Consumer::info`]; awaited via the /// [`kio::Pending`] wrapper. /// /// Counts as the track's [`Demand`] while held, answered or not. -pub struct Querying { +pub struct Resolving { name: Arc, broadcast: Arc, state: kio::Consumer, stats: stats::Scope, } -impl Querying { - /// A handle on the track instance this query asked, whatever its broadcast serves later. +impl Resolving { + /// A handle on the track instance this resolves, whatever its broadcast serves later. pub fn track(&self) -> Consumer { Consumer { name: self.name.clone(), @@ -4985,7 +4985,7 @@ impl Querying { } } -impl kio::Task for Querying { +impl kio::Task for Resolving { type Output = Result; fn poll(&mut self, waiter: &kio::Waiter) -> Poll { @@ -6865,7 +6865,7 @@ fn refuse_untimed(info: &Info, subscription: &Subscription) -> Result<()> { impl Subscriber { /// The track's [`Info`], resolved when the subscription was established. /// - /// Free, unlike [`Consumer::query`]: subscribing already waited for the info + /// Free, unlike [`Consumer::info`]: subscribing already waited for the info /// (SUBSCRIBE_OK on the wire), so a subscriber always has it. pub fn info(&self) -> &Info { &self.info @@ -16857,7 +16857,7 @@ mod test { let demand = request.demand(); let consumer = request.consume(); assert!(!demand.is_used(), "a bare handle is not demand"); - let query = consumer.query(); + let query = consumer.info(); assert!(demand.is_used()); assert!(dynamic.demand().is_used()); drop(query); diff --git a/rs/moq-net/src/server.rs b/rs/moq-net/src/server.rs index 99c6e74bfad..de0b6310dcb 100644 --- a/rs/moq-net/src/server.rs +++ b/rs/moq-net/src/server.rs @@ -570,7 +570,7 @@ impl PausedIetfModern { version, peer_setup, } = self; - server.stats.control(stats::Control::Session, peer_setup.size, true); + server.stats.control(stats::Message::Session, peer_setup.size, true); let (publish, subscribe) = server.stat_tagged_origins(); let peer_implementation = setup::PeerImplementation::known(peer_setup.implementation); @@ -656,7 +656,7 @@ impl PausedLegacy { client_setup_size, } = self; let mut stream = stream.with_stats(&server.stats); - server.stats.control(stats::Control::Session, client_setup_size, true); + server.stats.control(stats::Message::Session, client_setup_size, true); let (publish, subscribe) = server.stat_tagged_origins(); // Encode parameters using the version-appropriate type. @@ -936,7 +936,7 @@ impl Handshake { version, client_setup, } => { - server.stats.control(stats::Control::Session, client_setup.size, true); + server.stats.control(stats::Message::Session, client_setup.size, true); server.start_lite(runtime, session, version, Some(client_setup), peer_hop, auth) } PausedHandshake::IetfModern(paused) => paused.ok(server, runtime, peer_hop, auth), @@ -1189,9 +1189,6 @@ mod tests { fn poll_closed(&mut self, _cx: &mut std::task::Context<'_>) -> std::task::Poll { std::task::Poll::Pending } - fn stats(&self) -> impl crate::transport::Stats { - crate::transport::StatsUnavailable - } } #[derive(Clone, Default)] diff --git a/rs/moq-net/src/session.rs b/rs/moq-net/src/session.rs index fd6c7a2e7f5..e0a811157e1 100644 --- a/rs/moq-net/src/session.rs +++ b/rs/moq-net/src/session.rs @@ -3,7 +3,7 @@ use std::{sync::Arc, task::Poll, time::Duration}; use crate::transport::poll::Session as _; -use crate::transport::{Error as _, Stats as _}; +use crate::transport::{Error as _, Metrics as _}; use crate::{Error, SessionError, Version, auth, bandwidth, coding::StreamCodes, goaway}; @@ -171,7 +171,7 @@ pub struct Session { bandwidth: bandwidth::Allocator, goaway: Arc, auth: auth::Handle, - credential: Option, + credential: Option, } impl Session { @@ -221,10 +221,10 @@ impl Session { /// The session probes up to what the reservations add up to, through its /// transport's [`Probe`](crate::transport::Probe) when it has one, so reserve /// here rather than on an allocator of your own. Clones share one registry: a - /// [`Client::with_bandwidth`](crate::Client::with_bandwidth) allocator's when the + /// [`Client::with_allocator`](crate::Client::with_allocator) allocator's when the /// session was dialed with one, so reservations outlive a reconnect. Reservations /// report `None` when the transport has no estimate. - pub fn bandwidth(&self) -> bandwidth::Allocator { + pub fn allocator(&self) -> bandwidth::Allocator { self.bandwidth.with_estimate(self.send_bandwidth()) } @@ -375,7 +375,7 @@ impl Session { } /// The connection credential this side presents on AUTH, or `None` when this session offers no AUTH. - pub(crate) fn credential(&self) -> Option<&auth::Auth> { + pub(crate) fn credential(&self) -> Option<&auth::Credential> { self.credential.as_ref() } } @@ -386,7 +386,7 @@ pub(super) struct Handles { pub goaway: goaway::Handle, pub auth: auth::Link, /// The connection credential the driver presented on `auth`, when its version has AUTH. - pub credential: Option, + pub credential: Option, /// Where the driver publishes [`Estimate`] changes, for a protocol that reports /// them to the peer (moq-lite PROBE). Sampled only while a consumer exists. pub estimate: Option>, @@ -818,19 +818,21 @@ impl Supervisor { } } -/// A [`Stats`] snapshot of the transport's counters. +/// A [`Stats`] snapshot of the transport's metrics and wire counters. fn snapshot(session: &S) -> Stats { - let stats = session.stats(); + // Metrics first: a transport that polls its byte counts refreshes its wire while reading them. + let metrics = session.metrics(); + let wire = session.wire(); Stats { - rtt: stats.rtt(), - estimated_send_rate: stats.estimated_send_rate().map(bandwidth::Rate::from_bps), - bytes_sent: stats.bytes_sent(), - bytes_received: stats.bytes_received(), - bytes_lost: stats.bytes_lost(), - packets_sent: stats.packets_sent(), - packets_received: stats.packets_received(), - packets_lost: stats.packets_lost(), - streams_evicted: stats.streams_evicted(), + rtt: metrics.rtt(), + estimated_send_rate: metrics.estimated_send_rate().map(bandwidth::Rate::from_bps), + bytes_sent: wire.as_ref().map(crate::transport::Wire::sent_bytes), + bytes_received: wire.as_ref().map(crate::transport::Wire::received_bytes), + bytes_lost: metrics.bytes_lost(), + packets_sent: metrics.packets_sent(), + packets_received: metrics.packets_received(), + packets_lost: metrics.packets_lost(), + streams_evicted: metrics.streams_evicted(), } } diff --git a/rs/moq-net/src/setup.rs b/rs/moq-net/src/setup.rs index bfb8ba99c6d..a077fea58e1 100644 --- a/rs/moq-net/src/setup.rs +++ b/rs/moq-net/src/setup.rs @@ -146,7 +146,7 @@ impl Setup { impl Encode for Setup { fn encode(&self, w: &mut Encoder<'_>, v: Version) -> Result<(), EncodeError> { - w.control = Some(crate::stats::Control::Session); + w.control = Some(crate::stats::Message::Session); Self::check_version(v); w.varint(SETUP_V17)?; let prefix = w.prefix_u16(); @@ -157,7 +157,7 @@ impl Encode for Setup { impl Decode for Setup { fn decode(r: &mut Decoder<'_>, v: Version) -> Result { - r.control = Some(crate::stats::Control::Session); + r.control = Some(crate::stats::Message::Session); Self::check_version(v); let kind = r.varint()?; if kind != SETUP_V17 { @@ -220,7 +220,7 @@ impl Client { impl Decode for Client { /// Decode a client setup message (draft-14 through draft-16 only). fn decode(r: &mut Decoder<'_>, v: Version) -> Result { - r.control = Some(crate::stats::Control::Session); + r.control = Some(crate::stats::Message::Session); let kind = r.u8()?; if kind != CLIENT_SETUP { return Err(DecodeError::InvalidValue); @@ -249,7 +249,7 @@ impl Decode for Client { impl Encode for Client { /// Encode a client setup message (draft-14 through draft-16 only). fn encode(&self, w: &mut Encoder<'_>, v: Version) -> Result<(), EncodeError> { - w.control = Some(crate::stats::Control::Session); + w.control = Some(crate::stats::Message::Session); w.u8(CLIENT_SETUP); let prefix = prefix_body(w, v)?; self.encode_inner(w, v)?; @@ -318,7 +318,7 @@ impl Server { impl Encode for Server { /// Encode a server setup message (draft-14 through draft-16 only). fn encode(&self, w: &mut Encoder<'_>, v: Version) -> Result<(), EncodeError> { - w.control = Some(crate::stats::Control::Session); + w.control = Some(crate::stats::Message::Session); w.u8(SERVER_SETUP); let prefix = prefix_body(w, v)?; self.encode_inner(w, v)?; @@ -329,7 +329,7 @@ impl Encode for Server { impl Decode for Server { /// Decode a server setup message (draft-14 through draft-16 only). fn decode(r: &mut Decoder<'_>, v: Version) -> Result { - r.control = Some(crate::stats::Control::Session); + r.control = Some(crate::stats::Message::Session); let kind = r.u8()?; if kind != SERVER_SETUP { return Err(DecodeError::InvalidValue); diff --git a/rs/moq-net/src/stats.rs b/rs/moq-net/src/stats.rs index d9f1f4cfd0c..7c52cb37a0a 100644 --- a/rs/moq-net/src/stats.rs +++ b/rs/moq-net/src/stats.rs @@ -307,7 +307,7 @@ struct SessionCounters { bytes: Mutex, wire_tx: AtomicU64, wire_rx: AtomicU64, - control: [[AtomicU64; 2]; Control::ALL.len()], + control: [[AtomicU64; 2]; Message::ALL.len()], } impl SessionCounters { @@ -346,7 +346,7 @@ impl SessionCounters { (presence, empty) } - fn control(&self, totals: &mut [[u64; 2]; Control::ALL.len()]) { + fn control(&self, totals: &mut [[u64; 2]; Message::ALL.len()]) { for (total, counters) in totals.iter_mut().zip(&self.control) { for (total, counter) in total.iter_mut().zip(counters) { *total += counter.load(Ordering::Relaxed); @@ -873,10 +873,10 @@ impl Role { } } -/// Cumulative bytes sent and received, returned per [`Control`] class by [`Snapshot::control`]. +/// Cumulative bytes sent and received, returned per [`Message`] class by [`Snapshot::control`]. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] -pub struct Bytes { +pub struct Totals { /// Bytes successfully encoded for sending, counted even if the stream later fails. pub tx: u64, /// Bytes of complete messages decoded and consumed. @@ -890,7 +890,7 @@ pub struct Bytes { /// framing decodes, before request validation. Shared reply IDs use [`Self::Other`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] -pub enum Control { +pub enum Message { /// Session setup and information. Session, /// Namespace advertisements and listings. @@ -911,7 +911,7 @@ pub enum Control { Other, } -impl Control { +impl Message { const ALL: [Self; 9] = [ Self::Session, Self::Announce, @@ -958,20 +958,20 @@ pub struct Snapshot { traffic: HashMap, /// Session presence per tier; read via [`Self::sessions`]. sessions: HashMap, - control: HashMap, + control: HashMap, } impl Snapshot { /// The `(tier, class, totals)` control-message rows with any traffic, sorted by tier and class. /// Includes prefixes inside complete codec values, but excludes separately coded type selectors, /// media payload, and transport framing, acknowledgements, and retransmissions. - pub fn control(&self) -> Vec<(Tier, Control, Bytes)> { + pub fn control(&self) -> Vec<(Tier, Message, Totals)> { let mut rows = Vec::new(); for (tier, totals) in &self.control { - for class in Control::ALL { + for class in Message::ALL { let [tx, rx] = totals[class as usize]; if tx != 0 || rx != 0 { - rows.push((tier.clone(), class, Bytes { tx, rx })); + rows.push((tier.clone(), class, Totals { tx, rx })); } } } @@ -1621,7 +1621,7 @@ struct Viewer { impl Session { #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))] - pub(crate) fn control(&self, class: Control, bytes: usize, received: bool) { + pub(crate) fn control(&self, class: Message, bytes: usize, received: bool) { let Some(inner) = &self.inner else { return }; let current = inner.current.lock().unwrap_or_else(PoisonError::into_inner); if let Some(counters) = ¤t.presence { @@ -2562,12 +2562,12 @@ mod tests { let first = Tier::new("internal"); let second = Tier::new("edge"); let context = registry.tier(first.clone()).session(""); - context.control(Control::Announce, 17, false); + context.control(Message::Announce, 17, false); context.retag(second.clone(), ""); - context.control(Control::TrackInfo, 23, true); + context.control(Message::TrackInfo, 23, true); let expected = vec![ - (second, Control::TrackInfo, Bytes { tx: 0, rx: 23 }), - (first, Control::Announce, Bytes { tx: 17, rx: 0 }), + (second, Message::TrackInfo, Totals { tx: 0, rx: 23 }), + (first, Message::Announce, Totals { tx: 17, rx: 0 }), ]; assert_eq!(registry.snapshot().control(), expected); drop(context); diff --git a/rs/moq-net/src/transport.rs b/rs/moq-net/src/transport.rs index b956acd9bd3..8d99f53a497 100644 --- a/rs/moq-net/src/transport.rs +++ b/rs/moq-net/src/transport.rs @@ -121,21 +121,11 @@ impl Probe { } } -/// Connection-level statistics. +/// Connection-level metrics a transport reports, beyond the byte counts its [`Wire`] holds. /// /// Methods return `Option`: `None` means the implementation doesn't track /// this metric, while `Some(0)` means actually zero. -pub trait Stats { - /// Total bytes sent over the connection, including retransmissions and overhead. - fn bytes_sent(&self) -> Option { - None - } - - /// Total bytes received over the connection, including duplicate and overhead. - fn bytes_received(&self) -> Option { - None - } - +pub trait Metrics { /// Total bytes lost (detected via retransmission or acknowledgement). fn bytes_lost(&self) -> Option { None @@ -172,9 +162,9 @@ pub trait Stats { } } -/// Default stats implementation that returns `None` for all metrics. -pub struct StatsUnavailable; -impl Stats for StatsUnavailable {} +/// The metrics of a transport that tracks none. +struct Untracked; +impl Metrics for Untracked {} /// The smallest connection receive window a transport that leases may offer. /// @@ -233,7 +223,7 @@ pub mod poll { use std::collections::VecDeque; - use super::{Error, MaybeSend, MaybeSync, Stats}; + use super::{Error, MaybeSend, MaybeSync, Metrics, Untracked}; use bytes::{Buf, Bytes, BytesMut}; /// A cloneable transport session with independent progress on each handle. @@ -346,11 +336,10 @@ pub mod poll { /// Poll until the connection is closed by either side. fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll; - /// Return connection-level statistics. - /// - /// Return [`super::StatsUnavailable`] if the transport does not track them. Required - /// rather than defaulted for the same reason as [`protocol`](Self::protocol). - fn stats(&self) -> impl Stats; + /// Return connection-level metrics; by default, none are tracked. + fn metrics(&self) -> impl Metrics { + Untracked + } /// Return the wire counters this transport updates, or `None` when it tracks none. fn wire(&self) -> Option { diff --git a/rs/moq-net/src/transport/boxed.rs b/rs/moq-net/src/transport/boxed.rs index 7dfa9b8d1a6..83bb4d59e5f 100644 --- a/rs/moq-net/src/transport/boxed.rs +++ b/rs/moq-net/src/transport/boxed.rs @@ -122,11 +122,9 @@ impl RecvStream { /// A boxed [`poll::Lease`], borrowed from a [`RecvStream`]. pub(crate) struct Lease<'a>(Box); -/// The transport's connection stats, read once. +/// The transport's connection metrics, read once. #[derive(Clone, Copy, Debug, Default)] -pub(crate) struct Stats { - bytes_sent: Option, - bytes_received: Option, +pub(crate) struct Metrics { bytes_lost: Option, packets_sent: Option, packets_received: Option, @@ -136,29 +134,21 @@ pub(crate) struct Stats { streams_evicted: Option, } -impl Stats { - fn read(stats: impl super::Stats) -> Self { +impl Metrics { + fn read(metrics: impl super::Metrics) -> Self { Self { - bytes_sent: stats.bytes_sent(), - bytes_received: stats.bytes_received(), - bytes_lost: stats.bytes_lost(), - packets_sent: stats.packets_sent(), - packets_received: stats.packets_received(), - packets_lost: stats.packets_lost(), - rtt: stats.rtt(), - estimated_send_rate: stats.estimated_send_rate(), - streams_evicted: stats.streams_evicted(), + bytes_lost: metrics.bytes_lost(), + packets_sent: metrics.packets_sent(), + packets_received: metrics.packets_received(), + packets_lost: metrics.packets_lost(), + rtt: metrics.rtt(), + estimated_send_rate: metrics.estimated_send_rate(), + streams_evicted: metrics.streams_evicted(), } } } -impl super::Stats for Stats { - fn bytes_sent(&self) -> Option { - self.bytes_sent - } - fn bytes_received(&self) -> Option { - self.bytes_received - } +impl super::Metrics for Metrics { fn bytes_lost(&self) -> Option { self.bytes_lost } @@ -209,7 +199,7 @@ trait ErasedSession: MaybeSend + MaybeSync { fn address(&self) -> Address; fn close(&mut self, code: u32, reason: &str); fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll; - fn stats(&self) -> Stats; + fn metrics(&self) -> Metrics; fn wire(&self) -> Option; fn probe(&self) -> Option; } @@ -336,8 +326,8 @@ impl ErasedSession for S { poll::Session::poll_closed(self, cx).map(Error::new) } - fn stats(&self) -> Stats { - Stats::read(poll::Session::stats(self)) + fn metrics(&self) -> Metrics { + Metrics::read(poll::Session::metrics(self)) } fn wire(&self) -> Option { @@ -503,8 +493,8 @@ impl poll::Session for Session { self.inner.poll_closed(cx) } - fn stats(&self) -> impl super::Stats { - self.inner.stats() + fn metrics(&self) -> impl super::Metrics { + self.inner.metrics() } fn wire(&self) -> Option { diff --git a/rs/moq-net/src/transport/memory.rs b/rs/moq-net/src/transport/memory.rs index 9fa29d81972..8b0536a025f 100644 --- a/rs/moq-net/src/transport/memory.rs +++ b/rs/moq-net/src/transport/memory.rs @@ -31,7 +31,7 @@ use std::{ use bytes::{Buf, Bytes}; -use super::{StatsUnavailable, poll}; +use super::poll; /// The largest datagram either side sends: QUIC's minimum MTU, so a payload that fits /// here fits any QUIC path. @@ -428,10 +428,6 @@ impl poll::Session for Session { fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll { poll_close(&self.side.conn.close, self.closed.hold(cx)) } - - fn stats(&self) -> impl super::Stats { - StatsUnavailable - } } /// One direction of a stream: the messages its writer queued for its reader. diff --git a/rs/moq-net/tests/integration/compress.rs b/rs/moq-net/tests/integration/compress.rs index 666ce755162..22bddb5f8c8 100644 --- a/rs/moq-net/tests/integration/compress.rs +++ b/rs/moq-net/tests/integration/compress.rs @@ -419,7 +419,7 @@ async fn ietf_fetch_keeps_the_stored_form() { origin.consume().routed("bcast").await.unwrap(); let remote = origin.consume().request_broadcast("bcast", None).await.unwrap(); let consumer = remote.track("data").unwrap(); - assert_eq!(consumer.query().await.unwrap().compress, version != "moq-transport-16"); + assert_eq!(consumer.info().await.unwrap().compress, version != "moq-transport-16"); let mut fetched = consumer.fetch_group(0, moq_net::group::Fetch::default()).await.unwrap(); for index in 0..3 { assert_eq!( diff --git a/rs/moq-net/tests/integration/control_stats.rs b/rs/moq-net/tests/integration/control_stats.rs index 554859399b6..eac3fdc4ebc 100644 --- a/rs/moq-net/tests/integration/control_stats.rs +++ b/rs/moq-net/tests/integration/control_stats.rs @@ -8,7 +8,7 @@ use crate::support::{ }; use moq_net::{ Timescale, Timestamp, origin, - stats::{Control, Registry, Tier}, + stats::{Message, Registry, Tier}, }; fn origin() -> origin::Producer { @@ -57,7 +57,7 @@ async fn control_classes_cross_lite_and_ietf_sessions_without_counting_payload() let mut group = sub.recv_group().await.unwrap().unwrap(); assert_eq!(group.read_frame().await.unwrap().unwrap().payload.len(), 64 * 1024); let rows = registry.snapshot().control(); - for class in [Control::Announce, Control::Subscribe] { + for class in [Message::Announce, Message::Subscribe] { assert!( rows.iter() .any(|(row_tier, row_class, bytes)| *row_tier == tier && *row_class == class && bytes.tx > 0), @@ -103,7 +103,7 @@ async fn setup_counts_under_the_admitted_stats() { assert!( rows.iter() .any(|(row_tier, class, bytes)| *row_tier == tier - && *class == Control::Session + && *class == Message::Session && bytes.tx > 0 && bytes.rx > 0), "{version}: {rows:?}" ); diff --git a/rs/moq-net/tests/integration/fetch_cancel.rs b/rs/moq-net/tests/integration/fetch_cancel.rs index 588dffa4b38..e831383d2c7 100644 --- a/rs/moq-net/tests/integration/fetch_cancel.rs +++ b/rs/moq-net/tests/integration/fetch_cancel.rs @@ -89,7 +89,12 @@ async fn abandoned_fetch_reaches_the_publisher(version: &str, relays: u64, stage drop(fetched); // The publisher stops serving the group: nobody reads it any more. - moq_clock::timeout(Duration::from_secs(5), group.demand().unused()) + let mut demand = group.demand(); + let unwanted = async move { + while demand.wanted_changed().await? {} + Ok::<_, moq_net::Error>(()) + }; + moq_clock::timeout(Duration::from_secs(5), unwanted) .await .unwrap_or_else(|_| panic!("{ctx}: the publisher still serves the fetch")) .unwrap(); diff --git a/rs/moq-net/tests/integration/fetch_only.rs b/rs/moq-net/tests/integration/fetch_only.rs index 9f5e5ad4400..7bd1a4c5f08 100644 --- a/rs/moq-net/tests/integration/fetch_only.rs +++ b/rs/moq-net/tests/integration/fetch_only.rs @@ -180,7 +180,7 @@ async fn a_subscribe_after_track_status_keeps_timestamps() { let remote = resolve(&client).await; let copy = remote.track("video").unwrap(); - let info = copy.query().await.expect("TRACK_STATUS resolves the track"); + let info = copy.info().await.expect("TRACK_STATUS resolves the track"); assert!(info.timescale.is_some(), "{version}: the copy is untimed"); assert!(track.subscription().is_none(), "{version}: the query subscribed"); diff --git a/rs/moq-net/tests/integration/session_close.rs b/rs/moq-net/tests/integration/session_close.rs index bc08b6a9f3a..bbafd3dcf81 100644 --- a/rs/moq-net/tests/integration/session_close.rs +++ b/rs/moq-net/tests/integration/session_close.rs @@ -120,7 +120,7 @@ async fn track_info_interest_precedes_a_subscription() { consumer.routed("bcast").await.unwrap(); let remote = consumer.request_broadcast("bcast", None).await.unwrap(); let copy = remote.track("video").unwrap(); - copy.query().await.expect("TRACK_INFO"); + copy.info().await.expect("TRACK_INFO"); crate::support::wanted(track.demand()) .await .expect("TRACK_INFO holds demand"); diff --git a/rs/moq-net/tests/integration/subscribe_ranges.rs b/rs/moq-net/tests/integration/subscribe_ranges.rs index 1fb8e048d32..600b551ba54 100644 --- a/rs/moq-net/tests/integration/subscribe_ranges.rs +++ b/rs/moq-net/tests/integration/subscribe_ranges.rs @@ -694,8 +694,8 @@ async fn unresolved_time_reader_never_changes_sibling_demand() { .unwrap(); let track = fixture.remote.track("quiet").unwrap(); - // Pin the public track instance through a query before creating the pending reader. - let query = track.query(); + // Pin the public track instance through an info request before creating the pending reader. + let query = track.info(); let track = query.track(); let mut refused = Some(track.subscribe(Subscription::default().with_ranges([Range { diff --git a/rs/moq-net/tests/integration/support/mock.rs b/rs/moq-net/tests/integration/support/mock.rs index b2e54cc075b..0b3265cdcc7 100644 --- a/rs/moq-net/tests/integration/support/mock.rs +++ b/rs/moq-net/tests/integration/support/mock.rs @@ -448,7 +448,7 @@ struct Side { bidi_types: StreamTypes, /// Stream resets sent by this side. resets: Resets, - /// What [`poll::Session::stats`] reports. + /// What [`poll::Session::metrics`] reports. stats: Mutex, /// How many times the stats were read. stats_reads: AtomicUsize, @@ -467,7 +467,7 @@ pub struct MockStats { pub rtt: Option, } -impl moq_net::transport::Stats for MockStats { +impl moq_net::transport::Metrics for MockStats { fn estimated_send_rate(&self) -> Option { self.estimated_send_rate } @@ -640,7 +640,7 @@ impl poll::Session for MockSession { self.inner.poll_closed(cx) } - fn stats(&self) -> impl moq_net::transport::Stats { + fn metrics(&self) -> impl moq_net::transport::Metrics { assert!( !self.side.panic_on_stats.load(Ordering::Relaxed), "injected transport panic" diff --git a/rs/moq-net/tests/integration/track_info_cancel.rs b/rs/moq-net/tests/integration/track_info_cancel.rs index 6fcb5e55306..dcc171298bf 100644 --- a/rs/moq-net/tests/integration/track_info_cancel.rs +++ b/rs/moq-net/tests/integration/track_info_cancel.rs @@ -86,7 +86,7 @@ async fn withdrawn_broadcast_releases_track_info(version: &str, answered: bool, options.client_subscribe = Some(reader.clone()); let pair = connect_mock(options).await; let remote = reader.consume().routed_broadcast("room").await.unwrap(); - let mut query = remote.track("video").unwrap().query(); + let mut query = remote.track("video").unwrap().info(); let request = match futures::future::select(std::pin::pin!(dynamic.requested_track()), &mut query).await { futures::future::Either::Left((request, _)) => request.expect("TRACK reaches the publisher"), futures::future::Either::Right(_) => panic!("nothing answered TRACK"), diff --git a/rs/moq-net/tests/integration/track_stream_demand.rs b/rs/moq-net/tests/integration/track_stream_demand.rs index 9ef71922418..8d905a3717e 100644 --- a/rs/moq-net/tests/integration/track_stream_demand.rs +++ b/rs/moq-net/tests/integration/track_stream_demand.rs @@ -208,7 +208,7 @@ async fn bare_handle_is_lazy(version: &str, relays: usize) { ); // A held query reaches the publisher, and holds the track there until dropped. - let mut query = handle.query(); + let mut query = handle.info(); moq_clock::timeout(TIMEOUT, &mut query) .await .unwrap_or_else(|_| panic!("{label}: query stalled")) diff --git a/rs/moq-net/tests/loom.rs b/rs/moq-net/tests/loom.rs index 841b913b590..7cd685ef367 100644 --- a/rs/moq-net/tests/loom.rs +++ b/rs/moq-net/tests/loom.rs @@ -229,13 +229,13 @@ fn a_front_sees_a_reader_come_and_go() { let room = block_on(pending).expect("resolves"); // A first reader gets the source asked, then leaves. - let first = room.track("video").expect("track").query(); + let first = room.track("video").expect("track").info(); driver.poll(now, &noop).unwrap(); assert!(demand.wanted().is_some(), "the front never asked the source"); drop(first); let racing = room.clone(); - let reader = thread::spawn(move || drop(racing.track("video").expect("track").query())); + let reader = thread::spawn(move || drop(racing.track("video").expect("track").info())); driver.poll(now, &noop).unwrap(); reader.join().unwrap(); @@ -270,17 +270,17 @@ fn a_front_sees_a_reader_return() { let room = block_on(pending).expect("resolves"); // A first reader comes and goes, which parks the track. - let first = room.track("video").expect("track").query(); + let first = room.track("video").expect("track").info(); driver.poll(now, &noop).unwrap(); drop(first); driver.poll(now, &noop).unwrap(); assert!(demand.wanted().is_none(), "the front kept the source for nobody"); - let leaving = room.track("video").expect("track").query(); + let leaving = room.track("video").expect("track").info(); let racing = room.clone(); let reader = thread::spawn(move || { drop(leaving); - racing.track("video").expect("track").query() + racing.track("video").expect("track").info() }); driver.poll(now, &noop).unwrap(); let returned = reader.join().unwrap(); diff --git a/rs/moq-relay/benches/auth.rs b/rs/moq-relay/benches/auth.rs index 495acc71b34..c38b82fc42f 100644 --- a/rs/moq-relay/benches/auth.rs +++ b/rs/moq-relay/benches/auth.rs @@ -16,7 +16,7 @@ fn grant(prefix: &str) -> Grant { struct Fixture { _connections: Vec, - _tokens: Vec, + _tokens: Vec, producers: Vec, selected: usize, watch: moq_net::auth::Watch, diff --git a/rs/moq-relay/src/auth/refresh.rs b/rs/moq-relay/src/auth/refresh.rs index 2eaed108507..4c1b1b39439 100644 --- a/rs/moq-relay/src/auth/refresh.rs +++ b/rs/moq-relay/src/auth/refresh.rs @@ -938,7 +938,7 @@ mod tests { moq_net::Session, moq_net::Session, super::super::Lease, - moq_net::auth::Auth, + moq_net::auth::Credential, ) { let (auth, mut admissions) = super::super::Auth::embedded("test"); let (owner, consumer) = lease::Producer::new(grant("a/**", 3)); diff --git a/rs/moq-relay/src/internal.rs b/rs/moq-relay/src/internal.rs index 06d46a79264..2b9cc231a77 100644 --- a/rs/moq-relay/src/internal.rs +++ b/rs/moq-relay/src/internal.rs @@ -549,12 +549,12 @@ fn render_metrics( ( "moq_relay_control_tx_bytes_total", "Control-message bytes encoded for sending, including codec prefixes; excludes transport overhead.", - (|b: &moq_net::stats::Bytes| b.tx) as fn(&moq_net::stats::Bytes) -> u64, + (|b: &moq_net::stats::Totals| b.tx) as fn(&moq_net::stats::Totals) -> u64, ), ( "moq_relay_control_rx_bytes_total", "Control-message bytes decoded, including codec prefixes; excludes transport overhead.", - (|b: &moq_net::stats::Bytes| b.rx) as fn(&moq_net::stats::Bytes) -> u64, + (|b: &moq_net::stats::Totals| b.rx) as fn(&moq_net::stats::Totals) -> u64, ), ] { let _ = writeln!(out, "# HELP {name} {help}"); diff --git a/rs/moq-relay/tests/integration/wire_stats.rs b/rs/moq-relay/tests/integration/wire_stats.rs index a112db366f2..e3cb058185d 100644 --- a/rs/moq-relay/tests/integration/wire_stats.rs +++ b/rs/moq-relay/tests/integration/wire_stats.rs @@ -68,7 +68,7 @@ async fn wire_sources(io_uring: bool) { && row.wire_tx > 0 && row.wire_rx > 0 && registry.snapshot().control().iter().any(|(_, class, bytes)| { - *class == moq_net::stats::Control::Announce && bytes.tx > 0 && bytes.rx > 0 + *class == moq_net::stats::Message::Announce && bytes.tx > 0 && bytes.rx > 0 }) { break row; } diff --git a/rs/moq-rtc/src/ingest.rs b/rs/moq-rtc/src/ingest.rs index 859f3703e31..fc145c45862 100644 --- a/rs/moq-rtc/src/ingest.rs +++ b/rs/moq-rtc/src/ingest.rs @@ -106,7 +106,7 @@ mod tests { ) .unwrap(); - let info = broadcast.consume().track("0.avc3").unwrap().query().await.unwrap(); + let info = broadcast.consume().track("0.avc3").unwrap().info().await.unwrap(); assert_eq!(info.max_age, Some(Duration::from_secs(3))); } diff --git a/rs/moq-rtmp/src/server.rs b/rs/moq-rtmp/src/server.rs index cd6df1cd260..12c6af25784 100644 --- a/rs/moq-rtmp/src/server.rs +++ b/rs/moq-rtmp/src/server.rs @@ -2090,7 +2090,7 @@ mod tests { let consumer = origin.consume(); consumer.routed("live/cam0").await.unwrap(); let broadcast = consumer.request_broadcast("live/cam0", None).await.unwrap(); - let info = broadcast.track("0.flv-v").unwrap().query().await.unwrap(); + let info = broadcast.track("0.flv-v").unwrap().info().await.unwrap(); assert_eq!(info.max_age, Some(Duration::from_secs(3))); } diff --git a/rs/moq-srt/src/ts.rs b/rs/moq-srt/src/ts.rs index a67b30ce41a..407318b5078 100644 --- a/rs/moq-srt/src/ts.rs +++ b/rs/moq-srt/src/ts.rs @@ -609,7 +609,7 @@ mod tests { let consumer = origin.consume(); consumer.routed("live/cam0").await.unwrap(); let broadcast = consumer.request_broadcast("live/cam0", None).await.unwrap(); - let info = broadcast.track("0.avc3").unwrap().query().await.unwrap(); + let info = broadcast.track("0.avc3").unwrap().info().await.unwrap(); assert_eq!(info.max_age, Some(Duration::from_secs(3))); } diff --git a/rs/moq-tokio/MIGRATE.md b/rs/moq-tokio/MIGRATE.md index 3297855e610..f26fe53e87a 100644 --- a/rs/moq-tokio/MIGRATE.md +++ b/rs/moq-tokio/MIGRATE.md @@ -4,6 +4,10 @@ How to update your code for each breaking change, newest first. ## Unreleased +### `Connection::allocator` ([#6751](https://github.com/moq-dev/moq/pull/6751)) + +`Connection::bandwidth()` is `Connection::allocator()`, mirroring `moq_net::Session::allocator()`. + ### QUIC connections wait for the handshake Await `quic::driver::Connecting` instead of calling `into_0rtt()`. diff --git a/rs/moq-tokio/src/client.rs b/rs/moq-tokio/src/client.rs index a0da27e7ec4..7e45b517dd6 100644 --- a/rs/moq-tokio/src/client.rs +++ b/rs/moq-tokio/src/client.rs @@ -238,9 +238,9 @@ impl Client { self } - /// Share `bandwidth`'s reservations with every session this client dials. - pub(crate) fn with_bandwidth(mut self, bandwidth: moq_net::bandwidth::Allocator) -> Self { - self.moq = self.moq.with_bandwidth(bandwidth); + /// Share `allocator`'s reservations with every session this client dials. + pub(crate) fn with_allocator(mut self, allocator: moq_net::bandwidth::Allocator) -> Self { + self.moq = self.moq.with_allocator(allocator); self } diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index 549cf4e9355..8886a1045ab 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -980,7 +980,7 @@ impl Connection { let send_bandwidth = send_bw.consume(); let recv_bandwidth = recv_bw.weak(); let bandwidth = moq_net::bandwidth::Allocator::new(send_bandwidth.clone()); - let client = client.with_bandwidth(bandwidth.clone()); + let client = client.with_allocator(bandwidth.clone()); let closed: CloseGuard = Default::default(); let task_closed = closed.clone(); @@ -1546,12 +1546,12 @@ impl Connection { } /// Divides [`send_bandwidth`](Self::send_bandwidth) among this connection's senders, - /// mirroring [`moq_net::Session::bandwidth`]. + /// mirroring [`moq_net::Session::allocator`]. /// /// Persistent like the estimate: every session the loop dials probes for these /// reservations, so they survive reconnects. Reservations report `None` while /// disconnected, telling a sender to hold its rate. - pub fn bandwidth(&self) -> moq_net::bandwidth::Allocator { + pub fn allocator(&self) -> moq_net::bandwidth::Allocator { self.bandwidth.clone() } diff --git a/rs/moq-tokio/src/transport.rs b/rs/moq-tokio/src/transport.rs index 3264e559e39..c86e8690fad 100644 --- a/rs/moq-tokio/src/transport.rs +++ b/rs/moq-tokio/src/transport.rs @@ -117,6 +117,8 @@ pub struct Session { request_bi: OpSlot>, recv_datagram: OpSlot>, closed: OpSlot, + // Wire counters for a backend that has none and reports bytes only in its stats. + polled_wire: moq_net::transport::Wire, } /// The stream pair an async-interface accept or open resolves to. @@ -166,6 +168,7 @@ impl Session { request_bi: OpSlot::default(), recv_datagram: OpSlot::default(), closed: OpSlot::default(), + polled_wire: moq_net::transport::Wire::new(), } } } @@ -174,7 +177,10 @@ impl Session { // owns its own progress under the poll contract. impl Clone for Session { fn clone(&self) -> Self { - Self::new(self.session.clone(), self.address) + Self { + polled_wire: self.polled_wire.clone(), + ..Self::new(self.session.clone(), self.address) + } } } diff --git a/rs/moq-tokio/src/transport/owned.rs b/rs/moq-tokio/src/transport/owned.rs index 255f668335f..ea15a3e6c0b 100644 --- a/rs/moq-tokio/src/transport/owned.rs +++ b/rs/moq-tokio/src/transport/owned.rs @@ -20,17 +20,11 @@ impl moq::Error for Error { } } -struct Stats { +struct Metrics { inner: S, streams_evicted: Option, } -impl moq::Stats for Stats { - fn bytes_sent(&self) -> Option { - self.inner.bytes_sent() - } - fn bytes_received(&self) -> Option { - self.inner.bytes_received() - } +impl moq::Metrics for Metrics { fn bytes_lost(&self) -> Option { self.inner.bytes_lost() } @@ -139,14 +133,24 @@ impl> poll::Session fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll { backend::Session::poll_closed(self, cx).map(Error) } - fn stats(&self) -> impl moq::Stats { - Stats { - inner: backend::Session::stats(self), + fn metrics(&self) -> impl moq::Metrics { + let inner = backend::Session::stats(self); + // Reading the metrics refreshes the polled wire, which moq-net reads right after. + if super::Grouped::wire(&self.session).is_none() { + if let Some(sent) = wt::Stats::bytes_sent(&inner) { + self.polled_wire.set_sent_bytes(sent); + } + if let Some(received) = wt::Stats::bytes_received(&inner) { + self.polled_wire.set_received_bytes(received); + } + } + Metrics { + inner, streams_evicted: super::Grouped::streams_evicted(&self.session), } } fn wire(&self) -> Option { - super::Grouped::wire(&self.session) + super::Grouped::wire(&self.session).or_else(|| Some(self.polled_wire.clone())) } fn probe(&self) -> Option { super::Grouped::probe(&self.session) diff --git a/rs/moq-tokio/tests/integration/receive_credit.rs b/rs/moq-tokio/tests/integration/receive_credit.rs index 7b150892b25..62212443a3e 100644 --- a/rs/moq-tokio/tests/integration/receive_credit.rs +++ b/rs/moq-tokio/tests/integration/receive_credit.rs @@ -287,7 +287,7 @@ async fn the_less_urgent_partial_frame_gives_way(version: &str, profile: Option< moq_net::transport::Address::Setup, ); assert_eq!( - moq_net::transport::Stats::streams_evicted(&moq_net::transport::poll::Session::stats(&session)), + moq_net::transport::Metrics::streams_evicted(&moq_net::transport::poll::Session::metrics(&session)), Some(1), "moq-net sees the eviction count, {version}" ); diff --git a/rs/moq-transcode/src/lib.rs b/rs/moq-transcode/src/lib.rs index 86201a3c7a4..22b1254fbcc 100644 --- a/rs/moq-transcode/src/lib.rs +++ b/rs/moq-transcode/src/lib.rs @@ -1247,7 +1247,7 @@ mod tests { // wait until the live path has claimed group 0, so the fetch below can only // resolve from the track cache and retirement finds that live group open. let rung = consumer.track("video/120p").unwrap(); - let mut query = rung.query(); + let mut query = rung.info(); (&mut query).await.unwrap(); let mut edge = rung.clone(); assert_eq!(edge.largest().await.map(|position| position.group), Some(0)); @@ -1314,7 +1314,7 @@ mod tests { // A held query is demand, so the rung starts encoding and subscribes to the // source. let rung = consumer.track("video/120p").unwrap(); - let mut query = rung.query(); + let mut query = rung.info(); (&mut query).await.unwrap(); let wanted = async { while demand.wanted_changed().await?.is_none() {} @@ -1385,7 +1385,7 @@ mod tests { // Resolving the info waits for the transcoder to accept the track, so the // fetch below reaches a rung that is already serving. let rung = consumer.track("video/120p").unwrap(); - let mut query = rung.query(); + let mut query = rung.info(); (&mut query).await.unwrap(); assert!( source._track.subscription_changed().await.unwrap().is_some(), @@ -1469,7 +1469,7 @@ mod tests { // No live groups, so group 7 misses and reaches the fetch handler. let rung = consumer.track("video/120p").unwrap(); - rung.query().await.unwrap(); + rung.info().await.unwrap(); let fetching = rung.fetch_group(7, None); let abandoned = tokio::time::timeout(std::time::Duration::from_secs(5), source_fetches.requested_fill()) diff --git a/rs/moq-uring/src/transport/adapter.rs b/rs/moq-uring/src/transport/adapter.rs index 705ad878e2a..00d8777143e 100644 --- a/rs/moq-uring/src/transport/adapter.rs +++ b/rs/moq-uring/src/transport/adapter.rs @@ -20,17 +20,11 @@ impl moq::Error for Error { } } -struct Stats { +struct Metrics { inner: S, streams_evicted: Option, } -impl moq::Stats for Stats { - fn bytes_sent(&self) -> Option { - self.inner.bytes_sent() - } - fn bytes_received(&self) -> Option { - self.inner.bytes_received() - } +impl moq::Metrics for Metrics { fn bytes_lost(&self) -> Option { self.inner.bytes_lost() } @@ -214,8 +208,8 @@ impl + Clone + 'static> pol fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll { backend::Session::poll_closed(&mut self.0, cx).map(Error) } - fn stats(&self) -> impl moq::Stats { - Stats { + fn metrics(&self) -> impl moq::Metrics { + Metrics { inner: backend::Session::stats(&self.0), streams_evicted: Grouped::streams_evicted(&self.0), } @@ -422,13 +416,13 @@ mod tests { #[test] fn forwards_thread_local_streams_and_keeps_error_codes() { - use moq_net::transport::Stats as _; + use moq_net::transport::Metrics as _; let state = Rc::new(Cell::new(0)); let mut session = Session::new(Backend(state.clone()), moq::Address::Setup); let mut cx = Context::from_waker(std::task::Waker::noop()); assert_eq!(poll::Session::protocol(&session), Some("moq-lite-06")); assert_eq!( - poll::Session::stats(&session).rtt(), + poll::Session::metrics(&session).rtt(), Some(std::time::Duration::from_millis(7)) ); let Poll::Ready(Ok((mut send, mut recv))) = diff --git a/rs/moq-uring/src/transport/local.rs b/rs/moq-uring/src/transport/local.rs index e46c3f831c0..6f8a9824558 100644 --- a/rs/moq-uring/src/transport/local.rs +++ b/rs/moq-uring/src/transport/local.rs @@ -108,8 +108,8 @@ impl poll::Session for Local { self.0.poll_closed(cx) } - fn stats(&self) -> impl moq::Stats { - self.0.stats() + fn metrics(&self) -> impl moq::Metrics { + self.0.metrics() } fn wire(&self) -> Option { diff --git a/rs/moq-video/src/encode/producer.rs b/rs/moq-video/src/encode/producer.rs index 21347998c3d..244ad95ebff 100644 --- a/rs/moq-video/src/encode/producer.rs +++ b/rs/moq-video/src/encode/producer.rs @@ -776,7 +776,7 @@ async fn capture_loop( // so the policy's ceiling is that rate and the target starts there. A // reopened camera starts optimistic again rather than inheriting the // backed-off rate from whatever the link was doing last time. - let mut rate = Some(rate::Follower::new(reservation.consumer(), rate::Policy::new(ceiling))); + let mut rate = Some(rate::Follower::new(reservation.consume(), rate::Policy::new(ceiling))); // Per encoder, since a fresh one opens with a keyframe that serves every earlier ask. let mut forced = Cuts::new(served); diff --git a/rs/moq-wasm/src/transport/adapter.rs b/rs/moq-wasm/src/transport/adapter.rs index 78fc7339a2f..57c338d32ed 100644 --- a/rs/moq-wasm/src/transport/adapter.rs +++ b/rs/moq-wasm/src/transport/adapter.rs @@ -17,14 +17,8 @@ impl moq::Error for Error { } } -struct Stats(S); -impl moq::Stats for Stats { - fn bytes_sent(&self) -> Option { - self.0.bytes_sent() - } - fn bytes_received(&self) -> Option { - self.0.bytes_received() - } +struct Metrics(S); +impl moq::Metrics for Metrics { fn bytes_lost(&self) -> Option { self.0.bytes_lost() } @@ -134,8 +128,8 @@ impl + Clone + 'st fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll { backend::Session::poll_closed(&mut self.0, cx).map(Error) } - fn stats(&self) -> impl moq::Stats { - Stats(backend::Session::stats(&self.0)) + fn metrics(&self) -> impl moq::Metrics { + Metrics(backend::Session::stats(&self.0)) } } /// An outgoing WebTransport stream adapted to moq-net. @@ -306,13 +300,13 @@ mod tests { #[test] fn forwards_thread_local_streams_and_keeps_error_codes() { - use moq_net::transport::Stats as _; + use moq_net::transport::Metrics as _; let state = Rc::new(Cell::new(0)); let mut session = Session::new(Backend(state.clone())); let mut cx = Context::from_waker(std::task::Waker::noop()); assert_eq!(poll::Session::protocol(&session), Some("moq-lite-06")); assert_eq!( - poll::Session::stats(&session).rtt(), + poll::Session::metrics(&session).rtt(), Some(std::time::Duration::from_millis(7)) ); let Poll::Ready(Ok((mut send, mut recv))) = diff --git a/rs/qmux/src/session.rs b/rs/qmux/src/session.rs index 74b8d65b569..d60c8b2f97c 100644 --- a/rs/qmux/src/session.rs +++ b/rs/qmux/src/session.rs @@ -752,14 +752,12 @@ impl poll::Session for Session { Poll::Pending } - fn stats(&self) -> impl net::Stats { + fn metrics(&self) -> impl net::Metrics { let state = self.inner.lock(); // The kernel's view of the socket underneath beats a QX_PING sample: it is there // from the first byte and costs no traffic. let socket = self.inner.socket_stats.as_ref(); - Stats { - sent: state.sent_bytes, - received: state.received_bytes, + Metrics { rtt: socket.and_then(|stats| stats.rtt()).or(state.conn.rtt()), rate: socket.and_then(|stats| stats.estimated_send_rate()), } @@ -770,23 +768,13 @@ impl poll::Session for Session { } } -/// A snapshot of the session's counters. -struct Stats { - sent: u64, - received: u64, +/// A snapshot of the session's metrics; its [`net::Wire`] holds the byte counts. +struct Metrics { rtt: Option, rate: Option, } -impl net::Stats for Stats { - fn bytes_sent(&self) -> Option { - Some(self.sent) - } - - fn bytes_received(&self) -> Option { - Some(self.received) - } - +impl net::Metrics for Metrics { fn rtt(&self) -> Option { self.rtt } diff --git a/swift/MIGRATE.md b/swift/MIGRATE.md index 3eb2a684b7f..8b0c265707b 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 +### `Allocator` ([#6751](https://github.com/moq-dev/moq/pull/6751)) + +`Bandwidth` is `Allocator`, `Session.bandwidth()` is `allocator()`, and `Reservation.grant()` is `rate()`. `Bandwidth.Consumer`, returned by `recvBandwidth()`, is the top-level `BandwidthConsumer`. The producers' `bandwidth:` parameter keeps its name. + ### Decoders read gaps and ends `Audio.Consumer` and `Video.Consumer` yield `Audio.Read` / `Video.Read` instead of frames. Match `case .frame(let frame)` where you used each element as a frame; `.gap(timestampUs:duration:)` marks lost media and `.end(endUs:)` where the publisher stopped its encoder, and what follows either does not continue what came before. diff --git a/swift/Sources/Moq/Audio.swift b/swift/Sources/Moq/Audio.swift index 080093e2176..56abcdbbac7 100644 --- a/swift/Sources/Moq/Audio.swift +++ b/swift/Sources/Moq/Audio.swift @@ -34,7 +34,7 @@ public enum Audio { input: EncoderInput, output: EncoderOutput, track: String? = nil, - bandwidth: Bandwidth? = nil + bandwidth: Allocator? = nil ) throws { ffi = try MoqAudioProducer( catalog: catalog.ffi, diff --git a/swift/Sources/Moq/Bandwidth.swift b/swift/Sources/Moq/Bandwidth.swift index 910dafeed91..917b4199046 100644 --- a/swift/Sources/Moq/Bandwidth.swift +++ b/swift/Sources/Moq/Bandwidth.swift @@ -1,29 +1,29 @@ import MoqFFI -/// Divides one connection's send estimate among the tracks sharing it. -/// -/// Minted by `Session.bandwidth`. Handles from the same session share one -/// reservation registry. -public final class Bandwidth: Sendable { - /// An owned bandwidth estimate, in bits per second. - public final class Consumer: Sendable { - let ffi: MoqBandwidthConsumer +/// An owned bandwidth estimate, in bits per second, returned by `Session.recvBandwidth()`. +public final class BandwidthConsumer: Sendable { + let ffi: MoqBandwidthConsumer - init(_ ffi: MoqBandwidthConsumer) { self.ffi = ffi } + init(_ ffi: MoqBandwidthConsumer) { self.ffi = ffi } - /// The current estimate, or nil while unavailable. - public func rate() -> UInt64? { ffi.rate() } + /// The current estimate, or nil while unavailable. + public func rate() -> UInt64? { ffi.rate() } - /// Wait for the estimate to change and return the new rate, throwing when its producer closes. - public func rateChanged() async throws -> UInt64? { try await ffi.rateChanged() } + /// Wait for the estimate to change and return the new rate, throwing when its producer closes. + public func rateChanged() async throws -> UInt64? { try await ffi.rateChanged() } - /// Release this consumer's demand, including a pending wait. - public func cancel() { ffi.cancel() } - } + /// Release this consumer's demand, including a pending wait. + public func cancel() { ffi.cancel() } +} - let ffi: MoqBandwidth +/// Divides one connection's send estimate among the tracks sharing it. +/// +/// Minted by `Session.allocator`. Handles from the same session share one +/// reservation registry. +public final class Allocator: Sendable { + let ffi: MoqAllocator - init(_ ffi: MoqBandwidth) { + init(_ ffi: MoqAllocator) { self.ffi = ffi } @@ -36,10 +36,10 @@ public final class Bandwidth: Sendable { } } -/// One track's standing claim on a `Bandwidth`. +/// One track's standing claim on an `Allocator`. /// -/// `grant()` is a snapshot: `nil` means no estimate, so hold the current rate, -/// and `0` is a real zero grant. While nothing subscribes it is the share the +/// `rate()` is a snapshot: `nil` means no estimate, so hold the current rate, +/// and `0` is a real zero rate. While nothing subscribes it is the share the /// track would get. public final class Reservation: Sendable { let ffi: MoqReservation @@ -49,8 +49,8 @@ public final class Reservation: Sendable { } /// This reservation's slice right now, in bits per second. - public func grant() -> UInt64? { - ffi.grant() + public func rate() -> UInt64? { + ffi.rate() } /// Change the ceiling, keeping the same claim. diff --git a/swift/Sources/Moq/Client.swift b/swift/Sources/Moq/Client.swift index 7a2eababdd9..1a5ec39a438 100644 --- a/swift/Sources/Moq/Client.swift +++ b/swift/Sources/Moq/Client.swift @@ -161,8 +161,8 @@ public final class Session: Sendable { } /// Hold receive-estimate demand until the returned consumer is released. - public func recvBandwidth() -> Bandwidth.Consumer? { - ffi.recvBandwidth().map(Bandwidth.Consumer.init) + public func recvBandwidth() -> BandwidthConsumer? { + ffi.recvBandwidth().map(BandwidthConsumer.init) } /// The session's bandwidth allocator. @@ -171,7 +171,7 @@ public final class Session: Sendable { /// through one are visible to the others. A client handle survives /// reconnects: the grant is `nil` while disconnected and resumes on the /// next connection. - public func bandwidth() -> Bandwidth { - Bandwidth(ffi.bandwidth()) + public func allocator() -> Allocator { + Allocator(ffi.allocator()) } } diff --git a/swift/Sources/Moq/Video.swift b/swift/Sources/Moq/Video.swift index 2e7c2b20c62..5c3140602ea 100644 --- a/swift/Sources/Moq/Video.swift +++ b/swift/Sources/Moq/Video.swift @@ -43,7 +43,7 @@ public enum Video { input: EncoderInput, output: EncoderOutput, track: String? = nil, - bandwidth: Bandwidth? = nil, + bandwidth: Allocator? = nil, lower: Producer? = nil ) throws { ffi = try MoqVideoProducer( diff --git a/test/interop/clients/js/open-gop/main.ts b/test/interop/clients/js/open-gop/main.ts index 87d02089059..99ece7553d9 100644 --- a/test/interop/clients/js/open-gop/main.ts +++ b/test/interop/clients/js/open-gop/main.ts @@ -65,8 +65,7 @@ window.runRecovery = async (packets) => { for (const packet of packets) { if (group?.sequence !== packet.group) { group?.finish(); - group = new Moq.Group.Producer(packet.group); - track.writeGroup(group); + group = track.createGroup(packet.group); } const timestamp = Micro(packet.timestamp); const payload = Uint8Array.from(atob(packet.data), (c) => c.charCodeAt(0)); diff --git a/test/interop/clients/rust/tail.rs b/test/interop/clients/rust/tail.rs index ac55b7946bd..2f0f04f2e3d 100644 --- a/test/interop/clients/rust/tail.rs +++ b/test/interop/clients/rust/tail.rs @@ -134,7 +134,7 @@ async fn main() -> anyhow::Result<()> { if status { // Query before subscribing so draft-18+ must use TRACK_STATUS, // rather than learn metadata from SUBSCRIBE_OK as a side effect. - let info = remote.query().await?; + let info = remote.info().await?; ensure!(info.timescale.is_none(), "IETF track should be untimed"); ensure!(info.priority == 2, "TRACK_STATUS lost publisher priority"); eprintln!("track status answered"); diff --git a/test/interop/track-status.ts b/test/interop/track-status.ts index 2e3cd324988..65cbebf14b3 100644 --- a/test/interop/track-status.ts +++ b/test/interop/track-status.ts @@ -1,7 +1,6 @@ // Answer Rust-encoded TRACK_STATUS requests with the JS publisher, returning each response. import assert from "node:assert/strict"; import { Milli } from "@moq/clock"; -import { Producer as GroupProducer } from "../../js/net/src/group.ts"; import { NativeSession } from "../../js/net/src/ietf/adapter.ts"; import { Publisher } from "../../js/net/src/ietf/publisher.ts"; import { TrackStatusRequest } from "../../js/net/src/ietf/track.ts"; @@ -24,10 +23,9 @@ const broadcastPublication = origin.createBroadcast(Path.from("room")); const broadcast = broadcastPublication.broadcast; broadcastPublication.announce(); const track = broadcast.createTrack("video", { timescale: Timescale.MILLI, maxAge: Milli(5000), priority: 2 }); -const group = new GroupProducer(4); +const group = track.createGroup(4); group.writeFrame({ payload: new Uint8Array([1]), timestamp: Timestamp.fromMillis(0) }); group.writeFrame({ payload: new Uint8Array([2]), timestamp: Timestamp.fromMillis(1) }); -track.writeGroup(group); const publisher = new Publisher({ quic: pair.server, diff --git a/test/wasm/baseline/publisher.ts b/test/wasm/baseline/publisher.ts index 6758fe8bf95..4dc21b26695 100644 --- a/test/wasm/baseline/publisher.ts +++ b/test/wasm/baseline/publisher.ts @@ -30,11 +30,10 @@ async function prepare(config: Workload): Promise { while (demand.peek() === undefined && track.closed.peek() === undefined) await Promise.race([demand.changed(), track.closed]); if (track.closed.peek() !== undefined) return; - const group = new Moq.Group.Producer(config.sequence); + const group = track.createGroup(config.sequence); for (const [frame, bytes] of fixtures.entries()) group.writeFrame({ payload: bytes, timestamp: Moq.Time.Timestamp.fromMillis(frame) }); group.finish(); - track.writeGroup(group); // Keep the track and broadcast served until every reader completes. No timing arm or tail-close race. })(), );