@moq/net 0.2.3 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/announced.d.ts +75 -1
- package/announced.d.ts.map +1 -1
- package/announced.js +140 -1
- package/announced.js.map +1 -1
- package/announced.test.js +3 -3
- package/announced.test.js.map +1 -1
- package/broadcast.d.ts.map +1 -1
- package/broadcast.js +11 -8
- package/broadcast.js.map +1 -1
- package/broadcast.test.js +24 -0
- package/broadcast.test.js.map +1 -1
- package/connection/established.d.ts +14 -1
- package/connection/established.d.ts.map +1 -1
- package/connection/established.js.map +1 -1
- package/connection/reload.d.ts +26 -5
- package/connection/reload.d.ts.map +1 -1
- package/connection/reload.js +55 -26
- package/connection/reload.js.map +1 -1
- package/connection/reload.test.js +56 -0
- package/connection/reload.test.js.map +1 -1
- package/consume.d.ts +18 -0
- package/consume.d.ts.map +1 -1
- package/consume.js +20 -0
- package/consume.js.map +1 -1
- package/ietf/connection.d.ts +8 -1
- package/ietf/connection.d.ts.map +1 -1
- package/ietf/connection.js +11 -0
- package/ietf/connection.js.map +1 -1
- package/ietf/ietf.test.js +57 -0
- package/ietf/ietf.test.js.map +1 -1
- package/ietf/properties.d.ts +6 -2
- package/ietf/properties.d.ts.map +1 -1
- package/ietf/properties.js +43 -20
- package/ietf/properties.js.map +1 -1
- package/ietf/publish.d.ts.map +1 -1
- package/ietf/publish.js +13 -3
- package/ietf/publish.js.map +1 -1
- package/ietf/publisher.d.ts +14 -2
- package/ietf/publisher.d.ts.map +1 -1
- package/ietf/publisher.js +148 -104
- package/ietf/publisher.js.map +1 -1
- package/ietf/subscribe.d.ts.map +1 -1
- package/ietf/subscribe.js +9 -5
- package/ietf/subscribe.js.map +1 -1
- package/ietf/subscriber.d.ts.map +1 -1
- package/ietf/subscriber.js +9 -0
- package/ietf/subscriber.js.map +1 -1
- package/integration.test.js +294 -0
- package/integration.test.js.map +1 -1
- package/internal.d.ts +1 -1
- package/internal.d.ts.map +1 -1
- package/internal.js.map +1 -1
- package/lite/connection.d.ts +8 -1
- package/lite/connection.d.ts.map +1 -1
- package/lite/connection.js +10 -0
- package/lite/connection.js.map +1 -1
- package/lite/publisher.d.ts.map +1 -1
- package/lite/publisher.js +30 -5
- package/lite/publisher.js.map +1 -1
- package/lite/subscribe.test.js +43 -1
- package/lite/subscribe.test.js.map +1 -1
- package/lite/subscriber.d.ts.map +1 -1
- package/lite/subscriber.js +91 -25
- package/lite/subscriber.js.map +1 -1
- package/lite/subscriber.test.js +78 -0
- package/lite/subscriber.test.js.map +1 -1
- package/package.json +1 -1
- package/track.d.ts +26 -6
- package/track.d.ts.map +1 -1
- package/track.js +112 -27
- package/track.js.map +1 -1
- package/track.test.js +52 -5
- package/track.test.js.map +1 -1
package/broadcast.test.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"broadcast.test.js","sourceRoot":"","sources":["../src/broadcast.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AACvD,OAAO,EAAE,QAAQ,IAAI,iBAAiB,EAAE,QAAQ,IAAI,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAC9F,OAAO,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,OAAO,EAAE,QAAQ,IAAI,aAAa,EAAE,MAAM,YAAY,CAAC;AAEvD,2FAA2F;AAC3F,6EAA6E;AAC7E,MAAM,YAAa,SAAQ,iBAAiB;IAC3C,qGAAqG;IACrG;QACC,KAAK,EAAE,CAAC;IACT,CAAC;CACD;AAED,sFAAsF;AACtF,uFAAuF;AACvF,KAAK,UAAU,cAAc,CAAC,SAA+C;IAC5E,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IAC5B,MAAM,MAAM,GAAG,M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WAAW,CAAC,QAAQ,CAAC,CAAC;IAC3B,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,SAAS,EAAE,CAAC;IACjC,MAAM,CAAC,MAAM,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC;IAEnD,6EAA6E;IAC7E,MAAM,OAAO,GAAG,IAAI,iBAAiB,EAAE,CAAC;IACxC,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;IAC9B,OAAO,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;IAC9B,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,SAAS,EAAE,CAAC;IACpC,MAAM,CAAC,CAAC,MAAM,cAAc,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC9D,CAAC,CAAC,CAAC;AAEH,IAAI,CAAC,wEAAwE,EAAE,KAAK,IAAI,EAAE;IACzF,MAAM,SAAS,GAAG,IAAI,YAAY,EAAE,CAAC;IAErC,+EAA+E;IAC/E,mDAAmD;IACnD,MAAM,UAAU,GAAG,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC;IACxD,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,EAAE,CAAC;IAE/B,iFAAiF;IACjF,gFAAgF;IAChF,mBAAmB;IACnB,SAAS,CAAC,KAAK,EAAE,CAAC;IAElB,MAAM,MAAM,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;AACtC,CAAC,CAAC,CAAC","sourcesContent":["import { expect, setSystemTime, test } from \"bun:test\";\nimport { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from \"./broadcast.ts\";\nimport { Lagged, MAX_GROUP_FRAMES } from \"./group.ts\";\nimport { Timestamp } from \"./time.ts\";\nimport type { Request as TrackRequest } from \"./track.ts\";\nimport { Producer as TrackProducer } from \"./track.ts\";\n\n// The public API mints consumers internally (Producer.consume, the wire layers); tests act\n// as a wire layer by subclassing, the same way lite's ConsumeBroadcast does.\nclass TestConsumer extends BroadcastConsumer {\n\t// biome-ignore lint/complexity/noUselessConstructor: widens the protected base constructor to public\n\tconstructor() {\n\t\tsuper();\n\t}\n}\n\n// Observe whether an on-demand track request is pending without blocking: returns the\n// next request if one has already been emitted, or undefined if none is (yet) waiting.\nasync function pendingRequest(broadcast: Pick<BroadcastProducer, \"requested\">): Promise<TrackRequest | undefined> {\n\tconst none = Symbol(\"none\");\n\tconst result = await Promise.race([broadcast.requested(), Promise.resolve(none)]);\n\treturn result === none ? undefined : (result as TrackRequest | undefined);\n}\n\ntest(\"consumer dedupes repeat subscriptions onto one upstream request\", async () => {\n\tconst consumer = new TestConsumer();\n\n\t// Two subscriptions to the same track share one upstream subscription...\n\tconst a = consumer.track(\"video\").subscribe();\n\tconst b = consumer.subscribe(\"video\");\n\n\tconst request = await pendingRequest(consumer);\n\texpect(request?.name).toBe(\"video\");\n\t// ...so only one on-demand request is emitted for it.\n\texpect(await pendingRequest(consumer)).toBeUndefined();\n\n\t// Serving that single request fans out to both subscribers.\n\tif (!request) throw new Error(\"expected request\");\n\tconst producer = request.accept();\n\tproducer.writeString(\"hello\");\n\texpect(await a.readString()).toBe(\"hello\");\n\texpect(await b.readString()).toBe(\"hello\");\n\n\t// A different track still opens its own request.\n\tconsumer.subscribe(\"audio\");\n\texpect((await pendingRequest(consumer))?.name).toBe(\"audio\");\n\n\t// Once the shared track closes, a later subscribe re-opens it.\n\tproducer.close();\n\tconsumer.subscribe(\"video\");\n\texpect((await pendingRequest(consumer))?.name).toBe(\"video\");\n});\n\ntest(\"a consumer clone shares the broadcast until every handle closes\", () => {\n\tconst consumer = new TestConsumer();\n\tconst clone = consumer.clone();\n\n\t// Closing one handle leaves the shared broadcast live for the other...\n\tconsumer.close();\n\texpect(consumer.closed.peek()).toBeUndefined();\n\texpect(clone.closed.peek()).toBeUndefined();\n\n\t// ...and closing the last handle closes it for both.\n\tclone.close();\n\texpect(consumer.closed.peek()).toBeDefined();\n\texpect(clone.closed.peek()).toBeDefined();\n});\n\ntest(\"double-closing a consumer handle does not prematurely close the broadcast\", () => {\n\tconst consumer = new TestConsumer();\n\tconst clone = consumer.clone();\n\n\t// The double close must decrement the shared count only once...\n\tclone.close();\n\tclone.close();\n\texpect(consumer.closed.peek()).toBeUndefined();\n\n\t// ...so the broadcast still stays live until the other handle closes.\n\tconsumer.close();\n\texpect(consumer.closed.peek()).toBeDefined();\n});\n\ntest(\"consumer track subscriptions fan out and close independently\", async () => {\n\tconst consumer = new TestConsumer();\n\n\t// Two subscriptions to one track dedupe onto a single upstream request...\n\tconst a = consumer.subscribe(\"video\");\n\tconst b = consumer.subscribe(\"video\");\n\n\tconst request = await pendingRequest(consumer);\n\tif (!request) throw new Error(\"expected request\");\n\texpect(await pendingRequest(consumer)).toBeUndefined();\n\n\tconst producer = request.accept();\n\tproducer.writeString(\"one\");\n\texpect(await a.readString()).toBe(\"one\");\n\texpect(await b.readString()).toBe(\"one\");\n\n\t// ...and closing one subscriber leaves the other (and the shared upstream) delivering.\n\ta.close();\n\tproducer.writeString(\"two\");\n\texpect(await b.readString()).toBe(\"two\");\n});\n\ntest(\"subscribe serves a statically inserted track without a request\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\n\tconst track1 = new TrackProducer(\"track1\").accept();\n\tbroadcast.insertTrack(track1);\n\ttrack1.appendGroup().close();\n\n\t// The track already exists, so subscribe resolves immediately (no requested()).\n\tconst sub1 = broadcast.track(\"track1\").subscribe();\n\texpect((await sub1.nextGroup())?.sequence).toBe(0);\n\n\t// No on-demand request was emitted for it.\n\texpect(await pendingRequest(broadcast)).toBeUndefined();\n\n\t// A second static track behaves the same.\n\tconst track2 = new TrackProducer(\"track2\").accept();\n\tbroadcast.insertTrack(track2);\n\n\tconst sub2 = broadcast.track(\"track2\").subscribe();\n\ttrack2.appendGroup().close();\n\texpect((await sub2.nextGroup())?.sequence).toBe(0);\n});\n\ntest(\"two subscribers to one inserted track each get a full copy\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\tconst producer = broadcast.createTrack(\"video\");\n\n\tconst a = broadcast.track(\"video\").subscribe();\n\tconst b = broadcast.track(\"video\").subscribe();\n\n\tproducer.writeString(\"hello\");\n\tproducer.writeString(\"world\");\n\n\t// Neither subscriber steals from the other: both see every frame in order.\n\texpect(await a.readString()).toBe(\"hello\");\n\texpect(await b.readString()).toBe(\"hello\");\n\texpect(await a.readString()).toBe(\"world\");\n\texpect(await b.readString()).toBe(\"world\");\n});\n\ntest(\"a late subscriber replays the cached window\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\tconst producer = broadcast.createTrack(\"video\");\n\n\t// Written before anyone subscribes; retained in the cache for replay.\n\tproducer.writeString(\"early\");\n\n\tconst late = broadcast.track(\"video\").subscribe();\n\texpect(await late.readString()).toBe(\"early\");\n\n\tproducer.writeString(\"later\");\n\texpect(await late.readString()).toBe(\"later\");\n});\n\ntest(\"a read throws Lagged on a gap, then resyncs to the next group\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\tconst producer = broadcast.createTrack(\"video\");\n\tconst sub = broadcast.track(\"video\").subscribe();\n\n\t// Group 0 overflows its frame cap without being read, evicting the front: a gap.\n\tconst g0 = producer.appendGroup();\n\tfor (let i = 0; i < MAX_GROUP_FRAMES + 10; i++)\n\t\tg0.writeFrame({ payload: new Uint8Array([i & 0xff]), timestamp: Timestamp.now() });\n\tg0.close();\n\n\t// Group 1 is clean.\n\tconst g1 = producer.appendGroup();\n\tg1.writeFrame({ payload: new TextEncoder().encode(\"ok\"), timestamp: Timestamp.now() });\n\tg1.close();\n\n\t// The reader hits the gap in group 0 (error, not a silent skip), then the next\n\t// read resyncs from group 1.\n\texpect(sub.readFrame()).rejects.toBeInstanceOf(Lagged);\n\texpect(await sub.readString()).toBe(\"ok\");\n});\n\ntest(\"a stalled consumer does not pin evicted groups\", async () => {\n\ttry {\n\t\tsetSystemTime(new Date(10_000));\n\n\t\tconst broadcast = new BroadcastProducer();\n\t\tconst producer = broadcast.createTrack(\"video\", { latencyMax: 1000 });\n\n\t\t// A subscriber that never reads. Its sink must not grow without bound.\n\t\tconst stalled = broadcast.track(\"video\").subscribe();\n\n\t\tproducer.writeString(\"old\");\n\n\t\t// Advance past the cache window and write again to trigger a prune. The old\n\t\t// (closed, aged-out) group is dropped from the stalled sink, not retained.\n\t\tsetSystemTime(new Date(12_000));\n\t\tproducer.writeString(\"fresh\");\n\n\t\t// The next group in arrival order is the fresh one (seq 1): the old (seq 0) group\n\t\t// was evicted, not still buffered ahead of it.\n\t\texpect((await stalled.recvGroup())?.sequence).toBe(1);\n\n\t\t// Nothing else is buffered: a second recvGroup stays pending (the track is open),\n\t\t// proving exactly one group remained in the sink rather than two.\n\t\tconst pending = Symbol(\"pending\");\n\t\tconst next = await Promise.race([stalled.recvGroup(), Promise.resolve(pending)]);\n\t\texpect(next).toBe(pending);\n\t} finally {\n\t\tsetSystemTime();\n\t}\n});\n\ntest(\"createTrack commits info up front\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\n\tconst producer = broadcast.createTrack(\"video\", { latencyMax: 2000, priority: 3 });\n\texpect(producer.name).toBe(\"video\");\n\n\tconst info = await broadcast.track(\"video\").info();\n\texpect(info.latencyMax).toBe(2000);\n\texpect(info.priority).toBe(3);\n});\n\ntest(\"insertTrack rejects a duplicate live name\", () => {\n\tconst broadcast = new BroadcastProducer();\n\tbroadcast.createTrack(\"dup\");\n\texpect(() => broadcast.insertTrack(new TrackProducer(\"dup\").accept())).toThrow();\n});\n\ntest(\"a closed track is evicted and re-subscribing falls through to a request\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\n\tconst track1 = broadcast.createTrack(\"track1\");\n\ttrack1.close();\n\n\t// The stale entry is gone, so subscribe creates an on-demand request instead.\n\tconst pending = broadcast.track(\"track1\").subscribe();\n\texpect(pending).toBeDefined();\n\n\t// That on-demand request is now waiting to be answered.\n\tconst request = await broadcast.requested();\n\texpect(request?.name).toBe(\"track1\");\n});\n\ntest(\"removeTrack drops the static entry\", async () => {\n\t// While the static entry exists, subscribing takes the fast path: no on-demand request.\n\tconst kept = new BroadcastProducer();\n\tkept.createTrack(\"track1\");\n\tkept.track(\"track1\").subscribe();\n\texpect(await pendingRequest(kept)).toBeUndefined();\n\n\t// With the entry removed, subscribing falls through to an on-demand request.\n\tconst removed = new BroadcastProducer();\n\tremoved.createTrack(\"track1\");\n\tremoved.removeTrack(\"track1\");\n\tremoved.track(\"track1\").subscribe();\n\texpect((await pendingRequest(removed))?.name).toBe(\"track1\");\n});\n\ntest(\"close rejects a still-pending track request so its subscriber unblocks\", async () => {\n\tconst broadcast = new TestConsumer();\n\n\t// Subscribing with no static entry queues an on-demand request; the subscriber\n\t// blocks on info() until that request is answered.\n\tconst subscriber = broadcast.track(\"video\").subscribe();\n\tconst info = subscriber.info();\n\n\t// Closing must reject the still-queued request rather than silently dropping it,\n\t// so the awaiting subscriber rejects instead of hanging on a producer that will\n\t// never be served.\n\tbroadcast.close();\n\n\tawait expect(info).rejects.toThrow();\n});\n"]}
|
|
1
|
+
{"version":3,"file":"broadcast.test.js","sourceRoot":"","sources":["../src/broadcast.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AACvD,OAAO,EAAE,QAAQ,IAAI,iBAAiB,EAAE,QAAQ,IAAI,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAC9F,OAAO,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,OAAO,EAAE,QAAQ,IAAI,aAAa,EAAE,MAAM,YAAY,CAAC;AAEvD,2FAA2F;AAC3F,6EAA6E;AAC7E,MAAM,YAAa,SAAQ,iBAAiB;IAC3C,qGAAqG;IACrG;QACC,KAAK,EAAE,CAAC;IACT,CAAC;CACD;AAED,sF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,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,EAAE,CAAC;IAE/B,iFAAiF;IACjF,gFAAgF;IAChF,mBAAmB;IACnB,SAAS,CAAC,KAAK,EAAE,CAAC;IAElB,MAAM,MAAM,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;AACtC,CAAC,CAAC,CAAC","sourcesContent":["import { expect, setSystemTime, test } from \"bun:test\";\nimport { Consumer as BroadcastConsumer, Producer as BroadcastProducer } from \"./broadcast.ts\";\nimport { Lagged, MAX_GROUP_FRAMES } from \"./group.ts\";\nimport { Timestamp } from \"./time.ts\";\nimport type { Request as TrackRequest } from \"./track.ts\";\nimport { Producer as TrackProducer } from \"./track.ts\";\n\n// The public API mints consumers internally (Producer.consume, the wire layers); tests act\n// as a wire layer by subclassing, the same way lite's ConsumeBroadcast does.\nclass TestConsumer extends BroadcastConsumer {\n\t// biome-ignore lint/complexity/noUselessConstructor: widens the protected base constructor to public\n\tconstructor() {\n\t\tsuper();\n\t}\n}\n\n// Observe whether an on-demand track request is pending without blocking: returns the\n// next request if one has already been emitted, or undefined if none is (yet) waiting.\nasync function pendingRequest(broadcast: Pick<BroadcastProducer, \"requested\">): Promise<TrackRequest | undefined> {\n\tconst none = Symbol(\"none\");\n\tconst result = await Promise.race([broadcast.requested(), Promise.resolve(none)]);\n\treturn result === none ? undefined : (result as TrackRequest | undefined);\n}\n\ntest(\"consumer dedupes repeat subscriptions onto one upstream request\", async () => {\n\tconst consumer = new TestConsumer();\n\n\t// Two subscriptions to the same track share one upstream subscription...\n\tconst a = consumer.track(\"video\").subscribe();\n\tconst b = consumer.subscribe(\"video\");\n\n\tconst request = await pendingRequest(consumer);\n\texpect(request?.name).toBe(\"video\");\n\t// ...so only one on-demand request is emitted for it.\n\texpect(await pendingRequest(consumer)).toBeUndefined();\n\n\t// Serving that single request fans out to both subscribers.\n\tif (!request) throw new Error(\"expected request\");\n\tconst producer = request.accept();\n\tproducer.writeString(\"hello\");\n\texpect(await a.readString()).toBe(\"hello\");\n\texpect(await b.readString()).toBe(\"hello\");\n\n\t// A different track still opens its own request.\n\tconsumer.subscribe(\"audio\");\n\texpect((await pendingRequest(consumer))?.name).toBe(\"audio\");\n\n\t// Once the shared track closes, a later subscribe re-opens it.\n\tproducer.close();\n\tconsumer.subscribe(\"video\");\n\texpect((await pendingRequest(consumer))?.name).toBe(\"video\");\n});\n\ntest(\"a request exposes the aggregate subscription options\", async () => {\n\tconst consumer = new TestConsumer();\n\n\tconsumer.subscribe(\"video\", { priority: 3, ordered: true, latencyMax: 100, startGroup: 10, endGroup: 20 });\n\tconsumer.subscribe(\"video\", { priority: 7, ordered: true, latencyMax: 250, startGroup: 0, endGroup: 30 });\n\n\tconst request = await pendingRequest(consumer);\n\texpect(request?.subscription).toEqual({\n\t\tpriority: 7,\n\t\tordered: true,\n\t\tlatencyMax: 250,\n\t\tstartGroup: 0,\n\t\tendGroup: 30,\n\t});\n\texpect(request?.priority).toBe(7);\n});\n\ntest(\"requested selects the highest current priority\", async () => {\n\tconst consumer = new TestConsumer();\n\n\tconst first = consumer.subscribe(\"first\", { priority: 1 });\n\tconsumer.subscribe(\"second\", { priority: 5 });\n\tconst updated = first.subscription.changed();\n\tfirst.update({ priority: 9 });\n\tawait updated;\n\n\texpect((await consumer.requested())?.name).toBe(\"first\");\n\texpect((await consumer.requested())?.name).toBe(\"second\");\n});\n\ntest(\"a consumer clone shares the broadcast until every handle closes\", () => {\n\tconst consumer = new TestConsumer();\n\tconst clone = consumer.clone();\n\n\t// Closing one handle leaves the shared broadcast live for the other...\n\tconsumer.close();\n\texpect(consumer.closed.peek()).toBeUndefined();\n\texpect(clone.closed.peek()).toBeUndefined();\n\n\t// ...and closing the last handle closes it for both.\n\tclone.close();\n\texpect(consumer.closed.peek()).toBeDefined();\n\texpect(clone.closed.peek()).toBeDefined();\n});\n\ntest(\"double-closing a consumer handle does not prematurely close the broadcast\", () => {\n\tconst consumer = new TestConsumer();\n\tconst clone = consumer.clone();\n\n\t// The double close must decrement the shared count only once...\n\tclone.close();\n\tclone.close();\n\texpect(consumer.closed.peek()).toBeUndefined();\n\n\t// ...so the broadcast still stays live until the other handle closes.\n\tconsumer.close();\n\texpect(consumer.closed.peek()).toBeDefined();\n});\n\ntest(\"consumer track subscriptions fan out and close independently\", async () => {\n\tconst consumer = new TestConsumer();\n\n\t// Two subscriptions to one track dedupe onto a single upstream request...\n\tconst a = consumer.subscribe(\"video\");\n\tconst b = consumer.subscribe(\"video\");\n\n\tconst request = await pendingRequest(consumer);\n\tif (!request) throw new Error(\"expected request\");\n\texpect(await pendingRequest(consumer)).toBeUndefined();\n\n\tconst producer = request.accept();\n\tproducer.writeString(\"one\");\n\texpect(await a.readString()).toBe(\"one\");\n\texpect(await b.readString()).toBe(\"one\");\n\n\t// ...and closing one subscriber leaves the other (and the shared upstream) delivering.\n\ta.close();\n\tproducer.writeString(\"two\");\n\texpect(await b.readString()).toBe(\"two\");\n});\n\ntest(\"subscribe serves a statically inserted track without a request\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\n\tconst track1 = new TrackProducer(\"track1\").accept();\n\tbroadcast.insertTrack(track1);\n\ttrack1.appendGroup().close();\n\n\t// The track already exists, so subscribe resolves immediately (no requested()).\n\tconst sub1 = broadcast.track(\"track1\").subscribe();\n\texpect((await sub1.nextGroup())?.sequence).toBe(0);\n\n\t// No on-demand request was emitted for it.\n\texpect(await pendingRequest(broadcast)).toBeUndefined();\n\n\t// A second static track behaves the same.\n\tconst track2 = new TrackProducer(\"track2\").accept();\n\tbroadcast.insertTrack(track2);\n\n\tconst sub2 = broadcast.track(\"track2\").subscribe();\n\ttrack2.appendGroup().close();\n\texpect((await sub2.nextGroup())?.sequence).toBe(0);\n});\n\ntest(\"two subscribers to one inserted track each get a full copy\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\tconst producer = broadcast.createTrack(\"video\");\n\n\tconst a = broadcast.track(\"video\").subscribe();\n\tconst b = broadcast.track(\"video\").subscribe();\n\n\tproducer.writeString(\"hello\");\n\tproducer.writeString(\"world\");\n\n\t// Neither subscriber steals from the other: both see every frame in order.\n\texpect(await a.readString()).toBe(\"hello\");\n\texpect(await b.readString()).toBe(\"hello\");\n\texpect(await a.readString()).toBe(\"world\");\n\texpect(await b.readString()).toBe(\"world\");\n});\n\ntest(\"a late subscriber replays the cached window\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\tconst producer = broadcast.createTrack(\"video\");\n\n\t// Written before anyone subscribes; retained in the cache for replay.\n\tproducer.writeString(\"early\");\n\n\tconst late = broadcast.track(\"video\").subscribe();\n\texpect(await late.readString()).toBe(\"early\");\n\n\tproducer.writeString(\"later\");\n\texpect(await late.readString()).toBe(\"later\");\n});\n\ntest(\"a read throws Lagged on a gap, then resyncs to the next group\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\tconst producer = broadcast.createTrack(\"video\");\n\tconst sub = broadcast.track(\"video\").subscribe();\n\n\t// Group 0 overflows its frame cap without being read, evicting the front: a gap.\n\tconst g0 = producer.appendGroup();\n\tfor (let i = 0; i < MAX_GROUP_FRAMES + 10; i++)\n\t\tg0.writeFrame({ payload: new Uint8Array([i & 0xff]), timestamp: Timestamp.now() });\n\tg0.close();\n\n\t// Group 1 is clean.\n\tconst g1 = producer.appendGroup();\n\tg1.writeFrame({ payload: new TextEncoder().encode(\"ok\"), timestamp: Timestamp.now() });\n\tg1.close();\n\n\t// The reader hits the gap in group 0 (error, not a silent skip), then the next\n\t// read resyncs from group 1.\n\texpect(sub.readFrame()).rejects.toBeInstanceOf(Lagged);\n\texpect(await sub.readString()).toBe(\"ok\");\n});\n\ntest(\"a stalled consumer does not pin evicted groups\", async () => {\n\ttry {\n\t\tsetSystemTime(new Date(10_000));\n\n\t\tconst broadcast = new BroadcastProducer();\n\t\tconst producer = broadcast.createTrack(\"video\", { latencyMax: 1000 });\n\n\t\t// A subscriber that never reads. Its sink must not grow without bound.\n\t\tconst stalled = broadcast.track(\"video\").subscribe();\n\n\t\tproducer.writeString(\"old\");\n\n\t\t// Advance past the cache window and write again to trigger a prune. The old\n\t\t// (closed, aged-out) group is dropped from the stalled sink, not retained.\n\t\tsetSystemTime(new Date(12_000));\n\t\tproducer.writeString(\"fresh\");\n\n\t\t// The next group in arrival order is the fresh one (seq 1): the old (seq 0) group\n\t\t// was evicted, not still buffered ahead of it.\n\t\texpect((await stalled.recvGroup())?.sequence).toBe(1);\n\n\t\t// Nothing else is buffered: a second recvGroup stays pending (the track is open),\n\t\t// proving exactly one group remained in the sink rather than two.\n\t\tconst pending = Symbol(\"pending\");\n\t\tconst next = await Promise.race([stalled.recvGroup(), Promise.resolve(pending)]);\n\t\texpect(next).toBe(pending);\n\t} finally {\n\t\tsetSystemTime();\n\t}\n});\n\ntest(\"createTrack commits info up front\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\n\tconst producer = broadcast.createTrack(\"video\", { latencyMax: 2000, priority: 3 });\n\texpect(producer.name).toBe(\"video\");\n\n\tconst info = await broadcast.track(\"video\").info();\n\texpect(info.latencyMax).toBe(2000);\n\texpect(info.priority).toBe(3);\n});\n\ntest(\"insertTrack rejects a duplicate live name\", () => {\n\tconst broadcast = new BroadcastProducer();\n\tbroadcast.createTrack(\"dup\");\n\texpect(() => broadcast.insertTrack(new TrackProducer(\"dup\").accept())).toThrow();\n});\n\ntest(\"a closed track is evicted and re-subscribing falls through to a request\", async () => {\n\tconst broadcast = new BroadcastProducer();\n\n\tconst track1 = broadcast.createTrack(\"track1\");\n\ttrack1.close();\n\n\t// The stale entry is gone, so subscribe creates an on-demand request instead.\n\tconst pending = broadcast.track(\"track1\").subscribe();\n\texpect(pending).toBeDefined();\n\n\t// That on-demand request is now waiting to be answered.\n\tconst request = await broadcast.requested();\n\texpect(request?.name).toBe(\"track1\");\n});\n\ntest(\"removeTrack drops the static entry\", async () => {\n\t// While the static entry exists, subscribing takes the fast path: no on-demand request.\n\tconst kept = new BroadcastProducer();\n\tkept.createTrack(\"track1\");\n\tkept.track(\"track1\").subscribe();\n\texpect(await pendingRequest(kept)).toBeUndefined();\n\n\t// With the entry removed, subscribing falls through to an on-demand request.\n\tconst removed = new BroadcastProducer();\n\tremoved.createTrack(\"track1\");\n\tremoved.removeTrack(\"track1\");\n\tremoved.track(\"track1\").subscribe();\n\texpect((await pendingRequest(removed))?.name).toBe(\"track1\");\n});\n\ntest(\"close rejects a still-pending track request so its subscriber unblocks\", async () => {\n\tconst broadcast = new TestConsumer();\n\n\t// Subscribing with no static entry queues an on-demand request; the subscriber\n\t// blocks on info() until that request is answered.\n\tconst subscriber = broadcast.track(\"video\").subscribe();\n\tconst info = subscriber.info();\n\n\t// Closing must reject the still-queued request rather than silently dropping it,\n\t// so the awaiting subscriber rejects instead of hanging on a producer that will\n\t// never be served.\n\tbroadcast.close();\n\n\tawait expect(info).rejects.toThrow();\n});\n"]}
|
|
@@ -27,8 +27,21 @@ export interface Established {
|
|
|
27
27
|
announced(prefix?: Path.Valid): announce.Consumer;
|
|
28
28
|
/** Publish a broadcast at the given path. */
|
|
29
29
|
publish(path: Path.Valid, broadcast: broadcast.Producer): void;
|
|
30
|
-
/**
|
|
30
|
+
/**
|
|
31
|
+
* Consume the broadcast at the given path, immediately.
|
|
32
|
+
*
|
|
33
|
+
* The subscription is reset if nobody publishes the path, so use
|
|
34
|
+
* {@link announcedBroadcast} instead when the broadcast may not be online yet.
|
|
35
|
+
*/
|
|
31
36
|
consume(path: Path.Valid): broadcast.Consumer;
|
|
37
|
+
/**
|
|
38
|
+
* A reactive handle to the broadcast at the given path, live only while it is announced.
|
|
39
|
+
*
|
|
40
|
+
* The announcement-gated counterpart to {@link consume}: it waits for the broadcast to come
|
|
41
|
+
* online instead of resetting, and drops back to `undefined` when it goes away. See
|
|
42
|
+
* {@link announce.Broadcast}. Close the handle when done.
|
|
43
|
+
*/
|
|
44
|
+
announcedBroadcast(path: Path.Valid): announce.Broadcast;
|
|
32
45
|
/**
|
|
33
46
|
* Snapshot the transport's counters, querying it fresh on each call.
|
|
34
47
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"established.d.ts","sourceRoot":"","sources":["../../src/connection/established.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,KAAK,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AACjD,OAAO,KAAK,KAAK,SAAS,MAAM,iBAAiB,CAAC;AAClD,OAAO,KAAK,KAAK,IAAI,MAAM,YAAY,CAAC;AACxC,OAAO,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEhD,2FAA2F;AAC3F,MAAM,WAAW,WAAW;IAC3B,mCAAmC;IACnC,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC;IAElB,wCAAwC;IACxC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAEzB,iDAAiD;IACjD,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAE9B;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;IAE9B;;;;OAIG;IACH,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAE5B,mHAAmH;IACnH,SAAS,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC,QAAQ,CAAC;IAElD,6CAA6C;IAC7C,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,CAAC,QAAQ,GAAG,IAAI,CAAC;IAE/D
|
|
1
|
+
{"version":3,"file":"established.d.ts","sourceRoot":"","sources":["../../src/connection/established.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,KAAK,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AACjD,OAAO,KAAK,KAAK,SAAS,MAAM,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sourcesContent":["import type { Getter } from \"@moq/signals\";\nimport type * as announce from \"../announced.ts\";\nimport type * as broadcast from \"../broadcast.ts\";\nimport type * as Path from \"../path.ts\";\nimport type { Probe, Stats } from \"./stats.ts\";\nimport type { Transport } from \"./transport.ts\";\n\n/** An established MoQ session, implemented by both the moq-lite and moq-ietf protocols. */\nexport interface Established {\n\t/** URL of the connected server. */\n\treadonly url: URL;\n\n\t/** Negotiated wire protocol version. */\n\treadonly version: string;\n\n\t/** The wire transport this session runs over. */\n\treadonly transport: Transport;\n\n\t/**\n\t * Estimates measured by the peer, updated as PROBE messages arrive. Stays empty on\n\t * versions without PROBE. See {@link Stats} for what the local transport counts.\n\t */\n\treadonly probe: Getter<Probe>;\n\n\t/**\n\t * Whether the relay supports broadcast discovery: announcing which broadcasts exist under a\n\t * prefix. When false, {@link announced} never yields, so a consumer must subscribe blind\n\t * rather than wait for an announcement. Set via `discovery` on the connect options.\n\t */\n\treadonly discovery: boolean;\n\n\t/** Subscribe to broadcast announcements under an optional path prefix, returning paths relative to that prefix. */\n\tannounced(prefix?: Path.Valid): announce.Consumer;\n\n\t/** Publish a broadcast at the given path. */\n\tpublish(path: Path.Valid, broadcast: broadcast.Producer): void;\n\n\t
|
|
1
|
+
{"version":3,"file":"established.js","sourceRoot":"","sources":["../../src/connection/established.ts"],"names":[],"mappings":"","sourcesContent":["import type { Getter } from \"@moq/signals\";\nimport type * as announce from \"../announced.ts\";\nimport type * as broadcast from \"../broadcast.ts\";\nimport type * as Path from \"../path.ts\";\nimport type { Probe, Stats } from \"./stats.ts\";\nimport type { Transport } from \"./transport.ts\";\n\n/** An established MoQ session, implemented by both the moq-lite and moq-ietf protocols. */\nexport interface Established {\n\t/** URL of the connected server. */\n\treadonly url: URL;\n\n\t/** Negotiated wire protocol version. */\n\treadonly version: string;\n\n\t/** The wire transport this session runs over. */\n\treadonly transport: Transport;\n\n\t/**\n\t * Estimates measured by the peer, updated as PROBE messages arrive. Stays empty on\n\t * versions without PROBE. See {@link Stats} for what the local transport counts.\n\t */\n\treadonly probe: Getter<Probe>;\n\n\t/**\n\t * Whether the relay supports broadcast discovery: announcing which broadcasts exist under a\n\t * prefix. When false, {@link announced} never yields, so a consumer must subscribe blind\n\t * rather than wait for an announcement. Set via `discovery` on the connect options.\n\t */\n\treadonly discovery: boolean;\n\n\t/** Subscribe to broadcast announcements under an optional path prefix, returning paths relative to that prefix. */\n\tannounced(prefix?: Path.Valid): announce.Consumer;\n\n\t/** Publish a broadcast at the given path. */\n\tpublish(path: Path.Valid, broadcast: broadcast.Producer): void;\n\n\t/**\n\t * Consume the broadcast at the given path, immediately.\n\t *\n\t * The subscription is reset if nobody publishes the path, so use\n\t * {@link announcedBroadcast} instead when the broadcast may not be online yet.\n\t */\n\tconsume(path: Path.Valid): broadcast.Consumer;\n\n\t/**\n\t * A reactive handle to the broadcast at the given path, live only while it is announced.\n\t *\n\t * The announcement-gated counterpart to {@link consume}: it waits for the broadcast to come\n\t * online instead of resetting, and drops back to `undefined` when it goes away. See\n\t * {@link announce.Broadcast}. Close the handle when done.\n\t */\n\tannouncedBroadcast(path: Path.Valid): announce.Broadcast;\n\n\t/**\n\t * Snapshot the transport's counters, querying it fresh on each call.\n\t *\n\t * Resolves to an empty snapshot on a transport without `getStats()`. Sample it on\n\t * whatever schedule you need rather than expecting the library to poll for you.\n\t */\n\tstats(): Promise<Stats>;\n\n\t/** Close the session. */\n\tclose(): void;\n\n\t/** Resolves when the session closes. */\n\tclosed: Promise<void>;\n}\n"]}
|
package/connection/reload.d.ts
CHANGED
|
@@ -4,18 +4,22 @@ import type * as Path from "../path";
|
|
|
4
4
|
import { type ConnectProps, type WebSocketOptions, type WebTransportProps } from "./connect";
|
|
5
5
|
import type { Established } from "./established";
|
|
6
6
|
import type { Probe, Stats } from "./stats";
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* Exponential backoff settings for {@link Reload}'s reconnect loop.
|
|
9
|
+
*
|
|
10
|
+
* The delays carry jitter, so a fleet of tabs knocked offline together doesn't reconnect in
|
|
11
|
+
* lockstep. Every failure is retried; {@link ReloadDelay.timeout} is what stops the loop.
|
|
12
|
+
*/
|
|
8
13
|
export type ReloadDelay = {
|
|
9
14
|
/** The delay in milliseconds before reconnecting (default: 1000). */
|
|
10
15
|
initial: DOMHighResTimeStamp;
|
|
11
16
|
/** The multiplier for the delay (default: 2). */
|
|
12
17
|
multiplier: number;
|
|
13
|
-
/** The maximum delay in milliseconds (default:
|
|
18
|
+
/** The maximum delay in milliseconds (default: 5000). */
|
|
14
19
|
max: DOMHighResTimeStamp;
|
|
15
20
|
/**
|
|
16
21
|
* Maximum total time in milliseconds to spend retrying before giving up (default:
|
|
17
|
-
*
|
|
18
|
-
* unlimited retries.
|
|
22
|
+
* 10000). Resets after each successful connection. Set to 0 for unlimited retries.
|
|
19
23
|
*/
|
|
20
24
|
timeout?: DOMHighResTimeStamp;
|
|
21
25
|
};
|
|
@@ -59,7 +63,12 @@ export declare class Reload {
|
|
|
59
63
|
discovery?: boolean;
|
|
60
64
|
/** Backoff settings for the reconnect loop. */
|
|
61
65
|
delay: ReloadDelay;
|
|
62
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
* Resolves when the reconnect loop stops via {@link Reload.close}.
|
|
68
|
+
*
|
|
69
|
+
* Rejects when the loop gives up instead, carrying the failure that was in flight when the
|
|
70
|
+
* retry window expired.
|
|
71
|
+
*/
|
|
63
72
|
closed: Promise<void>;
|
|
64
73
|
constructor(props?: ReloadProps);
|
|
65
74
|
/**
|
|
@@ -72,6 +81,18 @@ export declare class Reload {
|
|
|
72
81
|
* Stays empty while the relay lacks {@link Established.discovery}.
|
|
73
82
|
*/
|
|
74
83
|
announced(prefix?: Path.Valid): Announce.Consumer;
|
|
84
|
+
/**
|
|
85
|
+
* A reactive handle to one broadcast, spanning reconnects.
|
|
86
|
+
*
|
|
87
|
+
* The same {@link Announce.Broadcast} as {@link Established.announcedBroadcast}, but it
|
|
88
|
+
* follows the reconnect loop: the broadcast drops to `undefined` when the connection dies
|
|
89
|
+
* and resolves again once the new connection announces the path. Use it instead of
|
|
90
|
+
* consuming off {@link Reload.established} whenever the broadcast may come online after you
|
|
91
|
+
* do, which is exactly the case a blind `consume` loses.
|
|
92
|
+
*
|
|
93
|
+
* Close the handle when done; {@link Reload.close} only drops it to `undefined`.
|
|
94
|
+
*/
|
|
95
|
+
announcedBroadcast(path: Path.Valid): Announce.Broadcast;
|
|
75
96
|
/**
|
|
76
97
|
* Snapshot the live connection's transport counters, or undefined while disconnected.
|
|
77
98
|
* See {@link Established.stats}.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reload.d.ts","sourceRoot":"","sources":["../../src/connection/reload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"reload.d.ts","sourceRoot":"","sources":["../../src/connection/reload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAE5C,OAAO,KAAK,KAAK,IAAI,MAAM,YAAY,CAAC;AAExC,OAAO,EAAE,KAAK,YAAY,EAAW,KAAK,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACzG,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAE/C;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GAAG;IACzB,qEAAqE;IACrE,OAAO,EAAE,mBAAmB,CAAC;IAE7B,iDAAiD;IACjD,UAAU,EAAE,MAAM,CAAC;IAEnB,yDAAyD;IACzD,GAAG,EAAE,mBAAmB,CAAC;IAEzB;;;OAG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;;;;;;;;;OAUG;IACH,kBAAkB,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC,SAAS,CAEvD;IAED;;;OAGG;IACG,KAAK,IAAI,OAAO,CAAC,KAAK,GAAG,SAAS,CAAC,CAExC;IAED,0FAA0F;IAC1F,KAAK,SAGJ;CACD"}
|
package/connection/reload.js
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
/* @ts-self-types="./reload.d.ts" */
|
|
2
2
|
import { Effect, Signal } from "@moq/signals";
|
|
3
3
|
import * as Announce from "../announced.js";
|
|
4
|
+
import { error } from "../error.js";
|
|
4
5
|
import { empty as emptyPath } from "../path.js";
|
|
5
6
|
import { connect } from "./connect.js";
|
|
7
|
+
/**
|
|
8
|
+
* How long to keep retrying before giving up, when {@link ReloadDelay.timeout} is unset.
|
|
9
|
+
*
|
|
10
|
+
* Short on purpose: a failure that clears within it was transient, and one that doesn't should
|
|
11
|
+
* surface as an error rather than leave the page silently reconnecting for minutes.
|
|
12
|
+
*/
|
|
13
|
+
const DEFAULT_TIMEOUT = 10000;
|
|
6
14
|
/** Maintains a MoQ connection, reconnecting with exponential backoff when it drops. */
|
|
7
15
|
export class Reload {
|
|
8
16
|
/** Relay URL to connect to; updating it triggers a reconnect. */
|
|
@@ -33,13 +41,19 @@ export class Reload {
|
|
|
33
41
|
delay;
|
|
34
42
|
/** The reactive effect scope driving the connect loop; closed by {@link Reload.close}. */
|
|
35
43
|
#signals = new Effect();
|
|
36
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
* Resolves when the reconnect loop stops via {@link Reload.close}.
|
|
46
|
+
*
|
|
47
|
+
* Rejects when the loop gives up instead, carrying the failure that was in flight when the
|
|
48
|
+
* retry window expired.
|
|
49
|
+
*/
|
|
37
50
|
closed;
|
|
38
51
|
#closedResolve;
|
|
39
52
|
#closedReject;
|
|
53
|
+
// The current wait between attempts, doubling per failure, and when the retry window expires.
|
|
54
|
+
// Both are undefined between sequences, so a later edit to `delay` applies to the next one.
|
|
40
55
|
#delay;
|
|
41
|
-
|
|
42
|
-
#retryStart;
|
|
56
|
+
#deadline;
|
|
43
57
|
// Increased by 1 each time to trigger a reload.
|
|
44
58
|
#tick = new Signal(0);
|
|
45
59
|
// True after the browser freezes or hides the page until it visibly resumes.
|
|
@@ -50,15 +64,18 @@ export class Reload {
|
|
|
50
64
|
constructor(props) {
|
|
51
65
|
this.url = Signal.from(props?.url);
|
|
52
66
|
this.enabled = Signal.from(props?.enabled ?? false);
|
|
53
|
-
this.delay = props?.delay ?? { initial: 1000, multiplier: 2, max:
|
|
67
|
+
this.delay = props?.delay ?? { initial: 1000, multiplier: 2, max: 5000 };
|
|
54
68
|
this.webtransport = props?.webtransport;
|
|
55
69
|
this.websocket = props?.websocket;
|
|
56
70
|
this.discovery = props?.discovery;
|
|
57
|
-
this.#delay = this.delay.initial;
|
|
58
71
|
this.closed = new Promise((resolve, reject) => {
|
|
59
72
|
this.#closedResolve = resolve;
|
|
60
73
|
this.#closedReject = reject;
|
|
61
74
|
});
|
|
75
|
+
// A caller is free to never await `closed`, and giving up rejects it unprompted. Marking the
|
|
76
|
+
// rejection handled here keeps that from surfacing as an `unhandledrejection`; a consumer
|
|
77
|
+
// awaiting the same promise still receives it.
|
|
78
|
+
this.closed.catch(() => { });
|
|
62
79
|
if (typeof window !== "undefined" && typeof document !== "undefined") {
|
|
63
80
|
this.#signals.event(window, "pagehide", () => this.#suspended.set(true));
|
|
64
81
|
this.#signals.event(window, "pageshow", () => this.#suspended.set(false));
|
|
@@ -126,9 +143,9 @@ export class Reload {
|
|
|
126
143
|
});
|
|
127
144
|
}
|
|
128
145
|
/**
|
|
129
|
-
* Schedule the next connect attempt after the current backoff, or
|
|
130
|
-
*
|
|
131
|
-
*
|
|
146
|
+
* Schedule the next connect attempt after the current backoff, or stop once the retry window
|
|
147
|
+
* has expired. `connected` is when the dead session was established, if it ever was, and
|
|
148
|
+
* `cause` the error that killed it, if it died with one.
|
|
132
149
|
*/
|
|
133
150
|
#retry(effect, connected, cause) {
|
|
134
151
|
// Any session is dead now: report disconnected during the backoff rather than
|
|
@@ -140,27 +157,25 @@ export class Reload {
|
|
|
140
157
|
// shorter is a peer that accepts and immediately severs, which has to keep
|
|
141
158
|
// escalating or we hammer it forever at the initial delay.
|
|
142
159
|
if (connected !== undefined && performance.now() - connected >= this.delay.initial) {
|
|
143
|
-
this.#delay =
|
|
144
|
-
this.#
|
|
160
|
+
this.#delay = undefined;
|
|
161
|
+
this.#deadline = undefined;
|
|
145
162
|
}
|
|
146
|
-
|
|
147
|
-
this
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
this.#closedReject(new Error("reconnect timed out"));
|
|
156
|
-
else
|
|
157
|
-
this.#closedReject(cause instanceof Error ? cause : new Error(String(cause)));
|
|
158
|
-
return;
|
|
159
|
-
}
|
|
163
|
+
const now = performance.now();
|
|
164
|
+
const timeout = this.delay.timeout ?? DEFAULT_TIMEOUT;
|
|
165
|
+
this.#delay ??= this.delay.initial;
|
|
166
|
+
this.#deadline ??= timeout > 0 ? now + timeout : Number.POSITIVE_INFINITY;
|
|
167
|
+
if (now >= this.#deadline) {
|
|
168
|
+
console.warn("reconnect timed out");
|
|
169
|
+
// A graceful close has no error, so report the timeout itself.
|
|
170
|
+
this.#closedReject(cause === undefined ? new Error("reconnect timed out") : error(cause));
|
|
171
|
+
return;
|
|
160
172
|
}
|
|
161
|
-
|
|
162
|
-
|
|
173
|
+
// Equal jitter, so a fleet of tabs knocked offline together doesn't reconnect on the same
|
|
174
|
+
// tick, and never past the deadline the retry window promised.
|
|
175
|
+
const wait = Math.min(this.#delay * (0.5 + Math.random() / 2), this.#deadline - now);
|
|
163
176
|
this.#delay = Math.min(this.#delay * this.delay.multiplier, this.delay.max);
|
|
177
|
+
const tick = this.#tick.peek() + 1;
|
|
178
|
+
effect.timer(() => this.#tick.update((prev) => Math.max(prev, tick)), wait);
|
|
164
179
|
}
|
|
165
180
|
/**
|
|
166
181
|
* Subscribe to broadcast announcements under an optional prefix, spanning reconnects.
|
|
@@ -223,6 +238,20 @@ export class Reload {
|
|
|
223
238
|
void consumer.closed.then(() => pump.close());
|
|
224
239
|
return consumer;
|
|
225
240
|
}
|
|
241
|
+
/**
|
|
242
|
+
* A reactive handle to one broadcast, spanning reconnects.
|
|
243
|
+
*
|
|
244
|
+
* The same {@link Announce.Broadcast} as {@link Established.announcedBroadcast}, but it
|
|
245
|
+
* follows the reconnect loop: the broadcast drops to `undefined` when the connection dies
|
|
246
|
+
* and resolves again once the new connection announces the path. Use it instead of
|
|
247
|
+
* consuming off {@link Reload.established} whenever the broadcast may come online after you
|
|
248
|
+
* do, which is exactly the case a blind `consume` loses.
|
|
249
|
+
*
|
|
250
|
+
* Close the handle when done; {@link Reload.close} only drops it to `undefined`.
|
|
251
|
+
*/
|
|
252
|
+
announcedBroadcast(path) {
|
|
253
|
+
return new Announce.Broadcast({ connection: this.established, path });
|
|
254
|
+
}
|
|
226
255
|
/**
|
|
227
256
|
* Snapshot the live connection's transport counters, or undefined while disconnected.
|
|
228
257
|
* See {@link Established.stats}.
|
package/connection/reload.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reload.js","sourceRoot":"","sources":["../../src/connection/reload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAe,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAqB,OAAO,EAAiD,MAAM,cAAc,CAAC;AAsCzG,uFAAuF;AACvF,MAAM,OAAO,MAAM;IAClB,iEAAiE;IACjE,GAAG,CAA0B;IAE7B,sCAAsC;IACtC,OAAO,CAAkB;IAEzB,iCAAiC;IACjC,MAAM,GAAG,IAAI,MAAM,C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,EAAE,CAAC,CAAC,CAAC;wBACnE,IAAI,CAAC,KAAK;4BAAE,MAAM;wBAClB,IAAI,KAAK,CAAC,MAAM;4BAAE,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;;4BACpC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;wBAC/B,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;oBACxB,CAAC;gBACF,CAAC;gBAAC,MAAM,CAAC;oBACR,mFAAmF;gBACpF,CAAC;wBAAS,CAAC;oBACV,iFAAiF;oBACjF,4DAA4D;oBAC5D,IAAI,CAAC,MAAM,EAAE,CAAC;wBACb,KAAK,MAAM,IAAI,IAAI,MAAM,EAAE,CAAC;4BAC3B,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;wBAC1C,CAAC;oBACF,CAAC;gBACF,CAAC;YACF,CAAC,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAC1C,KAAK,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAE9C,OAAO,QAAQ,CAAC;IACjB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,KAAK;QACV,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC;IACzC,CAAC;IAED,0FAA0F;IAC1F,KAAK;QACJ,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QACtB,IAAI,CAAC,cAAc,EAAE,CAAC;IACvB,CAAC;CACD","sourcesContent":["import { Effect, type Getter, Signal } from \"@moq/signals\";\nimport * as Announce from \"../announced.ts\";\nimport type * as Path from \"../path.ts\";\nimport { empty as emptyPath } from \"../path.ts\";\nimport { type ConnectProps, connect, type WebSocketOptions, type WebTransportProps } from \"./connect.ts\";\nimport type { Established } from \"./established.ts\";\nimport type { Probe, Stats } from \"./stats.ts\";\n\n/** Exponential backoff settings for {@link Reload}'s reconnect loop. */\nexport type ReloadDelay = {\n\t/** The delay in milliseconds before reconnecting (default: 1000). */\n\tinitial: DOMHighResTimeStamp;\n\n\t/** The multiplier for the delay (default: 2). */\n\tmultiplier: number;\n\n\t/** The maximum delay in milliseconds (default: 30000). */\n\tmax: DOMHighResTimeStamp;\n\n\t/**\n\t * Maximum total time in milliseconds to spend retrying before giving up (default:\n\t * 300000, 5 minutes). Resets after each successful connection. Set to 0 for\n\t * unlimited retries.\n\t */\n\ttimeout?: DOMHighResTimeStamp;\n};\n\n/** Connection and retry options for {@link Reload}. */\nexport type ReloadProps = Omit<ConnectProps, \"signal\"> & {\n\t/** Whether to reload the connection when it disconnects (default: true). */\n\tenabled?: boolean | Signal<boolean>;\n\n\t/** The URL of the relay server. */\n\turl?: URL | Signal<URL | undefined>;\n\n\t/** Backoff settings for the reconnect loop. */\n\tdelay?: ReloadDelay;\n};\n\n/** Current state of a {@link Reload} connection. */\nexport type ReloadStatus = \"connecting\" | \"connected\" | \"disconnected\";\n\n/** Maintains a MoQ connection, reconnecting with exponential backoff when it drops. */\nexport class Reload {\n\t/** Relay URL to connect to; updating it triggers a reconnect. */\n\turl: Signal<URL | undefined>;\n\n\t/** Whether reconnecting is active. */\n\tenabled: Signal<boolean>;\n\n\t/** Current connection status. */\n\tstatus = new Signal<ReloadStatus>(\"disconnected\");\n\n\t/** The currently established session, or undefined while disconnected. */\n\testablished = new Signal<Established | undefined>(undefined);\n\n\t/**\n\t * The current connection's PROBE estimates, spanning reconnects.\n\t *\n\t * Undefined while disconnected: the estimates belong to a single connection.\n\t * See {@link Established.probe}.\n\t */\n\treadonly probe: Getter<Probe | undefined>;\n\n\t/** WebTransport options applied to each connection attempt (not reactive). */\n\twebtransport?: WebTransportProps;\n\n\t/** WebSocket fallback options applied to each connection attempt (not reactive). */\n\twebsocket: WebSocketOptions | undefined;\n\n\t/**\n\t * Whether the relay supports broadcast discovery, applied to each connection attempt (not\n\t * reactive). Undefined defers to the default for the URL. See {@link Established.discovery}.\n\t */\n\tdiscovery?: boolean;\n\n\t/** Backoff settings for the reconnect loop. */\n\tdelay: ReloadDelay;\n\n\t/** The reactive effect scope driving the connect loop; closed by {@link Reload.close}. */\n\t#signals = new Effect();\n\n\t/** Resolves when the reconnect loop stops via {@link Reload.close} or the retry timeout. */\n\tclosed: Promise<void>;\n\t#closedResolve!: () => void;\n\t#closedReject!: (err: Error) => void;\n\n\t#delay: DOMHighResTimeStamp;\n\n\t// Timestamp when the current retry sequence started (for timeout).\n\t#retryStart: DOMHighResTimeStamp | undefined;\n\n\t// Increased by 1 each time to trigger a reload.\n\t#tick = new Signal(0);\n\n\t// True after the browser freezes or hides the page until it visibly resumes.\n\t#suspended = new Signal(false);\n\n\t// Use the serialized URL as the reactive connection key. URL objects use identity\n\t// equality, but replacing one with an equivalent instance should not reconnect.\n\t#url: Getter<string | undefined>;\n\tconstructor(props?: ReloadProps) {\n\t\tthis.url = Signal.from(props?.url);\n\t\tthis.enabled = Signal.from(props?.enabled ?? false);\n\t\tthis.delay = props?.delay ?? { initial: 1000, multiplier: 2, max: 30000 };\n\t\tthis.webtransport = props?.webtransport;\n\t\tthis.websocket = props?.websocket;\n\t\tthis.discovery = props?.discovery;\n\n\t\tthis.#delay = this.delay.initial;\n\n\t\tthis.closed = new Promise((resolve, reject) => {\n\t\t\tthis.#closedResolve = resolve;\n\t\t\tthis.#closedReject = reject;\n\t\t});\n\n\t\tif (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n\t\t\tthis.#signals.event(window, \"pagehide\", () => this.#suspended.set(true));\n\t\t\tthis.#signals.event(window, \"pageshow\", () => this.#suspended.set(false));\n\t\t\tthis.#signals.event(window, \"unload\", () => this.#suspended.set(true));\n\t\t\tthis.#signals.event(document, \"visibilitychange\", () => {\n\t\t\t\tif (!document.hidden) this.#suspended.set(false);\n\t\t\t});\n\t\t}\n\n\t\tthis.probe = this.#signals.computed((effect) => {\n\t\t\tconst connection = effect.get(this.established);\n\t\t\treturn connection && effect.get(connection.probe);\n\t\t});\n\n\t\tthis.#url = this.#signals.computed((effect) => effect.get(this.url)?.href);\n\t\t// Create a reactive root so cleanup is easier.\n\t\tthis.#signals.run(this.#connect.bind(this));\n\t}\n\n\t#connect(effect: Effect): void {\n\t\t// Will retry when the tick changes.\n\t\teffect.get(this.#tick);\n\n\t\tconst suspended = effect.get(this.#suspended);\n\t\tconst enabled = effect.get(this.enabled);\n\t\tif (!enabled || suspended) return;\n\n\t\tconst href = effect.get(this.#url);\n\t\tif (!href) return;\n\t\tconst url = new URL(href);\n\n\t\teffect.set(this.status, \"connecting\", \"disconnected\");\n\n\t\t// This run's teardown, handed to connect() so a rerun cancels the attempt in flight.\n\t\tconst signal = effect.abort;\n\n\t\teffect.spawn(async () => {\n\t\t\t// Set once the session is live, so #retry can tell a healthy session that\n\t\t\t// later dropped from a connect failure or a peer that flaps immediately.\n\t\t\tlet connected: DOMHighResTimeStamp | undefined;\n\n\t\t\ttry {\n\t\t\t\tconst connection = await connect(url, {\n\t\t\t\t\twebsocket: this.websocket,\n\t\t\t\t\twebtransport: this.webtransport,\n\t\t\t\t\tdiscovery: this.discovery,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\n\t\t\t\t// Hand the connection to the effect, which closes it now if this run is already over.\n\t\t\t\teffect.cleanup(() => connection.close());\n\t\t\t\tif (signal.aborted) return;\n\n\t\t\t\teffect.set(this.established, connection);\n\t\t\t\teffect.set(this.status, \"connected\", \"disconnected\");\n\n\t\t\t\tconnected = performance.now();\n\n\t\t\t\t// A cancelled effect resolves undefined, so the sentinel tells the session\n\t\t\t\t// closing apart from this run being torn down.\n\t\t\t\tconst closed = await Promise.race([effect.cancel, connection.closed.then(() => true)]);\n\t\t\t\tif (!closed) return;\n\n\t\t\t\tconsole.warn(\"connection closed, reconnecting\");\n\t\t\t\tthis.#retry(effect, connected);\n\t\t\t} catch (err) {\n\t\t\t\t// Treat teardown as cancellation, not a connection failure.\n\t\t\t\tif (signal.aborted) return;\n\n\t\t\t\tconsole.warn(\"connection error:\", err);\n\t\t\t\tthis.#retry(effect, connected, err);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Schedule the next connect attempt after the current backoff, or give up when the\n\t * retry window has expired. `connected` is when the dead session was established, if\n\t * it ever was, and `cause` the error that killed it, if it died with one.\n\t */\n\t#retry(effect: Effect, connected: DOMHighResTimeStamp | undefined, cause?: unknown): void {\n\t\t// Any session is dead now: report disconnected during the backoff rather than\n\t\t// when the retry reruns the effect.\n\t\tthis.established.set(undefined);\n\t\tthis.status.set(\"disconnected\");\n\n\t\t// A session that outlived the initial delay was healthy, so clear the backoff and\n\t\t// start a fresh retry window: a one-off drop should reconnect promptly. Anything\n\t\t// shorter is a peer that accepts and immediately severs, which has to keep\n\t\t// escalating or we hammer it forever at the initial delay.\n\t\tif (connected !== undefined && performance.now() - connected >= this.delay.initial) {\n\t\t\tthis.#delay = this.delay.initial;\n\t\t\tthis.#retryStart = undefined;\n\t\t}\n\n\t\t// Track retry start for timeout.\n\t\tthis.#retryStart ??= performance.now();\n\n\t\tconst timeout = this.delay.timeout ?? 300000;\n\t\tif (timeout > 0) {\n\t\t\tconst elapsed = performance.now() - this.#retryStart;\n\t\t\tif (elapsed >= timeout) {\n\t\t\t\tconsole.warn(\"reconnect timed out\");\n\t\t\t\t// A graceful close has no error, so report the timeout itself.\n\t\t\t\tif (cause === undefined) this.#closedReject(new Error(\"reconnect timed out\"));\n\t\t\t\telse this.#closedReject(cause instanceof Error ? cause : new Error(String(cause)));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tconst tick = this.#tick.peek() + 1;\n\t\teffect.timer(() => this.#tick.update((prev) => Math.max(prev, tick)), this.#delay);\n\n\t\tthis.#delay = Math.min(this.#delay * this.delay.multiplier, this.delay.max);\n\t}\n\n\t/**\n\t * Subscribe to broadcast announcements under an optional prefix, spanning reconnects.\n\t *\n\t * The same {@link Announce.Consumer} stream as {@link Established.announced}, but everything active\n\t * is retracted (an `active: false` update) whenever the connection drops and re-announced on\n\t * reconnect, so a consumer draining `next()` never clings to a dead route across a reconnect.\n\t *\n\t * Stays empty while the relay lacks {@link Established.discovery}.\n\t */\n\tannounced(prefix: Path.Valid = emptyPath()): Announce.Consumer {\n\t\tconst producer = new Announce.Producer(prefix);\n\t\tconst consumer = producer.consume();\n\n\t\t// Closing the consumer closes the shared state, so stop appending after that.\n\t\tlet closed = false;\n\t\tvoid consumer.closed.then(() => {\n\t\t\tclosed = true;\n\t\t});\n\n\t\tconst pump = new Effect();\n\t\tpump.run((effect) => {\n\t\t\tconst conn = effect.get(this.established);\n\t\t\tif (!conn) return;\n\n\t\t\t// Without discovery the upstream announce stream never yields, so leave the\n\t\t\t// consumer empty rather than opening a subscription that can't be answered.\n\t\t\tif (!conn.discovery) return;\n\n\t\t\tconst upstream = conn.announced(prefix);\n\t\t\teffect.cleanup(() => upstream.close());\n\n\t\t\t// Track what this connection announced so we can retract it if the connection drops.\n\t\t\tconst active = new Set<Path.Valid>();\n\n\t\t\teffect.spawn(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\tconst entry = await Promise.race([effect.cancel, upstream.next()]);\n\t\t\t\t\t\tif (!entry) break;\n\t\t\t\t\t\tif (entry.active) active.add(entry.path);\n\t\t\t\t\t\telse active.delete(entry.path);\n\t\t\t\t\t\tproducer.append(entry);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// A dropped connection resets the announce stream; the retractions below cover it.\n\t\t\t\t} finally {\n\t\t\t\t\t// Retract everything from the connection that just went away, so a per-broadcast\n\t\t\t\t\t// watcher tears down instead of clinging to the dead route.\n\t\t\t\t\tif (!closed) {\n\t\t\t\t\t\tfor (const path of active) {\n\t\t\t\t\t\t\tproducer.append({ path, active: false });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\tthis.#signals.cleanup(() => pump.close());\n\t\tvoid consumer.closed.then(() => pump.close());\n\n\t\treturn consumer;\n\t}\n\n\t/**\n\t * Snapshot the live connection's transport counters, or undefined while disconnected.\n\t * See {@link Established.stats}.\n\t */\n\tasync stats(): Promise<Stats | undefined> {\n\t\treturn this.established.peek()?.stats();\n\t}\n\n\t/** Stop reconnecting, close the current connection, and resolve {@link Reload.closed}. */\n\tclose() {\n\t\tthis.#signals.close();\n\t\tthis.#closedResolve();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"reload.js","sourceRoot":"","sources":["../../src/connection/reload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAe,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEpC,OAAO,EAAE,KAAK,IAAI,SAAS,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAqB,OAAO,EAAiD,MAAM,cAAc,CAAC;AAuCzG;;;;;GAKG;AACH,MAAM,eAAe,GAAG,KAAK,CAAC;AAK9B,uFAAuF;AACvF,MAAM,OAAO,MAAM;IAClB,iEAAiE;IACjE,GAAG,CAA0B;IAE7B,sCAAsC;IACtC,OAAO,CAAkB;IAEzB,iCAAiC;IACjC,MAAM,GAAG,IAAI,MAAM,CAAe,cAAc,CAAC,CAAC;IAElD,0EAA0E;IAC1E,WAAW,GAAG,IAAI,MAAM,CAA0B,SAAS,CAAC,CAAC;IAE7D;;;;;OAKG;IACM,KAAK,CAA4B;IAE1C,8EAA8E;IAC9E,YAAY,CAAqB;IAEjC,oFAAoF;IACpF,SAAS,CAA+B;IAExC;;;OAGG;IACH,SAAS,CAAW;IAEpB,+CAA+C;IAC/C,KAAK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AC;CACD","sourcesContent":["import { Effect, type Getter, Signal } from \"@moq/signals\";\nimport * as Announce from \"../announced.ts\";\nimport { error } from \"../error.ts\";\nimport type * as Path from \"../path.ts\";\nimport { empty as emptyPath } from \"../path.ts\";\nimport { type ConnectProps, connect, type WebSocketOptions, type WebTransportProps } from \"./connect.ts\";\nimport type { Established } from \"./established.ts\";\nimport type { Probe, Stats } from \"./stats.ts\";\n\n/**\n * Exponential backoff settings for {@link Reload}'s reconnect loop.\n *\n * The delays carry jitter, so a fleet of tabs knocked offline together doesn't reconnect in\n * lockstep. Every failure is retried; {@link ReloadDelay.timeout} is what stops the loop.\n */\nexport type ReloadDelay = {\n\t/** The delay in milliseconds before reconnecting (default: 1000). */\n\tinitial: DOMHighResTimeStamp;\n\n\t/** The multiplier for the delay (default: 2). */\n\tmultiplier: number;\n\n\t/** The maximum delay in milliseconds (default: 5000). */\n\tmax: DOMHighResTimeStamp;\n\n\t/**\n\t * Maximum total time in milliseconds to spend retrying before giving up (default:\n\t * 10000). Resets after each successful connection. Set to 0 for unlimited retries.\n\t */\n\ttimeout?: DOMHighResTimeStamp;\n};\n\n/** Connection and retry options for {@link Reload}. */\nexport type ReloadProps = Omit<ConnectProps, \"signal\"> & {\n\t/** Whether to reload the connection when it disconnects (default: true). */\n\tenabled?: boolean | Signal<boolean>;\n\n\t/** The URL of the relay server. */\n\turl?: URL | Signal<URL | undefined>;\n\n\t/** Backoff settings for the reconnect loop. */\n\tdelay?: ReloadDelay;\n};\n\n/**\n * How long to keep retrying before giving up, when {@link ReloadDelay.timeout} is unset.\n *\n * Short on purpose: a failure that clears within it was transient, and one that doesn't should\n * surface as an error rather than leave the page silently reconnecting for minutes.\n */\nconst DEFAULT_TIMEOUT = 10000;\n\n/** Current state of a {@link Reload} connection. */\nexport type ReloadStatus = \"connecting\" | \"connected\" | \"disconnected\";\n\n/** Maintains a MoQ connection, reconnecting with exponential backoff when it drops. */\nexport class Reload {\n\t/** Relay URL to connect to; updating it triggers a reconnect. */\n\turl: Signal<URL | undefined>;\n\n\t/** Whether reconnecting is active. */\n\tenabled: Signal<boolean>;\n\n\t/** Current connection status. */\n\tstatus = new Signal<ReloadStatus>(\"disconnected\");\n\n\t/** The currently established session, or undefined while disconnected. */\n\testablished = new Signal<Established | undefined>(undefined);\n\n\t/**\n\t * The current connection's PROBE estimates, spanning reconnects.\n\t *\n\t * Undefined while disconnected: the estimates belong to a single connection.\n\t * See {@link Established.probe}.\n\t */\n\treadonly probe: Getter<Probe | undefined>;\n\n\t/** WebTransport options applied to each connection attempt (not reactive). */\n\twebtransport?: WebTransportProps;\n\n\t/** WebSocket fallback options applied to each connection attempt (not reactive). */\n\twebsocket: WebSocketOptions | undefined;\n\n\t/**\n\t * Whether the relay supports broadcast discovery, applied to each connection attempt (not\n\t * reactive). Undefined defers to the default for the URL. See {@link Established.discovery}.\n\t */\n\tdiscovery?: boolean;\n\n\t/** Backoff settings for the reconnect loop. */\n\tdelay: ReloadDelay;\n\n\t/** The reactive effect scope driving the connect loop; closed by {@link Reload.close}. */\n\t#signals = new Effect();\n\n\t/**\n\t * Resolves when the reconnect loop stops via {@link Reload.close}.\n\t *\n\t * Rejects when the loop gives up instead, carrying the failure that was in flight when the\n\t * retry window expired.\n\t */\n\tclosed: Promise<void>;\n\t#closedResolve!: () => void;\n\t#closedReject!: (err: Error) => void;\n\n\t// The current wait between attempts, doubling per failure, and when the retry window expires.\n\t// Both are undefined between sequences, so a later edit to `delay` applies to the next one.\n\t#delay: DOMHighResTimeStamp | undefined;\n\t#deadline: DOMHighResTimeStamp | undefined;\n\n\t// Increased by 1 each time to trigger a reload.\n\t#tick = new Signal(0);\n\n\t// True after the browser freezes or hides the page until it visibly resumes.\n\t#suspended = new Signal(false);\n\n\t// Use the serialized URL as the reactive connection key. URL objects use identity\n\t// equality, but replacing one with an equivalent instance should not reconnect.\n\t#url: Getter<string | undefined>;\n\tconstructor(props?: ReloadProps) {\n\t\tthis.url = Signal.from(props?.url);\n\t\tthis.enabled = Signal.from(props?.enabled ?? false);\n\t\tthis.delay = props?.delay ?? { initial: 1000, multiplier: 2, max: 5000 };\n\t\tthis.webtransport = props?.webtransport;\n\t\tthis.websocket = props?.websocket;\n\t\tthis.discovery = props?.discovery;\n\n\t\tthis.closed = new Promise((resolve, reject) => {\n\t\t\tthis.#closedResolve = resolve;\n\t\t\tthis.#closedReject = reject;\n\t\t});\n\n\t\t// A caller is free to never await `closed`, and giving up rejects it unprompted. Marking the\n\t\t// rejection handled here keeps that from surfacing as an `unhandledrejection`; a consumer\n\t\t// awaiting the same promise still receives it.\n\t\tthis.closed.catch(() => {});\n\n\t\tif (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n\t\t\tthis.#signals.event(window, \"pagehide\", () => this.#suspended.set(true));\n\t\t\tthis.#signals.event(window, \"pageshow\", () => this.#suspended.set(false));\n\t\t\tthis.#signals.event(window, \"unload\", () => this.#suspended.set(true));\n\t\t\tthis.#signals.event(document, \"visibilitychange\", () => {\n\t\t\t\tif (!document.hidden) this.#suspended.set(false);\n\t\t\t});\n\t\t}\n\n\t\tthis.probe = this.#signals.computed((effect) => {\n\t\t\tconst connection = effect.get(this.established);\n\t\t\treturn connection && effect.get(connection.probe);\n\t\t});\n\n\t\tthis.#url = this.#signals.computed((effect) => effect.get(this.url)?.href);\n\t\t// Create a reactive root so cleanup is easier.\n\t\tthis.#signals.run(this.#connect.bind(this));\n\t}\n\n\t#connect(effect: Effect): void {\n\t\t// Will retry when the tick changes.\n\t\teffect.get(this.#tick);\n\n\t\tconst suspended = effect.get(this.#suspended);\n\t\tconst enabled = effect.get(this.enabled);\n\t\tif (!enabled || suspended) return;\n\n\t\tconst href = effect.get(this.#url);\n\t\tif (!href) return;\n\t\tconst url = new URL(href);\n\n\t\teffect.set(this.status, \"connecting\", \"disconnected\");\n\n\t\t// This run's teardown, handed to connect() so a rerun cancels the attempt in flight.\n\t\tconst signal = effect.abort;\n\n\t\teffect.spawn(async () => {\n\t\t\t// Set once the session is live, so #retry can tell a healthy session that\n\t\t\t// later dropped from a connect failure or a peer that flaps immediately.\n\t\t\tlet connected: DOMHighResTimeStamp | undefined;\n\n\t\t\ttry {\n\t\t\t\tconst connection = await connect(url, {\n\t\t\t\t\twebsocket: this.websocket,\n\t\t\t\t\twebtransport: this.webtransport,\n\t\t\t\t\tdiscovery: this.discovery,\n\t\t\t\t\tsignal,\n\t\t\t\t});\n\n\t\t\t\t// Hand the connection to the effect, which closes it now if this run is already over.\n\t\t\t\teffect.cleanup(() => connection.close());\n\t\t\t\tif (signal.aborted) return;\n\n\t\t\t\teffect.set(this.established, connection);\n\t\t\t\teffect.set(this.status, \"connected\", \"disconnected\");\n\n\t\t\t\tconnected = performance.now();\n\n\t\t\t\t// A cancelled effect resolves undefined, so the sentinel tells the session\n\t\t\t\t// closing apart from this run being torn down.\n\t\t\t\tconst closed = await Promise.race([effect.cancel, connection.closed.then(() => true)]);\n\t\t\t\tif (!closed) return;\n\n\t\t\t\tconsole.warn(\"connection closed, reconnecting\");\n\t\t\t\tthis.#retry(effect, connected);\n\t\t\t} catch (err) {\n\t\t\t\t// Treat teardown as cancellation, not a connection failure.\n\t\t\t\tif (signal.aborted) return;\n\n\t\t\t\tconsole.warn(\"connection error:\", err);\n\t\t\t\tthis.#retry(effect, connected, err);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Schedule the next connect attempt after the current backoff, or stop once the retry window\n\t * has expired. `connected` is when the dead session was established, if it ever was, and\n\t * `cause` the error that killed it, if it died with one.\n\t */\n\t#retry(effect: Effect, connected: DOMHighResTimeStamp | undefined, cause?: unknown): void {\n\t\t// Any session is dead now: report disconnected during the backoff rather than\n\t\t// when the retry reruns the effect.\n\t\tthis.established.set(undefined);\n\t\tthis.status.set(\"disconnected\");\n\n\t\t// A session that outlived the initial delay was healthy, so clear the backoff and\n\t\t// start a fresh retry window: a one-off drop should reconnect promptly. Anything\n\t\t// shorter is a peer that accepts and immediately severs, which has to keep\n\t\t// escalating or we hammer it forever at the initial delay.\n\t\tif (connected !== undefined && performance.now() - connected >= this.delay.initial) {\n\t\t\tthis.#delay = undefined;\n\t\t\tthis.#deadline = undefined;\n\t\t}\n\n\t\tconst now = performance.now();\n\t\tconst timeout = this.delay.timeout ?? DEFAULT_TIMEOUT;\n\t\tthis.#delay ??= this.delay.initial;\n\t\tthis.#deadline ??= timeout > 0 ? now + timeout : Number.POSITIVE_INFINITY;\n\n\t\tif (now >= this.#deadline) {\n\t\t\tconsole.warn(\"reconnect timed out\");\n\t\t\t// A graceful close has no error, so report the timeout itself.\n\t\t\tthis.#closedReject(cause === undefined ? new Error(\"reconnect timed out\") : error(cause));\n\t\t\treturn;\n\t\t}\n\n\t\t// Equal jitter, so a fleet of tabs knocked offline together doesn't reconnect on the same\n\t\t// tick, and never past the deadline the retry window promised.\n\t\tconst wait = Math.min(this.#delay * (0.5 + Math.random() / 2), this.#deadline - now);\n\t\tthis.#delay = Math.min(this.#delay * this.delay.multiplier, this.delay.max);\n\n\t\tconst tick = this.#tick.peek() + 1;\n\t\teffect.timer(() => this.#tick.update((prev) => Math.max(prev, tick)), wait);\n\t}\n\n\t/**\n\t * Subscribe to broadcast announcements under an optional prefix, spanning reconnects.\n\t *\n\t * The same {@link Announce.Consumer} stream as {@link Established.announced}, but everything active\n\t * is retracted (an `active: false` update) whenever the connection drops and re-announced on\n\t * reconnect, so a consumer draining `next()` never clings to a dead route across a reconnect.\n\t *\n\t * Stays empty while the relay lacks {@link Established.discovery}.\n\t */\n\tannounced(prefix: Path.Valid = emptyPath()): Announce.Consumer {\n\t\tconst producer = new Announce.Producer(prefix);\n\t\tconst consumer = producer.consume();\n\n\t\t// Closing the consumer closes the shared state, so stop appending after that.\n\t\tlet closed = false;\n\t\tvoid consumer.closed.then(() => {\n\t\t\tclosed = true;\n\t\t});\n\n\t\tconst pump = new Effect();\n\t\tpump.run((effect) => {\n\t\t\tconst conn = effect.get(this.established);\n\t\t\tif (!conn) return;\n\n\t\t\t// Without discovery the upstream announce stream never yields, so leave the\n\t\t\t// consumer empty rather than opening a subscription that can't be answered.\n\t\t\tif (!conn.discovery) return;\n\n\t\t\tconst upstream = conn.announced(prefix);\n\t\t\teffect.cleanup(() => upstream.close());\n\n\t\t\t// Track what this connection announced so we can retract it if the connection drops.\n\t\t\tconst active = new Set<Path.Valid>();\n\n\t\t\teffect.spawn(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\tconst entry = await Promise.race([effect.cancel, upstream.next()]);\n\t\t\t\t\t\tif (!entry) break;\n\t\t\t\t\t\tif (entry.active) active.add(entry.path);\n\t\t\t\t\t\telse active.delete(entry.path);\n\t\t\t\t\t\tproducer.append(entry);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// A dropped connection resets the announce stream; the retractions below cover it.\n\t\t\t\t} finally {\n\t\t\t\t\t// Retract everything from the connection that just went away, so a per-broadcast\n\t\t\t\t\t// watcher tears down instead of clinging to the dead route.\n\t\t\t\t\tif (!closed) {\n\t\t\t\t\t\tfor (const path of active) {\n\t\t\t\t\t\t\tproducer.append({ path, active: false });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\tthis.#signals.cleanup(() => pump.close());\n\t\tvoid consumer.closed.then(() => pump.close());\n\n\t\treturn consumer;\n\t}\n\n\t/**\n\t * A reactive handle to one broadcast, spanning reconnects.\n\t *\n\t * The same {@link Announce.Broadcast} as {@link Established.announcedBroadcast}, but it\n\t * follows the reconnect loop: the broadcast drops to `undefined` when the connection dies\n\t * and resolves again once the new connection announces the path. Use it instead of\n\t * consuming off {@link Reload.established} whenever the broadcast may come online after you\n\t * do, which is exactly the case a blind `consume` loses.\n\t *\n\t * Close the handle when done; {@link Reload.close} only drops it to `undefined`.\n\t */\n\tannouncedBroadcast(path: Path.Valid): Announce.Broadcast {\n\t\treturn new Announce.Broadcast({ connection: this.established, path });\n\t}\n\n\t/**\n\t * Snapshot the live connection's transport counters, or undefined while disconnected.\n\t * See {@link Established.stats}.\n\t */\n\tasync stats(): Promise<Stats | undefined> {\n\t\treturn this.established.peek()?.stats();\n\t}\n\n\t/** Stop reconnecting, close the current connection, and resolve {@link Reload.closed}. */\n\tclose() {\n\t\tthis.#signals.close();\n\t\tthis.#closedResolve();\n\t}\n}\n"]}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/* @ts-self-types="./reload.test.d.ts" */
|
|
2
2
|
import { expect, test } from "bun:test";
|
|
3
|
+
import { Producer as BroadcastProducer } from "../broadcast.js";
|
|
3
4
|
import * as Lite from "../lite/index.js";
|
|
4
5
|
import { createMockTransportPair } from "../mock.js";
|
|
6
|
+
import * as Path from "../path.js";
|
|
5
7
|
import { accept } from "./index.js";
|
|
6
8
|
import { Reload } from "./reload.js";
|
|
7
9
|
async function settle() {
|
|
@@ -101,4 +103,58 @@ test("a peer that severs immediately keeps escalating the backoff", async () =>
|
|
|
101
103
|
globalThis.WebTransport = original;
|
|
102
104
|
}
|
|
103
105
|
});
|
|
106
|
+
// Polls until `pred` holds, so a regression fails the test instead of hanging it.
|
|
107
|
+
async function waitUntil(pred) {
|
|
108
|
+
for (let i = 0; i < 500; i++) {
|
|
109
|
+
if (pred())
|
|
110
|
+
return;
|
|
111
|
+
await settle();
|
|
112
|
+
}
|
|
113
|
+
throw new Error("timed out waiting for condition");
|
|
114
|
+
}
|
|
115
|
+
test("announcedBroadcast follows the reconnect loop", async () => {
|
|
116
|
+
const original = globalThis.WebTransport;
|
|
117
|
+
const url = new URL("https://example.com/");
|
|
118
|
+
// Every connect attempt gets a fresh session, whose server publishes the path once the
|
|
119
|
+
// handshake finishes. The client therefore always asks before the broadcast exists.
|
|
120
|
+
const sessions = [];
|
|
121
|
+
const published = [];
|
|
122
|
+
const stub = function StubWebTransport() {
|
|
123
|
+
const pair = createMockTransportPair(Lite.ALPN_06_WIP);
|
|
124
|
+
void accept(pair.server, url).then((server) => {
|
|
125
|
+
sessions.push(server);
|
|
126
|
+
const broadcast = new BroadcastProducer();
|
|
127
|
+
published.push(broadcast);
|
|
128
|
+
server.publish(Path.from("late"), broadcast);
|
|
129
|
+
});
|
|
130
|
+
return pair.client;
|
|
131
|
+
};
|
|
132
|
+
globalThis.WebTransport = stub;
|
|
133
|
+
const reload = new Reload({
|
|
134
|
+
enabled: true,
|
|
135
|
+
url,
|
|
136
|
+
websocket: { enabled: false },
|
|
137
|
+
delay: { initial: 10, multiplier: 1, max: 10 },
|
|
138
|
+
});
|
|
139
|
+
const watched = reload.announcedBroadcast(Path.from("late"));
|
|
140
|
+
try {
|
|
141
|
+
await waitUntil(() => watched.active.peek() !== undefined);
|
|
142
|
+
const first = watched.active.peek();
|
|
143
|
+
// The session dies: the handle drops the broadcast rather than clinging to a dead one.
|
|
144
|
+
sessions[0]?.close();
|
|
145
|
+
await waitUntil(() => watched.active.peek() === undefined);
|
|
146
|
+
// The reconnect re-announces it, and the handle re-consumes on the new session.
|
|
147
|
+
await waitUntil(() => watched.active.peek() !== undefined);
|
|
148
|
+
expect(watched.active.peek()).not.toBe(first);
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
watched.close();
|
|
152
|
+
reload.close();
|
|
153
|
+
for (const broadcast of published)
|
|
154
|
+
broadcast.close();
|
|
155
|
+
for (const session of sessions)
|
|
156
|
+
session.close();
|
|
157
|
+
globalThis.WebTransport = original;
|
|
158
|
+
}
|
|
159
|
+
});
|
|
104
160
|
//# sourceMappingURL=reload.test.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reload.test.js","sourceRoot":"","sources":["../../src/connection/reload.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OA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ect, test } from \"bun:test\";\nimport * as Lite from \"../lite/index.ts\";\nimport { createMockTransportPair } from \"../mock.ts\";\nimport { accept } from \"./index.ts\";\nimport { Reload, type ReloadProps } from \"./reload.ts\";\n\nasync function settle() {\n\tawait new Promise((resolve) => setTimeout(resolve, 0));\n}\n\ntest(\"equivalent URL instances do not restart a pending connection\", async () => {\n\tconst original = globalThis.WebTransport;\n\tlet connects = 0;\n\n\tclass PendingWebTransport {\n\t\tready = new Promise<void>(() => {});\n\t\tclosed = new Promise<void>(() => {});\n\n\t\tconstructor() {\n\t\t\tconnects++;\n\t\t}\n\n\t\tclose() {}\n\t}\n\n\tglobalThis.WebTransport = PendingWebTransport as unknown as typeof WebTransport;\n\tconst reload = new Reload({\n\t\tenabled: true,\n\t\turl: new URL(\"https://example.com/broadcast\"),\n\t\twebsocket: { enabled: false },\n\t});\n\n\ttry {\n\t\tawait settle();\n\t\texpect(connects).toBe(1);\n\n\t\treload.url.set(new URL(\"https://example.com/broadcast\"));\n\t\tawait settle();\n\t\texpect(connects).toBe(1);\n\n\t\treload.url.set(new URL(\"https://example.com/other\"));\n\t\tawait settle();\n\t\texpect(connects).toBe(2);\n\t} finally {\n\t\treload.close();\n\t\tglobalThis.WebTransport = original;\n\t}\n});\n\ntest(\"ReloadProps excludes signal\", () => {\n\t// @ts-expect-error signal is not part of ReloadProps\n\tconst props: ReloadProps = { signal: new AbortController().signal };\n\texpect(props.enabled).toBeUndefined();\n});\n\ntest(\"closing mid-connect aborts the pending attempt\", async () => {\n\tconst original = globalThis.WebTransport;\n\tlet closes = 0;\n\n\tclass PendingWebTransport {\n\t\tready = new Promise<void>(() => {});\n\t\tclosed = new Promise<void>(() => {});\n\n\t\tclose() {\n\t\t\tcloses++;\n\t\t}\n\t}\n\n\tglobalThis.WebTransport = PendingWebTransport as unknown as typeof WebTransport;\n\tconst reload = new Reload({\n\t\tenabled: true,\n\t\turl: new URL(\"https://example.com/broadcast\"),\n\t\twebsocket: { enabled: false },\n\t});\n\n\ttry {\n\t\tawait settle();\n\t\texpect(closes).toBe(0);\n\n\t\treload.close();\n\t\tawait settle();\n\t\texpect(closes).toBe(1);\n\t} finally {\n\t\tglobalThis.WebTransport = original;\n\t}\n});\n\ntest(\"a peer that severs immediately keeps escalating the backoff\", async () => {\n\tconst original = globalThis.WebTransport;\n\tconst url = new URL(\"https://example.com/\");\n\tconst stub = function StubWebTransport() {\n\t\tconst pair = createMockTransportPair(Lite.ALPN_06_WIP);\n\t\t// Sever the session as soon as the server side finishes the handshake.\n\t\tvoid accept(pair.server, url).then((server) => server.close());\n\t\treturn pair.client;\n\t};\n\tglobalThis.WebTransport = stub as unknown as typeof WebTransport;\n\n\t// Every session dies well within `initial`, so the backoff has to keep escalating\n\t// and the retry window has to expire. Resetting either on each successful connect\n\t// reconnects forever at the initial delay and never gives up.\n\t//\n\t// `initial` sits far above the in-process handshake so a loaded runner can't make a\n\t// session look healthy, and the tiny timeout gives up after one backoff.\n\tconst reload = new Reload({\n\t\tenabled: true,\n\t\turl,\n\t\twebsocket: { enabled: false },\n\t\tdelay: { initial: 1000, multiplier: 2, max: 1000, timeout: 1 },\n\t});\n\ttry {\n\t\tawait expect(reload.closed).rejects.toThrow();\n\t} finally {\n\t\treload.close();\n\t\tglobalThis.WebTransport = original;\n\t}\n});\n"]}
|
|
1
|
+
{"version":3,"file":"reload.test.js","sourceRoot":"","sources":["../../src/connection/reload.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,QAAQ,IAAI,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAChE,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,MAAM,EAAoB,M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EAAE,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE;KAC9C,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,MAAM,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAE7D,IAAI,CAAC;QACJ,MAAM,SAAS,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS,CAAC,CAAC;QAC3D,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;QAEpC,uFAAuF;QACvF,QAAQ,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;QACrB,MAAM,SAAS,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS,CAAC,CAAC;QAE3D,gFAAgF;QAChF,MAAM,SAAS,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS,CAAC,CAAC;QAC3D,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/C,CAAC;YAAS,CAAC;QACV,OAAO,CAAC,KAAK,EAAE,CAAC;QAChB,MAAM,CAAC,KAAK,EAAE,CAAC;QACf,KAAK,MAAM,SAAS,IAAI,SAAS;YAAE,SAAS,CAAC,KAAK,EAAE,CAAC;QACrD,KAAK,MAAM,OAAO,IAAI,QAAQ;YAAE,OAAO,CAAC,KAAK,EAAE,CAAC;QAChD,UAAU,CAAC,YAAY,GAAG,QAAQ,CAAC;IACpC,CAAC;AACF,CAAC,CAAC,CAAC","sourcesContent":["import { expect, test } from \"bun:test\";\nimport { Producer as BroadcastProducer } from \"../broadcast.ts\";\nimport * as Lite from \"../lite/index.ts\";\nimport { createMockTransportPair } from \"../mock.ts\";\nimport * as Path from \"../path.ts\";\nimport { accept } from \"./index.ts\";\nimport { Reload, type ReloadProps } from \"./reload.ts\";\n\nasync function settle() {\n\tawait new Promise((resolve) => setTimeout(resolve, 0));\n}\n\ntest(\"equivalent URL instances do not restart a pending connection\", async () => {\n\tconst original = globalThis.WebTransport;\n\tlet connects = 0;\n\n\tclass PendingWebTransport {\n\t\tready = new Promise<void>(() => {});\n\t\tclosed = new Promise<void>(() => {});\n\n\t\tconstructor() {\n\t\t\tconnects++;\n\t\t}\n\n\t\tclose() {}\n\t}\n\n\tglobalThis.WebTransport = PendingWebTransport as unknown as typeof WebTransport;\n\tconst reload = new Reload({\n\t\tenabled: true,\n\t\turl: new URL(\"https://example.com/broadcast\"),\n\t\twebsocket: { enabled: false },\n\t});\n\n\ttry {\n\t\tawait settle();\n\t\texpect(connects).toBe(1);\n\n\t\treload.url.set(new URL(\"https://example.com/broadcast\"));\n\t\tawait settle();\n\t\texpect(connects).toBe(1);\n\n\t\treload.url.set(new URL(\"https://example.com/other\"));\n\t\tawait settle();\n\t\texpect(connects).toBe(2);\n\t} finally {\n\t\treload.close();\n\t\tglobalThis.WebTransport = original;\n\t}\n});\n\ntest(\"ReloadProps excludes signal\", () => {\n\t// @ts-expect-error signal is not part of ReloadProps\n\tconst props: ReloadProps = { signal: new AbortController().signal };\n\texpect(props.enabled).toBeUndefined();\n});\n\ntest(\"closing mid-connect aborts the pending attempt\", async () => {\n\tconst original = globalThis.WebTransport;\n\tlet closes = 0;\n\n\tclass PendingWebTransport {\n\t\tready = new Promise<void>(() => {});\n\t\tclosed = new Promise<void>(() => {});\n\n\t\tclose() {\n\t\t\tcloses++;\n\t\t}\n\t}\n\n\tglobalThis.WebTransport = PendingWebTransport as unknown as typeof WebTransport;\n\tconst reload = new Reload({\n\t\tenabled: true,\n\t\turl: new URL(\"https://example.com/broadcast\"),\n\t\twebsocket: { enabled: false },\n\t});\n\n\ttry {\n\t\tawait settle();\n\t\texpect(closes).toBe(0);\n\n\t\treload.close();\n\t\tawait settle();\n\t\texpect(closes).toBe(1);\n\t} finally {\n\t\tglobalThis.WebTransport = original;\n\t}\n});\n\ntest(\"a peer that severs immediately keeps escalating the backoff\", async () => {\n\tconst original = globalThis.WebTransport;\n\tconst url = new URL(\"https://example.com/\");\n\tconst stub = function StubWebTransport() {\n\t\tconst pair = createMockTransportPair(Lite.ALPN_06_WIP);\n\t\t// Sever the session as soon as the server side finishes the handshake.\n\t\tvoid accept(pair.server, url).then((server) => server.close());\n\t\treturn pair.client;\n\t};\n\tglobalThis.WebTransport = stub as unknown as typeof WebTransport;\n\n\t// Every session dies well within `initial`, so the backoff has to keep escalating\n\t// and the retry window has to expire. Resetting either on each successful connect\n\t// reconnects forever at the initial delay and never gives up.\n\t//\n\t// `initial` sits far above the in-process handshake so a loaded runner can't make a\n\t// session look healthy, and the tiny timeout gives up after one backoff.\n\tconst reload = new Reload({\n\t\tenabled: true,\n\t\turl,\n\t\twebsocket: { enabled: false },\n\t\tdelay: { initial: 1000, multiplier: 2, max: 1000, timeout: 1 },\n\t});\n\ttry {\n\t\tawait expect(reload.closed).rejects.toThrow();\n\t} finally {\n\t\treload.close();\n\t\tglobalThis.WebTransport = original;\n\t}\n});\n\n// Polls until `pred` holds, so a regression fails the test instead of hanging it.\nasync function waitUntil(pred: () => boolean): Promise<void> {\n\tfor (let i = 0; i < 500; i++) {\n\t\tif (pred()) return;\n\t\tawait settle();\n\t}\n\tthrow new Error(\"timed out waiting for condition\");\n}\n\ntest(\"announcedBroadcast follows the reconnect loop\", async () => {\n\tconst original = globalThis.WebTransport;\n\tconst url = new URL(\"https://example.com/\");\n\n\t// Every connect attempt gets a fresh session, whose server publishes the path once the\n\t// handshake finishes. The client therefore always asks before the broadcast exists.\n\tconst sessions: { close: () => void }[] = [];\n\tconst published: BroadcastProducer[] = [];\n\tconst stub = function StubWebTransport() {\n\t\tconst pair = createMockTransportPair(Lite.ALPN_06_WIP);\n\t\tvoid accept(pair.server, url).then((server) => {\n\t\t\tsessions.push(server);\n\t\t\tconst broadcast = new BroadcastProducer();\n\t\t\tpublished.push(broadcast);\n\t\t\tserver.publish(Path.from(\"late\"), broadcast);\n\t\t});\n\t\treturn pair.client;\n\t};\n\tglobalThis.WebTransport = stub as unknown as typeof WebTransport;\n\n\tconst reload = new Reload({\n\t\tenabled: true,\n\t\turl,\n\t\twebsocket: { enabled: false },\n\t\tdelay: { initial: 10, multiplier: 1, max: 10 },\n\t});\n\tconst watched = reload.announcedBroadcast(Path.from(\"late\"));\n\n\ttry {\n\t\tawait waitUntil(() => watched.active.peek() !== undefined);\n\t\tconst first = watched.active.peek();\n\n\t\t// The session dies: the handle drops the broadcast rather than clinging to a dead one.\n\t\tsessions[0]?.close();\n\t\tawait waitUntil(() => watched.active.peek() === undefined);\n\n\t\t// The reconnect re-announces it, and the handle re-consumes on the new session.\n\t\tawait waitUntil(() => watched.active.peek() !== undefined);\n\t\texpect(watched.active.peek()).not.toBe(first);\n\t} finally {\n\t\twatched.close();\n\t\treload.close();\n\t\tfor (const broadcast of published) broadcast.close();\n\t\tfor (const session of sessions) session.close();\n\t\tglobalThis.WebTransport = original;\n\t}\n});\n"]}
|
package/consume.d.ts
CHANGED
|
@@ -22,5 +22,23 @@ export declare class BroadcastCache {
|
|
|
22
22
|
* Call on a {@link get} miss, after wiring up the fresh consumer's subscribe loop.
|
|
23
23
|
*/
|
|
24
24
|
insert(path: Path.Valid, consumer: broadcast.Consumer): broadcast.Consumer;
|
|
25
|
+
/**
|
|
26
|
+
* Stop sharing the broadcast cached for `path`, so the next request subscribes fresh.
|
|
27
|
+
*
|
|
28
|
+
* Call when the path's advertisement goes away. A handle only leaves the cache on its own
|
|
29
|
+
* once *every* holder has closed it, so one holder outliving the publisher (a second
|
|
30
|
+
* watcher, or a caller consuming the path directly) would otherwise keep the dead
|
|
31
|
+
* generation's cached tracks alive and hand them to whoever consumes the path next.
|
|
32
|
+
* Existing handles are left alone: they belong to their holders, and the wire resets
|
|
33
|
+
* whatever they still have open.
|
|
34
|
+
*
|
|
35
|
+
* Eviction is unconditional, which costs a dedup miss when two announcement streams watch
|
|
36
|
+
* one path: the second stream's retraction can arrive after the first has already seen the
|
|
37
|
+
* replacement, dropping the fresh entry so the next request subscribes again instead of
|
|
38
|
+
* sharing. Telling that stale retraction from a live one needs a generation id on the
|
|
39
|
+
* advertisement (moq-lite's `Epoch`, not yet on the wire), so until then this errs toward a
|
|
40
|
+
* duplicate subscription rather than risk handing out a dead one.
|
|
41
|
+
*/
|
|
42
|
+
evict(path: Path.Valid): void;
|
|
25
43
|
}
|
|
26
44
|
//# sourceMappingURL=consume.d.ts.map
|
package/consume.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"consume.d.ts","sourceRoot":"","sources":["../src/consume.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,SAAS,MAAM,gBAAgB,CAAC;AACjD,OAAO,KAAK,KAAK,IAAI,MAAM,WAAW,CAAC;AAEvC;;;;;;;;;;;;GAYG;AACH,qBAAa,cAAc;;IAI1B,yFAAyF;IACzF,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,QAAQ,GAAG,SAAS,CAIpD;IAED;;;OAGG;IACH,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,SAAS,CAAC,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAUzE;CACD"}
|
|
1
|
+
{"version":3,"file":"consume.d.ts","sourceRoot":"","sources":["../src/consume.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,SAAS,MAAM,gBAAgB,CAAC;AACjD,OAAO,KAAK,KAAK,IAAI,MAAM,WAAW,CAAC;AAEvC;;;;;;;;;;;;GAYG;AACH,qBAAa,cAAc;;IAI1B,yFAAyF;IACzF,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,QAAQ,GAAG,SAAS,CAIpD;IAED;;;OAGG;IACH,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,SAAS,CAAC,QAAQ,GAAG,SAAS,CAAC,QAAQ,CAUzE;IAED;;;;;;;;;;;;;;;;OAgBG;IACH,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAE5B;CACD"}
|