diff --git a/js/net/src/ietf/fetch.test.ts b/js/net/src/ietf/fetch.test.ts index d80259d3c3f..cd3ae2921ea 100644 --- a/js/net/src/ietf/fetch.test.ts +++ b/js/net/src/ietf/fetch.test.ts @@ -36,7 +36,7 @@ const INVALID_RANGE = 0x11; const INVALID_JOINING_REQUEST_ID = 0x32; /** A publisher serving the `room` broadcast, with its `video` track and the client's uni streams. */ -function serve(version: IetfVersion, grant?: Signal) { +function serve(version: IetfVersion, grant?: Signal, priority?: number) { const pair = createMockTransportPair(ALPNS[version]); const origin = new OriginProducer(); const pub = new Publisher({ @@ -48,7 +48,7 @@ function serve(version: IetfVersion, grant?: Signal) { }); const publication = origin.createBroadcast(Path.from("room")); publication.announce(); - const track = publication.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + const track = publication.broadcast.createTrack("video", { timescale: Timescale.MILLI, priority }); const uni = pair.client.incomingUnidirectionalStreams.getReader() as ReadableStreamDefaultReader< ReadableStream >; @@ -326,6 +326,37 @@ test("a FETCH spanning groups is refused before FETCH_OK", async () => { } }); +/** The Publisher Priority each object on a fetch stream states, absent where it inherits. */ +async function priorities(raw: Uint8Array, version: IetfVersion): Promise<(number | undefined)[]> { + const reader = new Reader(undefined, raw, version); + expect(await reader.u53()).toBe(FetchHeader.type); + await FetchHeader.decode(reader, version); + const out: (number | undefined)[] = []; + while (!(await reader.done())) { + const flags = await reader.u53(); + if (flags & 0x08) await reader.u53(); + if (flags & 0x04) await reader.u53(); + out.push(flags & 0x10 ? await reader.u8() : undefined); + if (flags & 0x20) await reader.read(await reader.u53()); + await reader.read(await reader.u53()); + } + return out; +} + +// A fetch stream's first object states the track's Publisher Priority, as a subgroup header +// does, and the rest inherit it. Model priority 72 is wire 55, lower first. +test("a FETCH states the track's priority on its first object", async () => { + for (const version of VERSIONS) { + using fx = serve(version, undefined, 72); + publishPairs(fx.track, 2); + const type = range(version, at(1, 0), at(1, 0)); + const answer = served(await fetch(fx, new Fetch({ requestId: FETCH_ID, type }))); + expect(answer.objects).toEqual(pairs([1])); + expect(answer.ok.properties.priority).toBe(55); + expect(await priorities(answer.raw, version)).toEqual([55, undefined]); + } +}); + // Only a finished track's final object ends it, wherever the range starts or ends. test("a FETCH through the final object reports the end of track", async () => { for (const version of VERSIONS) { @@ -560,7 +591,8 @@ test("draft-18: a joining FETCH serves the head its subscription starts after", await reader.u53(); await FetchHeader.decode(reader, D18); expect(await reader.u53()).toBe(0x3c); - expect([await reader.u53(), await reader.u53(), await reader.u8()]).toEqual([5, 0, 0]); + // The priority is the track's, as FETCH_OK and every subgroup header state it. + expect([await reader.u53(), await reader.u53(), await reader.u8()]).toEqual([5, 0, 127]); await reader.read(await reader.u53()); await reader.read(await reader.u53()); expect(await reader.u53()).toBe(0x20); diff --git a/js/net/src/ietf/ietf.test.ts b/js/net/src/ietf/ietf.test.ts index 0242200518e..452f467985b 100644 --- a/js/net/src/ietf/ietf.test.ts +++ b/js/net/src/ietf/ietf.test.ts @@ -814,17 +814,18 @@ test("Frame reads only the current LOC Timestamp ID on every draft", async () => // A fetch stream's first object is the only one carrying absolute ids, so a wrong flag byte // there silently renumbers every object after it. This codec is the sole serialization path -// for a served fill. +// for a served fill. Its priority is the track's, as a subgroup header's is: model priority +// 72 is wire 55, lower first. test("FetchFrame: the first object carries its absolute ids and the rest inherit them", async () => { const timestamp = new Timestamp(96_000, Timescale.MILLI); - const frame = new FetchFrame({ payload: new Uint8Array([0xaa, 0xbb]), timestamp }); + const frame = new FetchFrame({ payload: new Uint8Array([0xaa, 0xbb]), timestamp, priority: 55 }); const first = await encodeFetchFrameVersioned(frame, { group: 7n, object: 3, first: true }, Version.DRAFT_22); expect(Array.from(first)).toEqual([ 0x3c, // GROUP_ID | OBJECT_ID | PRIORITY | PROPERTIES 7, // group id 3, // object id - 0, // publisher priority + 55, // publisher priority 0x04, // properties length 0x10, // TIMESTAMP 0xc1, @@ -879,7 +880,7 @@ test("FetchEndOfRange: absolute ids and nothing after them", async () => { // The first object after an End of Range has no prior object's priority to inherit, but its // group is still a delta from the marker's. test("FetchFrame: the first object after an End of Range", async () => { - const frame = new FetchFrame({ payload: new Uint8Array([0x01]) }); + const frame = new FetchFrame({ payload: new Uint8Array([0x01]), priority: 0 }); const encoded = await encodeFetchFrameVersioned( frame, { group: 9n, object: 0, first: true, previousGroup: 7n }, @@ -892,7 +893,11 @@ test("FetchFrame: the first object after an End of Range", async () => { // A fetch object has no status field, unlike a subgroup object: a zero payload length is // simply an empty object, and writing a status after it would desync the stream. test("FetchFrame: an empty payload is a zero length, with no status byte", async () => { - const frame = new FetchFrame({ payload: new Uint8Array(), timestamp: new Timestamp(0, Timescale.MILLI) }); + const frame = new FetchFrame({ + payload: new Uint8Array(), + timestamp: new Timestamp(0, Timescale.MILLI), + priority: 0, + }); const encoded = await encodeFetchFrameVersioned(frame, { group: 1n, object: 0, first: true }, Version.DRAFT_22); expect(Array.from(encoded)).toEqual([ @@ -911,7 +916,7 @@ test("FetchFrame: an empty payload is a zero length, with no status byte", async // omitted rather than carrying a value in units the peer was never told. This is what a // subscriber that sent INCLUDE_PROPERTIES=0 gets. test("FetchFrame: an unstamped object omits the properties field", async () => { - const frame = new FetchFrame({ payload: new Uint8Array([0x01]) }); + const frame = new FetchFrame({ payload: new Uint8Array([0x01]), priority: 0 }); const encoded = await encodeFetchFrameVersioned(frame, { group: 0n, object: 0, first: false }, Version.DRAFT_22); // Flags 0 (subgroup zero, no fields present), then the payload. @@ -920,7 +925,7 @@ test("FetchFrame: an unstamped object omits the properties field", async () => { // The first object still carries its absolute ids and priority; only the properties go. test("FetchFrame: an unstamped first object keeps its ids", async () => { - const frame = new FetchFrame({ payload: new Uint8Array([0x01]) }); + const frame = new FetchFrame({ payload: new Uint8Array([0x01]), priority: 0 }); const encoded = await encodeFetchFrameVersioned(frame, { group: 4n, object: 2, first: true }, Version.DRAFT_22); expect(Array.from(encoded)).toEqual([ diff --git a/js/net/src/ietf/join.test.ts b/js/net/src/ietf/join.test.ts index 2bb9938df14..9cb0a6563bf 100644 --- a/js/net/src/ietf/join.test.ts +++ b/js/net/src/ietf/join.test.ts @@ -115,7 +115,7 @@ async function head(requestId: bigint, payloads: string[], group = GROUP, versio const bytes = await Writer.collect(version, async (w) => { await w.u62(requestId); for (const [object, payload] of payloads.entries()) { - await new FetchFrame({ payload: text(payload) }).encode( + await new FetchFrame({ payload: text(payload), priority: 0 }).encode( w, { group, object, first: object === 0 }, undefined, @@ -394,7 +394,7 @@ async function deltaHead(requestId: bigint, payloads: string[], delta: number) { await w.u62(requestId); for (const [object, payload] of payloads.entries()) { if (object === 0) { - await new FetchFrame({ payload: text(payload) }).encode( + await new FetchFrame({ payload: text(payload), priority: 0 }).encode( w, { group: GROUP, object, first: true }, undefined, @@ -455,13 +455,13 @@ test("a joining FETCH spanning another group drops the head", async () => { const bytes = await Writer.collect(VERSION, async (w) => { await w.u62(fetch.requestId); - await new FetchFrame({ payload: text("h0") }).encode( + await new FetchFrame({ payload: text("h0"), priority: 0 }).encode( w, { group: GROUP, object: 0, first: true }, undefined, VERSION, ); - await new FetchFrame({ payload: text("x0") }).encode( + await new FetchFrame({ payload: text("x0"), priority: 0 }).encode( w, { group: GROUP + 1n, object: 0, first: false, previousGroup: GROUP }, undefined, @@ -550,13 +550,13 @@ test("a clean end finishes a head nothing claimed", () => { test("fetch objects decode as FetchFrame wrote them", async () => { const bytes = await Writer.collect(VERSION, async (w) => { - await new FetchFrame({ payload: text("a") }).encode( + await new FetchFrame({ payload: text("a"), priority: 0 }).encode( w, { group: 5n, object: 0, first: true }, undefined, VERSION, ); - await new FetchFrame({ payload: new Uint8Array() }).encode( + await new FetchFrame({ payload: new Uint8Array(), priority: 0 }).encode( w, { group: 5n, object: 1, first: false }, undefined, diff --git a/js/net/src/ietf/object.ts b/js/net/src/ietf/object.ts index 9630317c62f..48a33628352 100644 --- a/js/net/src/ietf/object.ts +++ b/js/net/src/ietf/object.ts @@ -423,10 +423,16 @@ export class FetchFrame { payload: Uint8Array; /** The presentation timestamp carried in object properties, when present. */ timestamp?: Timestamp; + /** + * The track's Publisher Priority on the wire, which the stream's first object states for + * every object after it, as a subgroup header does. + */ + priority: number; - constructor({ payload, timestamp }: { payload: Uint8Array; timestamp?: Timestamp }) { + constructor({ payload, timestamp, priority }: { payload: Uint8Array; timestamp?: Timestamp; priority: number }) { this.payload = payload; this.timestamp = timestamp; + this.priority = priority; } /** @@ -459,7 +465,7 @@ export class FetchFrame { ), encodeVarint(position.object, version), ); - if (position.first) header.push(Uint8Array.of(0)); + if (position.first) header.push(Uint8Array.of(this.priority)); } else { // Same group and priority; the Object ID is the prior one plus one. header.push(encodeVarint(stamped ? FETCH_PROPERTIES : 0, version)); diff --git a/js/net/src/ietf/publisher.test.ts b/js/net/src/ietf/publisher.test.ts index 983494d2998..a4d14dac0d9 100644 --- a/js/net/src/ietf/publisher.test.ts +++ b/js/net/src/ietf/publisher.test.ts @@ -4188,6 +4188,88 @@ test("draft-22: cancellation releases a fill parked on flow control", async () = } }); +// A fill reads the cache through forks of its own, ranked at the converted subscriber +// priority. Copied unconverted, wire 100 would raise the track's aggregate from 27 to 100, +// and wire 191 is outside the model's -128..=127, so the fork throws and the fill never runs. +test("draft-22: a SUBSCRIBE's fill reads the cache at the converted subscriber priority", async () => { + const fx = fixture(); + const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + writeGroup(track, 2); + const { client } = await runSubscribe( + fx, + new Subscribe({ + requestId: 0n, + trackNamespace: Path.from("test"), + trackName: "video", + subscriberPriority: 191, + filter: { kind: "absolute", startGroup: 10n, startObject: 0n }, + fill: { filter: { kind: "unfiltered" }, rangeFilters: false }, + }), + ); + try { + expect(track.subscription.peek()?.priority).toBe(-64); + const stream = await nextUni(fx.uni); + if (!stream) throw new Error("missing fill stream"); + const served = await readFill(new Reader(stream, undefined, V22), "ascending"); + expect(served.reset).toBeUndefined(); + expect(served.objects).toEqual([0, 1].map((id) => ({ group: 0, id, payload: `0.${id}` }))); + } finally { + client.close(); + track.finish(); + track.close(); + fx.close(); + } +}); + +test("draft-22: an update's fill reads the cache at the converted subscriber priority", async () => { + for (const [wire, model] of [ + [100, 27], + [191, -64], + ]) { + const fx = fixture(); + const parked = Promise.withResolvers(); + const stalled = new WritableStream({ + write() { + parked.resolve(); + return new Promise(() => {}); + }, + }); + const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); + writeGroup(track, 1); + const { client } = await runSubscribe( + fx, + new Subscribe({ + requestId: 0n, + trackNamespace: Path.from("test"), + trackName: "video", + subscriberPriority: wire, + filter: { kind: "absolute", startGroup: 10n, startObject: 0n }, + }), + ); + try { + expect(track.subscription.peek()?.priority).toBe(model); + spyOn(fx.pair.server, "createUnidirectionalStream").mockImplementationOnce(async () => stalled); + const parameters = new Parameters(); + parameters.fillParameters = Filter.encodeFill( + { filter: { kind: "unfiltered" }, groupOrder: "ascending", rangeFilters: false }, + fx.version, + ); + await client.writer.u53(SubscribeUpdate.id); + await new SubscribeUpdate({ requestId: 2n, parameters }).encode(client.writer, fx.version); + expect(await client.reader.u53()).toBe(RequestOk.id); + await RequestOk.decode(client.reader, fx.version); + // The fill is parked writing its header, so the fork it reads through is still live. + await parked.promise; + expect(track.subscription.peek()?.priority, `wire ${wire}`).toBe(model); + } finally { + client.close(); + track.finish(); + track.close(); + fx.close(); + } + } +}); + test("draft-22: narrowing gives up an excluded group's open stream", async () => { const fx = fixture(); const track = fx.broadcast.createTrack("video", { timescale: Timescale.MILLI }); diff --git a/js/net/src/ietf/publisher.ts b/js/net/src/ietf/publisher.ts index 22bc49b9ef2..43f59665270 100644 --- a/js/net/src/ietf/publisher.ts +++ b/js/net/src/ietf/publisher.ts @@ -273,6 +273,9 @@ interface RunFill { /** The subscriber's delivery priority, applied to the cache subscription the fill reads. */ priority: number; + /** The track's Publisher Priority on the wire, which the fill's first object states. */ + publisherPriority: number; + /** * The subscription's ranking. The fill joins it as the group it fills, so backfill goes out * in the subscription's GROUP_ORDER rather than ahead of the live groups or behind them all. @@ -747,6 +750,7 @@ export class Publisher { namespace: name, properties, timescale, + publisherPriority, ranking: ranked, } : { kind: "unsupported" }, @@ -796,6 +800,7 @@ export class Publisher { filling = this.#runFill({ requestId, priority: fromWire(msg.subscriberPriority), + publisherPriority, ranking: ranked, fill: selected, cache: source, @@ -1358,7 +1363,8 @@ export class Publisher { * fill-failure signal. Nothing here touches the subscription either way. */ async #runFill(options: RunFill) { - const { requestId, ranking, fill, cache, timescale, unsubscribed, cancelled, streams } = options; + const { requestId, ranking, fill, cache, timescale, publisherPriority, unsubscribed, cancelled, streams } = + options; const version = this.#session.version; // Everything is inside the try so the cache fork is released on every path out, @@ -1388,7 +1394,7 @@ export class Publisher { throw new Error("fill is not supported"); } - const out = new FetchWriter({ stream, version, timescale }); + const out = new FetchWriter({ stream, version, timescale, priority: publisherPriority }); const group = hooks.cachedGroup(cache, fill.start.group); if (!group) throw new NotFound("fill group unavailable"); try { @@ -2445,6 +2451,7 @@ export class Publisher { ok: new FetchOk({ endOfTrack, endLocation, properties: trackProperties(info, msg.propertiesWanted) }), // A Timestamp goes out only when FETCH_OK actually carries TIMESCALE. timescale: msg.propertiesWanted ? (info.timescale ?? undefined) : undefined, + publisherPriority: toWire(info.priority), // Its own rank, so it competes with group streams by its priority alone. sendOrder: sendOrder({ priority }), }; @@ -2538,6 +2545,7 @@ export class Publisher { // Where the subscription starts, never the end of the track. ok: new FetchOk({ endOfTrack: false, endLocation: end, properties: join.properties }), timescale: join.timescale, + publisherPriority: join.publisherPriority, // Ranked as the group it heads, ahead of that group's live rest. sendOrder: join.ranking.rank(sequence, 0), ranking: join.ranking, @@ -2550,7 +2558,7 @@ export class Publisher { */ async #answerFetch(msg: Fetch, request: RequestStream, answer: FetchAnswer, stop: AbortSignal) { const version = this.#session.version; - const { range, last, timescale, ranking } = answer; + const { range, last, timescale, publisherPriority, ranking } = answer; let stream: Writer | undefined; try { @@ -2566,7 +2574,7 @@ export class Publisher { ranking?.add(stream, range.start.group, safe(range.start.object)); await untilAborted(new FetchHeader({ requestId: msg.requestId }).encode(stream, version), stop); - const out = new FetchWriter({ stream, version, timescale }); + const out = new FetchWriter({ stream, version, timescale, priority: publisherPriority }); for (const frame of last.frames) await out.object(last.sequence, frame, stop); stream.close(); // The request stream ends once the answer is delivered. @@ -2676,6 +2684,8 @@ type Joinable = properties: Properties.Properties; /** The units the subscription stamps objects in, if any; see {@link RunGroup.timescale}. */ timescale?: Timescale; + /** The track's Publisher Priority on the wire, which the fetch's first object states. */ + publisherPriority: number; /** The subscription's ranking, which the fetch stream joins as the group it heads. */ ranking: Priority; }; @@ -2700,6 +2710,8 @@ interface FetchAnswer { ok: FetchOk; /** The units objects are stamped in, if any; see {@link RunGroup.timescale}. */ timescale?: Timescale; + /** The track's Publisher Priority on the wire, which the stream's first object states. */ + publisherPriority: number; /** The fetch stream's send order. */ sendOrder: number; /** The subscription ranking the fetch stream joins, if any. */ @@ -2780,21 +2792,25 @@ class FetchWriter { readonly stream: Writer; readonly #version: IetfVersion; readonly #timescale: Timescale | undefined; + /** The track's Publisher Priority on the wire, which the first object states for all. */ + readonly #priority: number; #written = false; constructor({ stream, version, timescale, - }: { stream: Writer; version: IetfVersion; timescale: Timescale | undefined }) { + priority, + }: { stream: Writer; version: IetfVersion; timescale: Timescale | undefined; priority: number }) { this.stream = stream; this.#version = version; this.#timescale = timescale; + this.#priority = priority; } /** Write `frame` of group `sequence`, following the prior object of that group, if any. */ async object(sequence: bigint, frame: { sequence: number } & group.Frame, stop: AbortSignal): Promise { - const obj = new FetchFrame({ payload: frame.payload, timestamp: frame.timestamp }); + const obj = new FetchFrame({ payload: frame.payload, timestamp: frame.timestamp, priority: this.#priority }); const position = { group: sequence, object: frame.sequence, diff --git a/rs/moq-net/src/ietf/publisher.rs b/rs/moq-net/src/ietf/publisher.rs index c773f9fd1c7..6b5de430b70 100644 --- a/rs/moq-net/src/ietf/publisher.rs +++ b/rs/moq-net/src/ietf/publisher.rs @@ -114,22 +114,6 @@ enum FetchPrior { None, /// The next object of the same group. Same(Option), - /// The first object of a group after another one's, carrying its Group ID field. - Group(u64), -} - -/// Where a fetch object sits, given the group written before its own, if any. -fn fetch_position(prior_group: Option, group: u64, prior: Option, object: u64) -> Result { - match (prior_group, prior) { - // A later group is spelled as its distance from the prior one, less one. - (Some(prior_group), None) => Ok(FetchPrior::Group( - group - .abs_diff(prior_group) - .checked_sub(1) - .ok_or(Error::MalformedTrack)?, - )), - _ => fetch_prior(prior, object), - } } /// The span a FETCH answers, as a standalone FETCH spells it. @@ -309,6 +293,8 @@ struct FetchObjectInfo<'a> { sequence: u64, object: u64, prior: FetchPrior, + /// The track's Publisher Priority on the wire, which the first object states for all. + priority: u8, timestamp: Option, inflated: Option, timescale: Option, @@ -2555,6 +2541,8 @@ impl Publisher { let res = async { stream.varint(FetchHeader::TYPE).await?; stream.encode(&FetchHeader { request_id }).await?; + // Resolved already: the subscription this fills described the track. + let publisher_priority = super::priority::to_wire(track.info().await?.priority); let FillServe::Group { sequence, skip, until } = fill else { return Err(Error::Unsupported); @@ -2580,7 +2568,7 @@ impl Publisher { GroupSlice { skip, until }, timescale, self.version, - &mut None, + publisher_priority, ) .await?; Ok(()) @@ -2615,7 +2603,7 @@ impl Publisher { slice: GroupSlice, timescale: Option, version: Version, - prior_group: &mut Option, + priority: u8, ) -> Result<(), Error> { let GroupSlice { skip, until } = slice; let mut index: u64 = 0; @@ -2673,7 +2661,8 @@ impl Publisher { FetchObjectInfo { sequence, object: index, - prior: fetch_position(*prior_group, sequence, prior, index)?, + prior: fetch_prior(prior, index)?, + priority, timestamp: frame.timestamp, inflated: frame.inflated, timescale, @@ -2721,7 +2710,8 @@ impl Publisher { FetchObjectInfo { sequence, object: index, - prior: fetch_position(*prior_group, sequence, prior, index)?, + prior: fetch_prior(prior, index)?, + priority, timestamp: frame.timestamp, inflated: frame.inflated, timescale, @@ -2760,10 +2750,6 @@ impl Publisher { if until.is_some_and(|until| index < until) { return Err(Error::NotFound); } - - if prior.is_some() { - *prior_group = Some(sequence); - } Ok(()) } @@ -2776,6 +2762,7 @@ impl Publisher { sequence, object, prior, + priority, timestamp, inflated, timescale, @@ -2806,12 +2793,13 @@ impl Publisher { let header = match prior { // The first object must carry its absolute Group and Object IDs. Include the - // priority too: "same as the prior object" has no prior to refer to. + // priority too: "same as the prior object" has no prior to refer to. It is the + // track's, as a subgroup header's Publisher Priority is. FetchPrior::None => ietf::FetchObject::Object { subgroup: ietf::FetchSubgroup::Zero, group: Some(sequence), object: Some(object), - priority: Some(0), + priority: Some(priority), properties, }, // Same group and priority; the Object ID is the prior one plus one. @@ -2822,14 +2810,6 @@ impl Publisher { priority: None, properties, }, - // A new group restates its Object ID absolutely, and keeps the prior priority. - FetchPrior::Group(group) => ietf::FetchObject::Object { - subgroup: ietf::FetchSubgroup::Zero, - group: Some(group), - object: Some(object), - priority: None, - properties, - }, }; stream.encode(&header).await?; @@ -2837,22 +2817,21 @@ impl Publisher { Ok(()) } - /// Write one group's objects to a fetch stream, after those of `prior_group`, which it - /// becomes once the group wrote any. + /// Write one group's objects to a fetch stream, which carries no other group. async fn write_fetched_group( writer: &mut Writer, Version>, group: FetchedGroup, - prior_group: &mut Option, version: Version, timescale: Option, ) -> Result<(), Error> { let source = group.info.ietf(); + let priority = super::priority::to_wire(group.info.priority); let mut prior = None; let mut budget = kio::coop::Budget::new(32); for (ordinal, frame) in (group.first..).zip(group.frames) { kio::wait(|waiter| budget.poll_yield(waiter)).await; let object = frame.fields.as_ref().map_or(ordinal, |fields| fields.id); - let position = fetch_position(*prior_group, group.sequence, prior, object)?; + let position = fetch_prior(prior, object)?; prior = Some(object); Self::write_fetch_object( writer, @@ -2860,6 +2839,7 @@ impl Publisher { sequence: group.sequence, object, prior: position, + priority, timestamp: frame.timestamp, inflated: frame.inflated, timescale, @@ -2871,9 +2851,6 @@ impl Publisher { .await?; Self::write_fetch_payload(writer, frame.frame.payload).await?; } - if prior.is_some() { - *prior_group = Some(group.sequence); - } Ok(()) } @@ -3322,8 +3299,7 @@ impl Publisher { request_id: msg.request_id, }) .await?; - let mut prior_group = None; - Self::write_fetched_group(&mut writer, group, &mut prior_group, self.version, timescale).await?; + Self::write_fetched_group(&mut writer, group, self.version, timescale).await?; settle(&mut writer).await?; Ok::<(), Error>(()) }; @@ -10986,7 +10962,8 @@ mod serve_tests { if index == 0 { assert_eq!(crate::coding::decode_varint(&mut buf, version).unwrap(), LATEST); assert_eq!(crate::coding::decode_varint(&mut buf, version).unwrap(), 0); - assert_eq!(bytes::Buf::try_get_u8(&mut buf).unwrap(), 0); + // The track's Publisher Priority, as FETCH_OK states it: unset is wire 127. + assert_eq!(bytes::Buf::try_get_u8(&mut buf).unwrap(), 127); } let properties = crate::coding::decode_buf(&mut buf, version, |r, _| Ok(r.bytes()?.to_vec())).unwrap(); assert!(!properties.is_empty(), "{version}: missing Timestamp"); @@ -12221,6 +12198,93 @@ mod serve_tests { } } + /// The Publisher Priority each object on a fetch stream states, after its FETCH_HEADER. + fn fetch_object_priorities(buf: &mut Decoder<'_>, version: Version) -> Vec> { + assert_eq!(buf.varint().unwrap(), FetchHeader::TYPE, "{version}"); + FetchHeader::decode(buf, version).unwrap(); + let mut priorities = Vec::new(); + while !buf.is_empty() { + let ietf::FetchObject::Object { priority, .. } = ietf::FetchObject::decode(buf, version).unwrap() else { + panic!("{version}: unexpected End of Range"); + }; + let size = buf.varint().unwrap() as usize; + buf.slice(size).unwrap(); + priorities.push(priority); + } + priorities + } + + /// A fetch stream's first object states the track's Publisher Priority, as a subgroup + /// header does, and every later one inherits it. Model 72 is wire 55 (lower first). + #[kio::test] + async fn a_standalone_fetch_states_the_track_priority() { + for version in FETCH_DRAFTS { + let mut h = serve_track( + version, + track::Info { + priority: 72, + ..track::Info::timed() + }, + ); + publish_pairs(&mut h, 3, None); + settle().await; + + let wire = standalone_fetch( + &h, + Location { group: 2, object: 0 }, + Location { group: 2, object: 0 }, + GroupOrder::Ascending, + ) + .await; + let mut buf = Decoder::new(&wire, version.into()); + assert_eq!(buf.varint().unwrap(), ietf::FetchOk::ID, "{version}"); + ietf::FetchOk::decode(&mut buf, version).unwrap(); + assert_eq!( + fetch_object_priorities(&mut buf, version), + [Some(55), None], + "{version}" + ); + } + } + + /// A fill's fetch stream states the track's Publisher Priority the same way. + #[kio::test] + async fn a_fill_states_the_track_priority() { + let version = Version::Draft22; + let h = serve_track( + version, + track::Info { + priority: 72, + ..track::Info::timed() + }, + ); + let mut group = h.track.create_group(group::Info { sequence: 4 }).unwrap(); + group.write_frame(timestamp(), b"fill".as_slice()).unwrap(); + group.finish().unwrap(); + + let ranking = Ranking { + queue: h.publisher.priority.clone(), + group: None, + request_id: RequestId(REQUEST_ID), + priority: kio::Producer::new(PRIORITY).consume(), + publisher: 0, + order: Order::Descending, + lapse: Lapse::default(), + }; + let opened = AtomicU64::new(0); + let fill = FillServe::Group { + sequence: 4, + skip: 0, + until: None, + }; + h.publisher + .run_fill(fill, &ranking, h.track.consume(), None, &opened, ranking.request_id) + .await; + let wire = bytes::Bytes::from(h.log.writes.lock().unwrap().to_vec()); + let mut buf = Decoder::new(&wire, version.into()); + assert_eq!(fetch_object_priorities(&mut buf, version), [Some(55)]); + } + /// The Track Properties block a publisher upstream of a relay sent on `version`: an even /// property the draft defines but moq-net does not implement (OBJECT_DELIVERY_TIMEOUT), /// and an odd one from the application range.