diff --git a/js/net/src/broadcast.ts b/js/net/src/broadcast.ts index 8f78e993a9b..fa94ed42dd8 100644 --- a/js/net/src/broadcast.ts +++ b/js/net/src/broadcast.ts @@ -6,7 +6,7 @@ import { type GetPromise, Once, Signal } from "@moq/signals"; import { NotFound } from "./error.ts"; import type { Consumer as GroupConsumer } from "./group.ts"; -import { type Hop, Route, randomHop } from "./hop.ts"; +import { Route } from "./hop.ts"; import { hooks, type TrackSequence } from "./internal.ts"; import * as Path from "./path.ts"; import * as track from "./track.ts"; @@ -34,17 +34,6 @@ class BroadcastState { // Live consumer handles sharing this state (see {@link Consumer.clone}). The broadcast // closes once the last one closes, so a shared consumer can be handed to several callers. consumers = 0; - // The origin serving this broadcast (see the wire's `origin`): named by an upstream - // reply, or generated on first use for content nobody named. - origin?: Hop; -} - -// The origin a peer is told serves this broadcast: proxied from upstream, or a random -// one for content originating here, stable for the broadcast's life and shared by every -// session serving it. -function origin(state: BroadcastState): Hop { - state.origin ??= randomHop(); - return state.origin; } function dequeueRequest(state: BroadcastState): track.Request | undefined { @@ -258,10 +247,6 @@ export class Producer { resolveTrackInfo: (name) => resolveTrackInfo(this.#state, name), fetchGroup: (name, sequence, options) => fetchGroup(this.#state, name, sequence, options), requested: () => this.#requested(), - origin: () => origin(this.#state), - name: (named) => { - this.#state.origin = named; - }, }; } @@ -335,10 +320,6 @@ export class Consumer { resolveTrackInfo: (name) => resolveTrackInfo(this.#state, name), fetchGroup: (name, sequence, options) => fetchGroup(this.#state, name, sequence, options), requested: () => this.#requested(), - origin: () => origin(this.#state), - name: (named) => { - this.#state.origin = named; - }, }); } diff --git a/js/net/src/lite/fetch.test.ts b/js/net/src/lite/fetch.test.ts index eb484a7f590..a38cb9160c8 100644 --- a/js/net/src/lite/fetch.test.ts +++ b/js/net/src/lite/fetch.test.ts @@ -51,13 +51,14 @@ test("FetchOk names the origin on draft-07 only", async () => { const written: Uint8Array[] = []; const writer = new Writer( new WritableStream({ write: (chunk) => void written.push(new Uint8Array(chunk)) }), + Version.DRAFT_07, ); await new FetchOk(HopSchema.parse(42n)).encode(writer, Version.DRAFT_07); writer.close(); await writer.closed; const buf = concat(written); expect(buf).toEqual(new Uint8Array([1, 42])); - const got = await FetchOk.decode(new Reader(undefined, buf), Version.DRAFT_07); + const got = await FetchOk.decode(new Reader(undefined, buf, Version.DRAFT_07), Version.DRAFT_07); expect(got.origin).toBe(HopSchema.parse(42n)); await expect(new FetchOk(HopSchema.parse(42n)).encode(writer, Version.DRAFT_06)).rejects.toThrow(); diff --git a/js/net/src/lite/origin.test.ts b/js/net/src/lite/origin.test.ts index 6518cb44ef7..6670ac3075e 100644 --- a/js/net/src/lite/origin.test.ts +++ b/js/net/src/lite/origin.test.ts @@ -1,13 +1,21 @@ import { expect, test } from "bun:test"; -import * as broadcast from "../broadcast.ts"; -import { HopSchema, randomHop, UNKNOWN_HOP } from "../hop.ts"; +import { Producer as GroupProducer } from "../group.ts"; +import { type Hop, HopSchema, randomHop } from "../hop.ts"; import { createMockTransportPair } from "../mock.ts"; +import { Producer as OriginProducer } from "../origin.ts"; import * as Path from "../path.ts"; import { Reader, Stream } from "../stream.ts"; -import { wireOf } from "../wire.ts"; +import { Fetch, FetchOk } from "./fetch.ts"; import { Group as GroupMessage } from "./group.ts"; +import { Publisher } from "./publisher.ts"; import { StreamId } from "./stream.ts"; -import { encodeSubscribeResponse, Subscribe, SubscribeStart } from "./subscribe.ts"; +import { + decodeSubscribeResponse, + encodeSubscribeResponse, + Subscribe, + SubscribeEnd, + SubscribeStart, +} from "./subscribe.ts"; import { Subscriber } from "./subscriber.ts"; import { TrackInfo, Track as TrackMessage } from "./track.ts"; import { ALPN_07_WIP, Version } from "./version.ts"; @@ -27,30 +35,142 @@ async function settlesWithin(promise: Promise, ms: number): Promise { - const producer = new broadcast.Producer(); - const origin = wireOf(producer).origin(); - expect(origin).not.toBe(UNKNOWN_HOP); - expect(wireOf(producer).origin()).toBe(origin); - // Every handle, and so every session serving it, names the same one. - expect(wireOf(producer.consume()).origin()).toBe(origin); - expect(wireOf(new broadcast.Producer()).origin()).not.toBe(origin); +// Serve one SUBSCRIBE and one FETCH of `track` over a fresh draft-07 session publishing `origin`, +// returning the origins its SUBSCRIBE_START and FETCH_OK name. +async function servedOrigins(origin: OriginProducer, track: string): Promise<[Hop, Hop]> { + const pair = createMockTransportPair(ALPN_07_WIP); + const publisher = new Publisher(pair.server, VERSION, randomHop(), origin.consume()); + + const sub = await Stream.open(pair.client, { version: VERSION }); + const serving = await Stream.accept(pair.server, VERSION); + if (!serving) throw new Error("the publisher never accepted the subscribe stream"); + void publisher.runSubscribe(new Subscribe({ id: 0n, broadcast: Path.from("room"), track, priority: 0 }), serving); + const start = await decodeSubscribeResponse(sub.reader, VERSION); + if (!("start" in start)) throw new Error("expected SUBSCRIBE_START"); + + const fetch = await Stream.open(pair.client, { version: VERSION }); + const fetching = await Stream.accept(pair.server, VERSION); + if (!fetching) throw new Error("the publisher never accepted the fetch stream"); + void publisher.runFetch(new Fetch({ broadcast: Path.from("room"), track, priority: 0, group: 0 }), fetching); + const ok = await FetchOk.decode(fetch.reader, VERSION); + + publisher.close(); + sub.close(); + fetch.close(); + return [start.start.origin, ok.origin]; +} + +// JS publishes only what it produces, so the origin it names is its own: one identity per +// origin, shared by every session serving it (Rust's `origin.hop()`). A relay failing over +// from one session to another sees the same origin and resumes rather than ending the broadcast. +test("every draft-07 session serving an origin names the same origin", async () => { + const origin = new OriginProducer(); + const produced = origin.createBroadcast(Path.from("room")); + produced.announce(); + const track = produced.createTrack("video"); + const group = new GroupProducer(0); + group.writeString("x"); + group.close(); + track.writeGroup(group); + + const [start, fetched] = await servedOrigins(origin, "video"); + expect(fetched).toBe(start); + expect(await servedOrigins(origin, "video")).toEqual([start, start]); + + const other = new OriginProducer(); + const elsewhere = other.createBroadcast(Path.from("room")); + elsewhere.announce(); + elsewhere.createTrack("video").writeGroup(group); + expect((await servedOrigins(other, "video"))[0]).not.toBe(start); +}); + +// Plays the upstream publisher on a mock draft-07 session, answering the subscriber's streams. +class Upstream { + readonly pair = createMockTransportPair(ALPN_07_WIP); + readonly subscriber = new Subscriber(this.pair.client, VERSION, randomHop()); + + // Answer a TRACK stream, then accept and start the SUBSCRIBE that follows it at group 0, + // naming `origin`. + async subscribe(origin: Hop): Promise { + const info = await Stream.accept(this.pair.server, VERSION); + if (!info) throw new Error("the subscriber never asked for TRACK_INFO"); + expect(await info.reader.u53()).toBe(StreamId.Track); + await TrackMessage.decode(info.reader, VERSION); + await new TrackInfo({ maxAge: 60_000 }).encode(info.writer, VERSION); + info.close(); + + const sub = await Stream.accept(this.pair.server, VERSION); + if (!sub) throw new Error("the subscriber never subscribed"); + expect(await sub.reader.u53()).toBe(StreamId.Subscribe); + await Subscribe.decode(sub.reader, VERSION); + await this.start(sub, origin); + return sub; + } + + async start(sub: Stream, origin: Hop): Promise { + await encodeSubscribeResponse(sub.writer, { start: new SubscribeStart(0, origin) }, VERSION); + } + + // End a started subscription cleanly with no groups served. + async end(sub: Stream): Promise { + await encodeSubscribeResponse(sub.writer, { end: new SubscribeEnd(0, 0) }, VERSION); + sub.close(); + } +} + +// JS used to keep one origin per broadcast, which the latest reply overwrote. Each track copy +// now keeps its own, so two tracks served by different origins are both fine. +test("tracks of one broadcast keep the origins their own replies named", async () => { + const upstream = new Upstream(); + const consumer = upstream.subscriber.consume(Path.from("room")); + + const video = consumer.track("video").subscribe({}); + const videoSub = await upstream.subscribe(HopSchema.parse(42n)); + const audio = consumer.track("audio").subscribe({}); + const audioSub = await upstream.subscribe(HopSchema.parse(43n)); + // Repeating a copy's own origin is not a change. + await upstream.start(videoSub, HopSchema.parse(42n)); + + // Both end cleanly, after every START was read, rather than with a mismatch. + await upstream.end(videoSub); + await upstream.end(audioSub); + expect(await video.closed).toBeNull(); + expect(await audio.closed).toBeNull(); + + upstream.subscriber.close(); +}); + +// Mirrors Rust's track::Provenance: a copy has one origin, so a reply naming another means +// upstream is serving a different track. The copy is dropped rather than relabeled. +test("a SUBSCRIBE_START naming a second origin drops the copy", async () => { + const upstream = new Upstream(); + const consumer = upstream.subscriber.consume(Path.from("room")); + + const reader = consumer.track("video").subscribe({}); + const sub = await upstream.subscribe(HopSchema.parse(42n)); + await upstream.start(sub, HopSchema.parse(43n)); + + const closed = await reader.closed; + expect(closed).toBeInstanceOf(Error); + expect((closed as Error).message).toContain("origin changed"); + + upstream.subscriber.close(); }); -test("a draft-07 group waits for SUBSCRIBE_START, whose origin the broadcast then names", async () => { +test("a draft-07 group waits for SUBSCRIBE_START", async () => { const pair = createMockTransportPair(ALPN_07_WIP); const subscriber = new Subscriber(pair.client, VERSION, randomHop()); const consumer = subscriber.consume(Path.from("room")); const reader = consumer.track("video").subscribe({}); - const info = await Stream.accept(pair.server); + const info = await Stream.accept(pair.server, VERSION); if (!info) throw new Error("the subscriber never asked for TRACK_INFO"); expect(await info.reader.u53()).toBe(StreamId.Track); await TrackMessage.decode(info.reader, VERSION); await new TrackInfo({ maxAge: 60_000 }).encode(info.writer, VERSION); info.close(); - const sub = await Stream.accept(pair.server); + const sub = await Stream.accept(pair.server, VERSION); if (!sub) throw new Error("the subscriber never subscribed"); expect(await sub.reader.u53()).toBe(StreamId.Subscribe); await Subscribe.decode(sub.reader, VERSION); @@ -58,19 +178,20 @@ test("a draft-07 group waits for SUBSCRIBE_START, whose origin the broadcast the // The group's stream races ahead of the subscribe stream. let controller!: ReadableStreamDefaultController; const readable = new ReadableStream({ start: (c) => (controller = c) }); - void subscriber.runGroup(new GroupMessage({ subscribe: 0n, sequence: 0 }), new Reader(readable)); + void subscriber.runGroup( + new GroupMessage({ subscribe: 0n, sequence: 0 }), + new Reader(readable, undefined, VERSION), + ); controller.enqueue(new Uint8Array([0, 1, 120])); controller.close(); const next = reader.recvGroup(); expect(await settlesWithin(next, 50)).toBe(false); - const origin = HopSchema.parse(42n); - await encodeSubscribeResponse(sub.writer, { start: new SubscribeStart(0, origin) }, VERSION); + await encodeSubscribeResponse(sub.writer, { start: new SubscribeStart(0, HopSchema.parse(42n)) }, VERSION); const group = await next; expect(group?.sequence).toBe(0); expect(await group?.readString()).toBe("x"); - // Republishing the broadcast proxies the origin upstream named. - expect(wireOf(consumer).origin()).toBe(origin); + subscriber.close(); }); diff --git a/js/net/src/lite/publisher.ts b/js/net/src/lite/publisher.ts index 84be2288f22..c7069a47fc4 100644 --- a/js/net/src/lite/publisher.ts +++ b/js/net/src/lite/publisher.ts @@ -380,6 +380,10 @@ export class Publisher { #publish?: OriginConsumer; + // The origin named in SUBSCRIBE_START and FETCH_OK: the published origin's identity, shared by + // every session serving it. Unused without one, since nothing is served. + #origin: Hop; + // TRACK_INFO is immutable per track, so resolve it from the application once // (via a throwaway subscribe whose info() resolves when the app calls accept) // and reuse it for every later TRACK request of the same track. Keyed by the @@ -404,6 +408,7 @@ export class Publisher { const origin = publish && wireOf(publish); this.#advertised = origin?.advertised ?? new Signal(new Map()); this.#publish = publish; + this.#origin = origin?.hop ?? hop; // Grab the datagram writer up front when the transport carries datagrams (no group // fallback, so it stays undefined otherwise). One writer for all subscriptions. @@ -670,9 +675,8 @@ export class Publisher { start: { included: sequence }, end: bounds.endGroup === undefined ? undefined : { included: bounds.endGroup }, }); - // Read once content flowed: an upstream's SUBSCRIBE_START named the origin - // before any of its content did. - const start = new SubscribeStart(sequence, wireOf(front).origin()); + // JS publishes only what it produces, so the origin serving it is ours. + const start = new SubscribeStart(sequence, this.#origin); await encodeSubscribeResponse(stream.writer, { start }, this.version); }); @@ -742,7 +746,7 @@ export class Publisher { const info = await this.#resolveTrackInfo(front, msg.track); group = await wireOf(front).fetchGroup(msg.track, msg.group, { priority: msg.priority }); if (hasOrigin(this.version)) { - await new FetchOk(wireOf(front).origin()).encode(stream.writer, this.version); + await new FetchOk(this.#origin).encode(stream.writer, this.version); } await this.#runFetchGroup(group, stream.writer, { timescale: Timescale(info.timescale), diff --git a/js/net/src/lite/subscriber.test.ts b/js/net/src/lite/subscriber.test.ts index 93ad01dc37e..f14cd4dca70 100644 --- a/js/net/src/lite/subscriber.test.ts +++ b/js/net/src/lite/subscriber.test.ts @@ -1,6 +1,5 @@ import { expect, spyOn, test } from "bun:test"; import { Signal } from "@moq/signals"; -import { Producer as BroadcastProducer } from "../broadcast.ts"; import type { Probe as ProbeStats } from "../connection/stats.ts"; import { error, fromTransport, reason, StreamCode, StreamError } from "../error.ts"; import { HopSchema, isAnonymous, MAX_HOPS, Route, UNKNOWN_HOP } from "../hop.ts"; @@ -806,7 +805,7 @@ test.each([ const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); let settled = false; - const fetch = subscriber.fetchGroup(new BroadcastProducer().consume(), Path.from("room"), "video", 0).then( + const fetch = subscriber.fetchGroup(Path.from("room"), "video", 0).then( () => { settled = true; return undefined; @@ -840,9 +839,7 @@ test("a fetch started after the subscriber closes rejects without opening a stre const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); subscriber.close(); - const err = await subscriber - .fetchGroup(new BroadcastProducer().consume(), Path.from("room"), "video", 0) - .catch((err: unknown) => err); + const err = await subscriber.fetchGroup(Path.from("room"), "video", 0).catch((err: unknown) => err); expectCut(err, undefined); expect(streams.length).toBe(0); }); @@ -853,7 +850,7 @@ test("an already-aborted fetch rejects without opening a stream", async () => { const cause = new Error("gone"); const err = await subscriber - .fetchGroup(new BroadcastProducer().consume(), Path.from("room"), "video", 0, { + .fetchGroup(Path.from("room"), "video", 0, { signal: AbortSignal.abort(cause), }) .catch((err: unknown) => err); @@ -868,10 +865,10 @@ test("one of two fetch sharers aborting leaves the other's fetch", async () => { const subscriber = new Subscriber(quic, Version.DRAFT_05, HopSchema.parse(1n)); const controller = new AbortController(); - const a = subscriber.fetchGroup(new BroadcastProducer().consume(), Path.from("room"), "video", 0, { + const a = subscriber.fetchGroup(Path.from("room"), "video", 0, { signal: controller.signal, }); - const b = subscriber.fetchGroup(new BroadcastProducer().consume(), Path.from("room"), "video", 0); + const b = subscriber.fetchGroup(Path.from("room"), "video", 0); await drainUntil(() => streams.length === 1); await answerTrackInfo(streams[0]); @@ -904,10 +901,10 @@ test.each([ const first = new AbortController(); const second = new AbortController(); - const a = subscriber.fetchGroup(new BroadcastProducer().consume(), Path.from("room"), "video", 0, { + const a = subscriber.fetchGroup(Path.from("room"), "video", 0, { signal: first.signal, }); - const b = subscriber.fetchGroup(new BroadcastProducer().consume(), Path.from("room"), "video", 0, { + const b = subscriber.fetchGroup(Path.from("room"), "video", 0, { signal: second.signal, }); diff --git a/js/net/src/lite/subscriber.ts b/js/net/src/lite/subscriber.ts index ab7146fd3de..759c6284dff 100644 --- a/js/net/src/lite/subscriber.ts +++ b/js/net/src/lite/subscriber.ts @@ -90,9 +90,9 @@ interface SubscribeEntry { // (SUBSCRIBE_END), once it declares them. start?: number; end?: number; - // The broadcast the subscription belongs to, which records the origin SUBSCRIBE_START - // names so a session republishing it names the same one. - broadcast: broadcast.Consumer; + // The origin SUBSCRIBE_START named (draft-07). The subscription feeds one track copy, + // and a copy has one origin for its whole life, as Rust's track::Provenance. + origin?: Hop; // Whether SUBSCRIBE_START arrived. On draft-07, which names the serving origin there, // group streams wait for it: until then nobody knows whose content they carry. started: Signal; @@ -506,14 +506,14 @@ export class Subscriber { for (;;) { const request = await wireOf(consumer).requested(); if (!request) break; - void this.#runSubscribe(consumer, path, request); + void this.#runSubscribe(path, request); } })(); return consumer; } - async #runSubscribe(consumer: broadcast.Consumer, broadcast: Path.Valid, request: track.Request) { + async #runSubscribe(broadcast: Path.Valid, request: track.Request) { const id = this.#subscribeNext++; const subscription = request.subscription; const initialBounds = groupBounds(subscription.groups); @@ -542,7 +542,7 @@ export class Subscriber { // Open the stream under a timeout. The stream handle flows back via `state` // so the timeout path can abort it if it finishes opening after the deadline. const state: { stream?: Stream } = {}; - const setup = this.#openSubscribe(state, msg, request, id, timescale, consumer); + const setup = this.#openSubscribe(state, msg, request, id, timescale); let opened: { stream: Stream; entry: SubscribeEntry }; try { @@ -637,7 +637,6 @@ export class Subscriber { request: track.Request, id: bigint, timescale: Signal, - consumer: broadcast.Consumer, ): Promise<{ stream: Stream; entry: SubscribeEntry }> { let producer: track.Producer; let drainOk = false; @@ -668,7 +667,6 @@ export class Subscriber { }, }), requested: msg.startGroup, - broadcast: consumer, started: new Signal(!hasOrigin(this.version)), }; this.#subscribes.set(id, entry); @@ -744,7 +742,6 @@ export class Subscriber { // Open a FETCH stream for one group and stream its bare frames into a group, for the // ConsumeBroadcast backing track.Consumer.fetchGroup() (lite-05+). async fetchGroup( - front: broadcast.Consumer, broadcast: Path.Valid, track: string, sequence: number, @@ -769,7 +766,7 @@ export class Subscriber { consumer = group.mirror(); entry = { group, - accepted: this.#runFetch(front, broadcast, track, sequence, options.priority ?? 0, group), + accepted: this.#runFetch(broadcast, track, sequence, options.priority ?? 0, group), }; this.#fetches.set(key, entry); void group.closed.then(() => { @@ -790,7 +787,6 @@ export class Subscriber { // group, evict the entry, and reject every caller waiting for acceptance. A setup every caller // has abandoned is cancelled the same way. async #runFetch( - front: broadcast.Consumer, broadcast: Path.Valid, track: string, sequence: number, @@ -805,7 +801,7 @@ export class Subscriber { // A publisher that never answers would hold the setup forever. Subscriber.close() // closing the group releases every caller at any stage, and resets the streams the // setup opened. - const setup = this.#fetchSetup(front, broadcast, track, sequence, priority, group); + const setup = this.#fetchSetup(broadcast, track, sequence, priority, group); let accepted: { stream: Stream; info: TrackInfo }; try { accepted = await untilAbandoned(group, setup); @@ -828,7 +824,6 @@ export class Subscriber { // Resolve the track's timescale, then open the FETCH stream and wait for it to be accepted. // Closing the group during that wait resets the stream. async #fetchSetup( - front: broadcast.Consumer, broadcast: Path.Valid, track: string, sequence: number, @@ -840,10 +835,9 @@ export class Subscriber { await stream.writer.u53(StreamId.Fetch); await new FetchMessage({ broadcast, track, priority, group: sequence }).encode(stream.writer, this.version); if (hasOrigin(this.version)) { - // Draft-07 accepts with FETCH_OK naming the serving origin before any frame; - // record it so a session republishing the broadcast names the same one. - const ok = await untilClosed(group, FetchOk.decode(stream.reader, this.version)); - wireOf(front).name(ok.origin); + // Draft-07 accepts with FETCH_OK before any frame. It names the serving origin, + // which only a republisher would need, and JS does not republish. + await untilClosed(group, FetchOk.decode(stream.reader, this.version)); } else { // A byte or an empty-group FIN accepts the fetch; a reset rejects it. // done() buffers that byte so the response pump can decode it normally. @@ -914,7 +908,12 @@ export class Subscriber { if ("start" in resp) { entry.start = resp.start.group; if (hasOrigin(this.version)) { - wireOf(entry.broadcast).name(resp.start.origin); + // A START naming another origin means upstream is serving a different + // track: drop the copy rather than splice another origin's content into it. + if (entry.origin !== undefined && entry.origin !== resp.start.origin) { + throw new Error(`origin changed: ${entry.origin} to ${resp.start.origin}`); + } + entry.origin = resp.start.origin; entry.started.set(true); } // The groups the SUBSCRIBE asked for below it are unavailable, whatever the @@ -1307,7 +1306,7 @@ class ConsumeBroadcast extends broadcast.Consumer { super(state); overrideBroadcastWire(this, { resolveTrackInfo: (name) => subscriber.resolveTrackInfo(path, name), - fetchGroup: (name, sequence, options) => subscriber.fetchGroup(this, path, name, sequence, options), + fetchGroup: (name, sequence, options) => subscriber.fetchGroup(path, name, sequence, options), }); this.#subscriber = subscriber; this.#path = path; diff --git a/js/net/src/origin.ts b/js/net/src/origin.ts index c06c5970969..2c3702ce650 100644 --- a/js/net/src/origin.ts +++ b/js/net/src/origin.ts @@ -14,7 +14,7 @@ import { Derived, type Dispose, type GetPromise, type Getter, getter, Once, Sign import * as announce from "./announced.ts"; import * as broadcast from "./broadcast.ts"; import { StreamCode, StreamError } from "./error.ts"; -import { isAnonymous, Route, routesEqual } from "./hop.ts"; +import { type Hop, isAnonymous, Route, randomHop, routesEqual } from "./hop.ts"; import { hiddenBelow, hooks, scopeCaptures, scopeHead, scopeOverlaps, spreadHash } from "./internal.ts"; import * as Path from "./path.ts"; import { type Advertised, type Advertisements, registerWire, wireOf } from "./wire.ts"; @@ -383,6 +383,9 @@ class OriginState { // received entry back to a peer, which is what makes an origin shared by both // directions echo-free. created: Map | undefined = new Map(); + // This origin's identity, which its replies name as the origin of what it serves. Shared by + // every session serving it, so a peer can fail over between them (Rust's `origin.hop()`). + readonly hop: Hop = randomHop(); local = new VersionedSignal | undefined>(new Map()); advertisedLocal = new VersionedSignal | undefined>(new Map()); routes = new VersionedSignal | undefined>(new Map()); @@ -1147,6 +1150,7 @@ export class Consumer { total === 0 ? undefined : discovery === total, ); registerWire(this, { + hop: state.hop, routes: (path) => this.#routes(scope.path(path)), broadcasts: scope === Scope.all ? state.local : new Derived([state.local], (local) => scope.projectPaths(local)), diff --git a/js/net/src/wire.ts b/js/net/src/wire.ts index bb9af836281..501c4d3586e 100644 --- a/js/net/src/wire.ts +++ b/js/net/src/wire.ts @@ -21,13 +21,6 @@ export interface Broadcast { resolveTrackInfo(name: string): Promise; fetchGroup(name: string, sequence: number, options?: track.FetchGroupOptions): Promise; requested(): Promise; - /** - * The origin serving this broadcast, named in SUBSCRIBE_OK and FETCH_OK: the one an - * upstream reply named, or else a random one generated once for the broadcast. - */ - origin(): Hop; - /** Record the origin an upstream reply named for this broadcast. */ - name(origin: Hop): void; } /** The protocol-facing operations behind an origin producer. */ @@ -50,6 +43,8 @@ export interface OriginProducer { /** The protocol-facing operations behind an origin consumer. */ export interface OriginConsumer { + /** The origin's identity, named in SUBSCRIBE_START and FETCH_OK for everything it serves. */ + readonly hop: Hop; routes(path: Path.Valid): boolean; readonly broadcasts: Getter | undefined>; readonly advertised: Getter; diff --git a/quest/m0/wildcard/js-origin.md b/quest/m0/wildcard/js-origin.md deleted file mode 100644 index df54d0bf6a8..00000000000 --- a/quest/m0/wildcard/js-origin.md +++ /dev/null @@ -1,35 +0,0 @@ -# [S] JS origin granularity - -## Goal - -`@moq/net` tracks the origin an upstream reply names at the same granularity -as Rust, and handles a second, different origin the way Rust does, so a JS -node that republishes never labels one origin's content as another's. - -## Plan - -[#4279](https://github.com/moq-dev/moq/pull/4279) had JS record the origin -an upstream SUBSCRIBE_OK or FETCH_OK names on the consumed broadcast's shared -state (`js/net/src/broadcast.ts`), and the latest reply wins. Rust records it -per copy of a track (`track::Provenance`) and only admits a replacement -naming the same origin. Codex asked for a conflicting name to be refused -([r4112837960](https://github.com/moq-dev/moq/pull/4279#discussion_r4112837960)). -The agent declined, since a later request for the same broadcast can -legitimately land on a front serving another origin, and left the -granularity question to the maintainer -([r4113954489](https://github.com/moq-dev/moq/pull/4279#discussion_r4113954489)). -The maintainer decided in the 09-28 merged-PR audit that JS must match Rust. - -- Move the origin to the level Rust keeps it at, so two tracks of one - broadcast served by different origins stay distinct. -- A reply naming a different origin for content already labeled follows - Rust's rule rather than overwriting silently. -- A republished broadcast advertises, per track, the origin that actually - served it, or a random one when nothing upstream named one. - -Test the mid-life origin change JS previously absorbed, and pin that JS and -Rust agree on it in the interop suite if the scenario is reachable there. - -## Related - -- [Wildcard](/quest/m0/wildcard/README.md) - the line this blocks