diff --git a/.github/workflows/interop.yml b/.github/workflows/interop.yml index f2520b9638f..676469e81a6 100644 --- a/.github/workflows/interop.yml +++ b/.github/workflows/interop.yml @@ -15,6 +15,8 @@ on: pull_request: paths: - "test/lib/**" + - "test/p2p/**" + - "js/p2p/**" - "test/interop/**" - "test/max-age/**" - "test/portrait/**" @@ -102,6 +104,11 @@ jobs: run: nix develop --command just test bare-fin shell: bash -leo pipefail {0} + - name: P2P data-channel transport + if: ${{ !cancelled() && steps.setup.outcome == 'success' }} + run: nix develop --command just test p2p + shell: bash -leo pipefail {0} + - name: Interop (full matrix) if: ${{ !cancelled() && steps.setup.outcome == 'success' }} run: nix develop --command just test interop --all diff --git a/bun.lock b/bun.lock index 1bf3578f65c..a458d7ba417 100644 --- a/bun.lock +++ b/bun.lock @@ -228,6 +228,19 @@ "zod": "^4.5.0", }, }, + "js/p2p": { + "name": "@moq/p2p", + "version": "0.1.0", + "dependencies": { + "@moq/qmux": "^0.3.3", + }, + "devDependencies": { + "@types/bun": "^1.4.2", + "@typescript/lib-dom": "npm:@types/web@^0.0.350", + "rimraf": "^6.1.3", + "typescript": "7.0.2", + }, + }, "js/pattern": { "name": "@moq/pattern", "version": "0.2.1", @@ -389,6 +402,20 @@ "tsx": "^4.23.15", }, }, + "test/p2p": { + "name": "@moq/p2p-test", + "dependencies": { + "@moq/net": "workspace:*", + "@moq/p2p": "workspace:*", + }, + "devDependencies": { + "@types/bun": "^1.4.2", + "@typescript/lib-dom": "npm:@types/web@^0.0.350", + "playwright": "^1.63.0", + "typescript": "7.0.2", + "vite": "^8.3.2", + }, + }, "test/video": { "name": "@moq/video-test", "dependencies": { @@ -697,6 +724,10 @@ "@moq/net": ["@moq/net@workspace:js/net"], + "@moq/p2p": ["@moq/p2p@workspace:js/p2p"], + + "@moq/p2p-test": ["@moq/p2p-test@workspace:test/p2p"], + "@moq/pattern": ["@moq/pattern@workspace:js/pattern"], "@moq/publish": ["@moq/publish@workspace:js/publish"], diff --git a/demo/web/src/index.ts b/demo/web/src/index.ts index 3dbb76a88e8..f1b6d27712f 100644 --- a/demo/web/src/index.ts +++ b/demo/web/src/index.ts @@ -381,7 +381,9 @@ ui.run((effect) => { // Report the transport negotiated by the live connection. const transport = effect.get(connection.transport); - $("network-transport").textContent = transport ? (transport === "websocket" ? "WebSocket" : "WebTransport") : ""; + $("network-transport").textContent = transport + ? { websocket: "WebSocket", webtransport: "WebTransport", webrtc: "WebRTC" }[transport] + : ""; const video = effect.get(watch.video.out.stats); const audio = effect.get(watch.audio.out.stats); diff --git a/demo/web/src/publish.ts b/demo/web/src/publish.ts index c55cd7d1f66..c4a172fec9d 100644 --- a/demo/web/src/publish.ts +++ b/demo/web/src/publish.ts @@ -361,7 +361,9 @@ ui.run((effect) => { // Report the transport negotiated by the live connection. ui.run((effect) => { const transport = effect.get(publish.connection.transport); - $("network-transport").textContent = transport ? (transport === "websocket" ? "WebSocket" : "WebTransport") : ""; + $("network-transport").textContent = transport + ? { websocket: "WebSocket", webtransport: "WebTransport", webrtc: "WebRTC" }[transport] + : ""; }); // Audio: the resolved audio config (codec / sample rate / channels / bitrate). diff --git a/doc/concept/transport.md b/doc/concept/transport.md index a0ff1a7067c..e6e35580899 100644 --- a/doc/concept/transport.md +++ b/doc/concept/transport.md @@ -1,6 +1,6 @@ --- title: Transport -description: QUIC, WebTransport, the WebSocket fallback, raw QUIC, stream listeners, and iroh +description: QUIC, WebTransport, the WebSocket fallback, raw QUIC, stream listeners, WebRTC data channels, and iroh --- # Transport @@ -62,6 +62,15 @@ authenticate through the same JWT and public-access rules as QUIC, and the Unix socket can additionally allowlist the connecting process by uid, gid, or pid. See [stream listeners](/bin/relay/auth#stream-listeners). +## WebRTC data channels (experimental) + +Applications that already negotiate a browser `RTCPeerConnection` can pass an +[`@moq/p2p` transport](https://github.com/moq-dev/moq/tree/main/js/p2p) to +`@moq/net`'s connect or accept. One reliable ordered data channel carries qmux +records, with no datagrams. The application supplies signaling and ICE and +keeps ownership of the peer connection; closing the transport closes only its +channel. SCTP ordering means one lost packet can hold back every stream. + ## iroh (peer-to-peer, experimental) [iroh](https://www.iroh.computer/) swaps "dial a hostname" for "dial a public diff --git a/drafts/draft-lcurley-moq-lite.md b/drafts/draft-lcurley-moq-lite.md index 1c43d57a6cc..2c34de524f9 100644 --- a/drafts/draft-lcurley-moq-lite.md +++ b/drafts/draft-lcurley-moq-lite.md @@ -29,6 +29,7 @@ normative: date: false RFC3986: RFC6455: + RFC8831: RFC9000: RFC9002: RFC9562: @@ -93,7 +94,6 @@ The moq-lite layer provides fanout, prioritization, and caching even for latency ## Session A Session consists of a connection between a client and a server. -There is currently no P2P support within QUIC so it's out of scope for moq-lite. The moq-lite version identifier is `moq-lite-xx` where `xx` is the two-digit draft version. The identifier for this draft is `moq-lite-07-wip` while it is a work in progress, and becomes `moq-lite-07` once finalized. @@ -218,8 +218,8 @@ See [Transports](#transports) for the bindings. How the underlying connection is authenticated is out-of-scope for this draft. ## Transports {#transports} -moq-lite defines four transport bindings. -All four carry the same control and data streams defined elsewhere in this document; they differ only in how QUIC streams are multiplexed onto the underlying connection. +moq-lite defines five transport bindings. +All five carry the same control and data streams defined elsewhere in this document; they differ only in how QUIC streams are multiplexed onto the underlying connection. |----|---------------------|------------------|----------------------| | | Transport | ALPN / Identifier | Record framing | @@ -228,15 +228,23 @@ All four carry the same control and data streams defined elsewhere in this docum | 2 | WebTransport / H3 | `moq-lite-xx` (CONNECT header) | Native WebTransport streams | | 3 | Qmux over TCP/TLS | `moq-lite-xx` (ALPN over TLS) | Qmux Record [qmux] | | 4 | Qmux over WebSocket | `moq-lite-xx` (Sec-WebSocket-Protocol) | WebSocket message [qmuxws] | +| 5 | Qmux over RTCDataChannel | `moq-lite-xx` (signaling and DataChannel protocol) | DataChannel message | For bindings 1 and 2, moq-lite uses the underlying QUIC/WebTransport stream APIs directly. -QUIC datagrams (see [Datagrams](#datagrams)) are supported by bindings 1 and 2 only; a publisher MUST NOT emit datagrams on bindings 3 and 4. +QUIC datagrams (see [Datagrams](#datagrams)) are supported by bindings 1 and 2 only; a publisher MUST NOT emit datagrams on bindings 3, 4, and 5. For binding 3, a client opens a TCP connection, performs a TLS handshake, and negotiates the moq-lite version as the ALPN token. Each direction of the TLS byte stream then carries Qmux Records as defined in [qmux]. For binding 4, a client opens a WebSocket connection [RFC6455] offering the moq-lite version as the subprotocol, per [qmuxws]: each WebSocket binary message carries one Qmux Record's `Frames` payload, with the message boundary replacing the Record `Size` field. +For binding 5, WebRTC Data Channels [RFC8831] carry Qmux. Signaling agrees the moq-lite version before establishing the peer connection. +The client creates one reliable, ordered RTCDataChannel with that version as its protocol; the server MUST refuse a channel whose protocol differs or whose delivery is unordered or partially reliable. +The binding uses Qmux draft-01: each binary DataChannel message carries one Record's `Frames` payload, with the message boundary replacing the Record `Size` field. +The record limit defaults to 16 KiB and MUST NOT exceed the negotiated SCTP `maxMessageSize`; an endpoint MUST refuse a message limit below Qmux's minimum record size. +A sender splits stream payloads at frame boundaries to fit this limit, never within a frame. +Signaling, peer admission, and ICE server selection are application concerns. + All other moq-lite semantics (stream types, message encoding, flow control, etc.) are identical across bindings. ## Termination @@ -1561,6 +1569,8 @@ The `Message Length` describes the payload size on the wire. ## moq-lite-07 +- Added the reliable ordered RTCDataChannel binding, with one Qmux Record per binary message and no datagrams. + - Added `Group Order` to SUBSCRIBE and SUBSCRIBE_UPDATE: descending (0x0, the previous fixed order) or ascending (0x1). A relay requests descending upstream unless every subscription it serves is ascending. - Listed the shared INVALID_REQUEST_ID (0x4) session code used by moq-transport drafts 14 through 16. @@ -1762,7 +1772,7 @@ Some of these fields occur in multiple messages. # Security Considerations -moq-lite inherits the transport security of the underlying connection: QUIC and WebTransport provide confidentiality and integrity via TLS 1.3, and the Qmux bindings run over TLS (TCP) or a `wss://` WebSocket. How that connection is authenticated is out of scope (see [Connection](#connection)). The considerations below are specific to moq-lite. +moq-lite inherits the transport security of the underlying connection: QUIC and WebTransport provide confidentiality and integrity via TLS 1.3, the Qmux TCP and WebSocket bindings run over TLS, and the RTCDataChannel binding inherits DTLS security. How that connection is authenticated is out of scope (see [Connection](#connection)). The considerations below are specific to moq-lite. ## Bandwidth Probing The `Increase` Probe level (see [Probe Parameter](#probe-parameter)) lets a subscriber ask the publisher to pad the connection up to a target bitrate. A publisher MUST NOT treat the target as authorization to send beyond what congestion control allows: padding is bounded by the congestion window, so probing cannot be used to amplify traffic toward the subscriber or a spoofed address. A publisher that only advertised `Report` MUST NOT pad above its current sending rate. Because all data flows on an established, congestion-controlled session to the connecting peer, moq-lite offers no off-path amplification vector. diff --git a/js/justfile b/js/justfile index 4fad3263e37..0e1ea37e3ba 100644 --- a/js/justfile +++ b/js/justfile @@ -106,3 +106,8 @@ clock-bench: audio-warmup-bench: bun install --frozen-lockfile bun watch/bench/warmup.ts + +# Sweep data-channel qmux stream count and payload size. +p2p-bench: + bun install --frozen-lockfile + bun p2p/bench/transport.ts diff --git a/js/net/src/connection/goaway.ts b/js/net/src/connection/goaway.ts index a304e458383..e6640ac216b 100644 --- a/js/net/src/connection/goaway.ts +++ b/js/net/src/connection/goaway.ts @@ -6,6 +6,7 @@ */ import { RefusedRedirect } from "../error.ts"; import * as Time from "../time.ts"; +import type { Transport } from "./transport.ts"; /** A peer's GOAWAY as a session received it. */ export interface Drain { @@ -60,7 +61,7 @@ export function handover(cap: Time.Milli, timeout?: Time.Milli): Time.Milli { * * @internal */ -export function dialed(primary: URL, transport: "webtransport" | "websocket", websocket?: URL): URL { +export function dialed(primary: URL, transport: Transport, websocket?: URL): URL { return transport === "websocket" && websocket ? websocket : primary; } @@ -70,7 +71,7 @@ export function dialed(primary: URL, transport: "webtransport" | "websocket", we * * @internal */ -export function pinnedTransport(transport: "webtransport" | "websocket", configured: boolean): boolean { +export function pinnedTransport(transport: Transport, configured: boolean): boolean { return configured && transport === "webtransport"; } diff --git a/js/net/src/connection/transport.ts b/js/net/src/connection/transport.ts index af6c3ff1274..774e287da04 100644 --- a/js/net/src/connection/transport.ts +++ b/js/net/src/connection/transport.ts @@ -1,14 +1,15 @@ import Session from "@moq/qmux"; /** The wire transport a session runs over. */ -export type Transport = "webtransport" | "websocket"; +export type Transport = "webtransport" | "websocket" | "webrtc"; /** - * The transport a live session is actually running over. qmux implements the `WebTransport` - * interface on top of a WebSocket, so the two are indistinguishable by shape. + * The transport a live session is actually running over. WebSocket and WebRTC adapters + * share the WebTransport shape; WebRTC carries its label to avoid a dependency cycle. * * @internal Not re-exported from the package entrypoint. */ export function transportOf(quic: WebTransport): Transport { + if ("transport" in quic && quic.transport === "webrtc") return "webrtc"; return quic instanceof Session ? "websocket" : "webtransport"; } diff --git a/js/net/src/index.ts b/js/net/src/index.ts index 380378b9c41..574799966af 100644 --- a/js/net/src/index.ts +++ b/js/net/src/index.ts @@ -1,6 +1,6 @@ /** * MoQ networking layer for browsers: connect to a relay, then publish and consume - * broadcasts, tracks, groups, and frames over WebTransport (or a WebSocket fallback). + * broadcasts, tracks, groups, and frames over WebTransport, its WebSocket fallback, or a supplied transport. * * @module */ diff --git a/js/p2p/README.md b/js/p2p/README.md new file mode 100644 index 00000000000..36d258cd4e1 --- /dev/null +++ b/js/p2p/README.md @@ -0,0 +1,29 @@ +# @moq/p2p + +A WebTransport-shaped MoQ transport over one reliable ordered WebRTC data channel. +Applications own signaling, ICE configuration, admission, and the `RTCPeerConnection`. +The transport owns its data channel. Closing it leaves the peer connection open. + +```ts +import { Transport } from "@moq/p2p"; +import { Connection } from "@moq/net"; + +// The application agrees this ALPN with its peer through signaling. +const protocol = "moq-lite-07-wip"; +const transport = Transport.connect({ peer, protocol }); +const connection = await Connection.connect({ url, transport }); +``` + +The receiver adopts the incoming channel with +`Transport.accept({ peer, channel, protocol })` and passes that transport to +`Connection.accept({ url, transport })`. The channel's protocol must match the +agreed ALPN. Unordered or partially reliable channels are refused. + +Each binary data-channel message carries one qmux-01 record without its size +field. Records are capped at 16 KiB and the negotiated SCTP message limit; +a limit below qmux-01's 16,382-byte minimum is refused. There are no datagrams. +SCTP preserves ordering, so packet loss can hold back every stream. + +`just test p2p` runs SETUP and a media transfer between two real peer connections +in Chromium. `just js p2p-bench` sweeps stream counts and payload sizes through +an in-memory data-channel pair. diff --git a/js/p2p/bench/transport.ts b/js/p2p/bench/transport.ts new file mode 100644 index 00000000000..433c0a7732d --- /dev/null +++ b/js/p2p/bench/transport.ts @@ -0,0 +1,57 @@ +/** Sweep concurrent streams and bytes per stream through the real qmux adapter. @module */ +import { peers } from "../src/mock.ts"; +import { Transport } from "../src/transport.ts"; + +async function receive(stream: ReadableStream) { + const reader = stream.getReader(); + let bytes = 0; + try { + for (;;) { + const { value, done } = await reader.read(); + if (done) return bytes; + bytes += value.byteLength; + } + } finally { + reader.releaseLock(); + } +} + +async function measure(streams: number, bytes: number) { + const { left, right } = peers(); + const protocol = "moq-lite-07-wip"; + const client = Transport.connect({ peer: left.asPeer(), protocol }); + const server = Transport.accept({ peer: right.asPeer(), channel: right.incoming.asChannel(), protocol }); + left.channel.open(); + right.incoming.open(); + await Promise.all([client.ready, server.ready]); + const reader = server.incomingUnidirectionalStreams.getReader(); + const receiving = (async () => { + const pending: Promise[] = []; + for (let i = 0; i < streams; i++) { + const { value, done } = await reader.read(); + if (done) throw new Error("missing benchmark stream"); + pending.push(receive(value)); + } + return (await Promise.all(pending)).reduce((total, value) => total + value, 0); + })(); + const payload = new Uint8Array(bytes); + const start = performance.now(); + await Promise.all( + Array.from({ length: streams }, async () => { + const writer = (await client.createUnidirectionalStream()).getWriter(); + await writer.write(payload); + await writer.close(); + }), + ); + const delivered = await receiving; + const elapsed = performance.now() - start; + if (delivered !== streams * bytes || left.channel.records.some((record) => record.byteLength > 16384)) + throw new Error("benchmark delivery changed"); + console.log(`${streams},${bytes},${left.channel.records.length},${elapsed.toFixed(3)}`); + reader.releaseLock(); + client.close(); + await server.closed; +} + +console.log("streams,bytes_per_stream,records,elapsed_ms"); +for (const streams of [1, 8, 64]) for (const bytes of [1024, 16384, 262144]) await measure(streams, bytes); diff --git a/js/p2p/bench/tsconfig.json b/js/p2p/bench/tsconfig.json new file mode 100644 index 00000000000..172517b5a4c --- /dev/null +++ b/js/p2p/bench/tsconfig.json @@ -0,0 +1 @@ +{ "extends": "../tsconfig.json", "compilerOptions": { "rootDir": "..", "noEmit": true }, "include": ["transport.ts"] } diff --git a/js/p2p/package.json b/js/p2p/package.json new file mode 100644 index 00000000000..735fb7cca79 --- /dev/null +++ b/js/p2p/package.json @@ -0,0 +1,31 @@ +{ + "name": "@moq/p2p", + "type": "module", + "version": "0.1.0", + "description": "Media over QUIC transports over reliable WebRTC data channels.", + "license": "(MIT OR Apache-2.0)", + "repository": { + "type": "git", + "url": "git+https://github.com/moq-dev/moq.git", + "directory": "js/p2p" + }, + "sideEffects": false, + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "build": "rimraf dist && tsc -b tsconfig.build.json && bun ../common/package.ts", + "check": "tsc --noEmit && tsc --noEmit --project bench/tsconfig.json", + "test": "bun test --only-failures", + "release": "bun ../common/release.ts" + }, + "dependencies": { + "@moq/qmux": "^0.3.3" + }, + "devDependencies": { + "@types/bun": "^1.4.2", + "@typescript/lib-dom": "npm:@types/web@^0.0.350", + "rimraf": "^6.1.3", + "typescript": "7.0.2" + } +} diff --git a/js/p2p/src/channel.ts b/js/p2p/src/channel.ts new file mode 100644 index 00000000000..ea4d03d933d --- /dev/null +++ b/js/p2p/src/channel.ts @@ -0,0 +1,157 @@ +const RECORD_SIZE = 16 * 1024; +// Qmux-01 does not permit a smaller advertised record limit. +const MIN_RECORD_SIZE = 16382; +const SEND_WINDOW = RECORD_SIZE * 4; + +/** The WebSocketStream shape qmux consumes, backed by one owned data channel. */ +export class Channel { + readonly url = "webrtc://data-channel"; + readonly opened; + readonly closed; + maxRecordSize = RECORD_SIZE; + #open = Promise.withResolvers<{ + readable: ReadableStream; + writable: WritableStream; + extensions: string; + protocol: string; + }>(); + #closed = Promise.withResolvers<{ closeCode: number; reason: string }>(); + #drain?: ReturnType>; + #reader?: ReadableStreamDefaultController; + #ended = false; + #readable: ReadableStream; + #writable: WritableStream; + + private peer: RTCPeerConnection; + private channel: RTCDataChannel; + private protocol: string; + + constructor(peer: RTCPeerConnection, channel: RTCDataChannel, protocol: string) { + this.peer = peer; + this.channel = channel; + this.protocol = protocol; + this.opened = this.#open.promise; + this.closed = this.#closed.promise; + void this.opened.catch(() => {}); + void this.closed.catch(() => {}); + channel.binaryType = "arraybuffer"; + channel.bufferedAmountLowThreshold = SEND_WINDOW / 2; + this.#readable = new ReadableStream( + { + start: (controller) => { + this.#reader = controller; + }, + cancel: () => { + this.#reader = undefined; + this.close(); + }, + }, + new ByteLengthQueuingStrategy({ highWaterMark: SEND_WINDOW }), + ); + // An in-flight write retains the queue slot until the browser's send buffer + // falls below its low threshold, so writer.ready follows actual backpressure. + this.#writable = new WritableStream( + { + write: (data) => + this.#write(data).catch((error) => { + this.#finish(error); + throw error; + }), + close: () => this.close(), + abort: (reason) => this.#finish(reason instanceof Error ? reason : new Error(String(reason))), + }, + { highWaterMark: 1 }, + ); + channel.addEventListener("open", this.#onOpen); + channel.addEventListener("message", this.#onMessage); + channel.addEventListener("bufferedamountlow", this.#onDrain); + channel.addEventListener("close", this.#onClose); + channel.addEventListener("error", this.#onError); + if (channel.readyState === "open") this.#onOpen(); + else if (channel.readyState !== "connecting") this.#finish(new Error("data channel is already closing")); + } + + #onOpen = () => { + if (this.#ended) return; + // WebRTC reports an unbounded negotiated message size as positive Infinity. + const max = this.peer.sctp?.maxMessageSize; + if (max === undefined || Number.isNaN(max) || max < 0) { + this.#finish(new Error("data channel has no negotiated SCTP message limit")); + return; + } + this.maxRecordSize = Math.min(RECORD_SIZE, max); + if (this.maxRecordSize < MIN_RECORD_SIZE) { + this.#finish(new Error(`SCTP message limit ${max} is smaller than qmux's minimum ${MIN_RECORD_SIZE}`)); + return; + } + this.#open.resolve({ + readable: this.#readable, + writable: this.#writable, + extensions: "", + protocol: `qmux-01.${this.protocol}`, + }); + }; + + #onMessage = (event: MessageEvent) => { + if (this.#ended) return; + if (!(event.data instanceof ArrayBuffer)) { + this.#finish(new Error("qmux requires binary data-channel messages")); + return; + } + if (event.data.byteLength > this.maxRecordSize || (this.#reader?.desiredSize ?? 0) < event.data.byteLength) { + this.#finish(new Error("data-channel receive record exceeds its bounded queue")); + return; + } + this.#reader?.enqueue(new Uint8Array(event.data)); + }; + #onDrain = () => { + this.#drain?.resolve(); + this.#drain = undefined; + }; + #onClose = () => this.#finish(); + #onError = (event: Event) => + this.#finish("error" in event && event.error instanceof Error ? event.error : new Error("data channel failed")); + + async #wait() { + if (this.#ended || this.channel.readyState !== "open") throw new Error("data channel is closed"); + if (this.channel.bufferedAmount <= this.channel.bufferedAmountLowThreshold) return; + this.#drain ??= Promise.withResolvers(); + await this.#drain.promise; + } + + async #write(data: Uint8Array | string) { + await this.opened; + if (typeof data === "string") throw new TypeError("qmux requires binary records"); + if (data.byteLength > this.maxRecordSize) throw new RangeError("qmux record exceeds the SCTP message limit"); + await this.#wait(); + this.channel.send(data.buffer instanceof ArrayBuffer ? (data as Uint8Array) : data.slice()); + await this.#wait(); + } + + #finish(error?: Error) { + if (this.#ended) return; + this.#ended = true; + const closed = error ?? new Error("data channel is closed"); + this.#open.reject(closed); + this.#drain?.reject(closed); + this.#drain = undefined; + if (error) { + this.#reader?.error(error); + this.#closed.reject(error); + } else { + this.#reader?.close(); + this.#closed.resolve({ closeCode: 1000, reason: "" }); + } + this.#reader = undefined; + this.channel.removeEventListener("open", this.#onOpen); + this.channel.removeEventListener("message", this.#onMessage); + this.channel.removeEventListener("bufferedamountlow", this.#onDrain); + this.channel.removeEventListener("close", this.#onClose); + this.channel.removeEventListener("error", this.#onError); + this.channel.close(); + } + + close() { + this.#finish(); + } +} diff --git a/js/p2p/src/index.ts b/js/p2p/src/index.ts new file mode 100644 index 00000000000..1a23a3b790b --- /dev/null +++ b/js/p2p/src/index.ts @@ -0,0 +1,2 @@ +/** WebTransport-shaped transports over reliable ordered WebRTC data channels. @module */ +export { type AcceptProps, type ConnectProps, Transport } from "./transport.ts"; diff --git a/js/p2p/src/mock.ts b/js/p2p/src/mock.ts new file mode 100644 index 00000000000..c45aeaed980 --- /dev/null +++ b/js/p2p/src/mock.ts @@ -0,0 +1,110 @@ +export class MockChannel extends EventTarget { + binaryType = "blob"; + bufferedAmount = 0; + bufferedAmountLowThreshold = 0; + readyState: RTCDataChannelState = "connecting"; + ordered = true; + maxRetransmits: number | null = null; + maxPacketLifeTime: number | null = null; + protocol: string; + partner!: MockChannel; + autoDrain = true; + records: Uint8Array[] = []; + listeners = new Set(); + constructor(protocol: string) { + super(); + this.protocol = protocol; + } + override addEventListener( + type: string, + callback: EventListenerOrEventListenerObject | null, + options?: AddEventListenerOptions | boolean, + ) { + if (callback) this.listeners.add(callback); + super.addEventListener(type, callback, options); + } + override removeEventListener( + type: string, + callback: EventListenerOrEventListenerObject | null, + options?: EventListenerOptions | boolean, + ) { + if (callback) this.listeners.delete(callback); + super.removeEventListener(type, callback, options); + } + open() { + this.readyState = "open"; + this.dispatchEvent(new Event("open")); + } + send(data: Uint8Array) { + if (this.readyState !== "open") throw new Error("send on closed channel"); + const record = data.slice(); + this.records.push(record); + this.bufferedAmount += record.byteLength; + queueMicrotask(() => { + if (this.partner.readyState === "open") + this.partner.dispatchEvent(new MessageEvent("message", { data: record.buffer })); + if (this.autoDrain) this.drain(); + }); + } + drain() { + this.bufferedAmount = 0; + this.dispatchEvent(new Event("bufferedamountlow")); + } + close() { + if (this.readyState === "closed") return; + this.readyState = "closed"; + queueMicrotask(() => { + this.dispatchEvent(new Event("close")); + if (this.partner.readyState !== "closed") { + this.partner.readyState = "closed"; + this.partner.dispatchEvent(new Event("close")); + } + }); + } + asChannel(): RTCDataChannel { + return this as unknown as RTCDataChannel; + } +} + +export class MockPeer { + sctp = { maxMessageSize: 65536 }; + #channel?: MockChannel; + #incoming?: MockChannel; + partner!: MockPeer; + closed = false; + options?: RTCDataChannelInit; + createDataChannel(_label: string, options: RTCDataChannelInit) { + this.options = options; + const channel = new MockChannel(options.protocol ?? ""); + const incoming = new MockChannel(options.protocol ?? ""); + channel.partner = incoming; + incoming.partner = channel; + this.#channel = channel; + this.partner.#incoming = incoming; + return channel.asChannel(); + } + get channel() { + if (!this.#channel) throw new Error("mock peer has no outgoing channel"); + return this.#channel; + } + get incoming() { + if (!this.#incoming) throw new Error("mock peer has no incoming channel"); + return this.#incoming; + } + + close() { + this.closed = true; + } + asPeer(): RTCPeerConnection { + return this as unknown as RTCPeerConnection; + } +} + +export function peers(maxMessageSize = 65536) { + const left = new MockPeer(); + const right = new MockPeer(); + left.partner = right; + right.partner = left; + left.sctp.maxMessageSize = right.sctp.maxMessageSize = maxMessageSize; + return { left, right }; +} diff --git a/js/p2p/src/transport.test.ts b/js/p2p/src/transport.test.ts new file mode 100644 index 00000000000..5dc2e96b831 --- /dev/null +++ b/js/p2p/src/transport.test.ts @@ -0,0 +1,177 @@ +import { expect, test } from "bun:test"; +import { Channel } from "./channel.ts"; +import { peers } from "./mock.ts"; +import { Transport } from "./transport.ts"; + +const protocol = "moq-lite-07-wip"; + +function pair(maxMessageSize = 65536) { + const mock = peers(maxMessageSize); + const left = Transport.connect({ peer: mock.left.asPeer(), protocol }); + const right = Transport.accept({ peer: mock.right.asPeer(), channel: mock.right.incoming.asChannel(), protocol }); + mock.left.channel.open(); + mock.right.incoming.open(); + return { ...mock, client: left, server: right }; +} + +async function next(stream: ReadableStream): Promise { + const reader = stream.getReader(); + try { + const { value, done } = await reader.read(); + if (done) throw new Error("stream ended before its item"); + return value; + } finally { + reader.releaseLock(); + } +} + +async function readAll(stream: ReadableStream): Promise { + const reader = stream.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + while (true) { + const { value, done } = await reader.read(); + if (done) break; + chunks.push(value); + size += value.byteLength; + } + const result = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + result.set(chunk, offset); + offset += chunk.byteLength; + } + return result; +} + +test("qmux carries large streams in bounded binary records and preserves both stream-id roles", async () => { + for (const max of [16382, 16384, 65536, Infinity]) { + const { client, server, left, right } = pair(max); + await Promise.all([client.ready, server.ready]); + expect(left.options).toEqual({ ordered: true, protocol }); + expect(left.channel.binaryType).toBe("arraybuffer"); + expect(client.protocol).toBe(protocol); + expect(server.protocol).toBe(protocol); + expect(client.datagrams.maxDatagramSize).toBe(0); + const payload = Uint8Array.from({ length: 256 * 1024 }, (_, i) => i % 251); + const receiving = next(server.incomingUnidirectionalStreams).then(readAll); + const writer = (await client.createUnidirectionalStream()).getWriter(); + await writer.write(payload); + await writer.close(); + expect(await receiving).toEqual(payload); + const bidiIncoming = next(client.incomingBidirectionalStreams); + const bidi = await server.createBidirectionalStream(); + const response = bidi.writable.getWriter(); + await response.write(new Uint8Array([4, 2])); + await response.close(); + expect(await readAll((await bidiIncoming).readable)).toEqual(new Uint8Array([4, 2])); + expect(left.channel.records.every((record) => record.byteLength <= Math.min(16384, max))).toBe(true); + client.close({ closeCode: 42, reason: "bye" }); + expect(await server.closed).toEqual({ closeCode: 42, reason: "bye" }); + await client.closed; + expect(left.closed).toBe(false); + expect(right.closed).toBe(false); + expect(left.channel.listeners.size).toBe(0); + expect(right.incoming.listeners.size).toBe(0); + } +}); + +test("close before the channel opens settles closed and rejects ready without closing the peer", async () => { + const { left } = peers(); + const transport = Transport.connect({ peer: left.asPeer(), protocol }); + transport.close({ closeCode: 7, reason: "cancelled" }); + expect(await transport.closed).toEqual({ closeCode: 7, reason: "cancelled" }); + await expect(transport.ready).rejects.toThrow("closed"); + expect(left.channel.readyState).toBe("closed"); + expect(left.closed).toBe(false); + expect(left.channel.listeners.size).toBe(0); +}); + +test("accept refuses partial reliability, unordered delivery, and a different negotiated protocol", () => { + for (const change of [ + { ordered: false }, + { maxRetransmits: 1 }, + { maxPacketLifeTime: 10 }, + { protocol: "other" }, + ]) { + const { left, right } = peers(); + left.createDataChannel("moq", { ordered: true, protocol }); + Object.assign(right.incoming, change); + expect(() => + Transport.accept({ peer: right.asPeer(), channel: right.incoming.asChannel(), protocol }), + ).toThrow(); + } + expect(() => Transport.connect({ peer: peers().left.asPeer(), protocol: "" })).toThrow("ALPN"); +}); + +test("an SCTP message limit below qmux's protocol minimum is refused", async () => { + const { client, server, left } = pair(8192); + await expect(client.ready).rejects.toThrow("minimum"); + await expect(server.ready).rejects.toThrow(); + await expect(client.closed).rejects.toThrow("minimum"); + expect(left.channel.listeners.size).toBe(0); +}); + +test("writer.ready follows bufferedamountlow and closing releases a blocked write", async () => { + const { left } = peers(); + const channel = left.createDataChannel("moq", { ordered: true, protocol }); + left.channel.autoDrain = false; + const socket = new Channel(left.asPeer(), channel, protocol); + left.channel.open(); + const { writable } = await socket.opened; + const writer = writable.getWriter(); + const record = new Uint8Array(16384); + await writer.write(record); + await writer.write(record); + const pending = writer.write(record); + let sent = false; + void pending.then( + () => { + sent = true; + }, + () => {}, + ); + await Promise.resolve(); + await Promise.resolve(); + expect(writer.desiredSize).toBe(0); + expect(sent).toBe(false); + left.channel.drain(); + await pending; + expect(sent).toBe(true); + await writer.write(record); + await writer.write(record); + const blocked = writer.write(record); + await Promise.resolve(); + socket.close(); + await expect(blocked).rejects.toThrow("closed"); + expect(left.channel.listeners.size).toBe(0); +}); + +test("malformed binary input and an overflowing receive queue close the channel", async () => { + for (const data of ["text", new ArrayBuffer(16385), new ArrayBuffer(16384)]) { + const { left } = peers(); + const channel = left.createDataChannel("moq", { ordered: true, protocol }); + const socket = new Channel(left.asPeer(), channel, protocol); + left.channel.open(); + await socket.opened; + if (data instanceof ArrayBuffer && data.byteLength === 16384) { + for (let i = 0; i < 4; i++) left.channel.dispatchEvent(new MessageEvent("message", { data })); + } + left.channel.dispatchEvent(new MessageEvent("message", { data })); + await expect(socket.closed).rejects.toThrow(); + expect(left.channel.listeners.size).toBe(0); + } +}); + +test("incoming stream cancellation waits for the channel to open", async () => { + const mock = peers(); + const client = Transport.connect({ peer: mock.left.asPeer(), protocol }); + const server = Transport.accept({ peer: mock.right.asPeer(), channel: mock.right.incoming.asChannel(), protocol }); + const cancelled = client.incomingUnidirectionalStreams.cancel(); + mock.left.channel.open(); + mock.right.incoming.open(); + await cancelled; + await Promise.all([client.ready, server.ready]); + client.close(); + await Promise.all([client.closed, server.closed]); +}); diff --git a/js/p2p/src/transport.ts b/js/p2p/src/transport.ts new file mode 100644 index 00000000000..6113bdc559f --- /dev/null +++ b/js/p2p/src/transport.ts @@ -0,0 +1,161 @@ +import Session from "@moq/qmux"; +import { Channel } from "./channel.ts"; + +/** The peer connection and the MoQ ALPN agreed through signaling. */ +export interface ConnectProps { + /** The caller-owned peer connection. */ + peer: RTCPeerConnection; + /** The negotiated MoQ ALPN, such as moq-lite-07-wip. */ + protocol: string; +} + +/** An incoming data channel and its agreed MoQ protocol. */ +export interface AcceptProps extends ConnectProps { + /** The reliable ordered data channel whose ownership transfers to the transport. */ + channel: RTCDataChannel; +} + +function incoming(stream: Promise>): ReadableStream { + const opened = stream.then((stream) => stream.getReader()); + return new ReadableStream({ + async start() { + await opened; + }, + async pull(controller) { + const reader = await opened; + const { value, done } = await reader.read(); + if (done) { + reader.releaseLock(); + controller.close(); + } else controller.enqueue(value); + }, + async cancel(reason) { + const reader = await opened; + await reader.cancel(reason); + reader.releaseLock(); + }, + }); +} + +/** A WebTransport-shaped handle owning one reliable ordered data channel. */ +export class Transport implements WebTransport { + /** The transport label used by MoQ connection statistics. */ + readonly transport = "webrtc"; + /** The MoQ ALPN agreed through signaling. */ + readonly protocol: string; + /** Resolves once the channel and qmux session are ready. */ + readonly ready: Promise; + /** Resolves on an application close or rejects on transport failure. */ + readonly closed: Promise; + /** The connection uses reliable delivery only. */ + readonly reliability = "reliable-only"; + /** SCTP controls congestion for the connection. */ + readonly congestionControl = "default"; + /** Incoming bidirectional qmux streams. */ + readonly incomingBidirectionalStreams: ReadableStream; + /** Incoming unidirectional qmux streams. */ + readonly incomingUnidirectionalStreams: ReadableStream>; + /** Datagram-shaped streams with a zero send limit, since this binding has no datagrams. */ + readonly datagrams: WebTransportDatagramDuplexStream; + #session: Promise; + #active?: Session; + #socket: Channel; + #closing = false; + #closed = Promise.withResolvers(); + + private constructor({ peer, channel, protocol }: AcceptProps, server: boolean) { + if (!protocol || /\s/.test(protocol)) throw new TypeError("a negotiated MoQ ALPN is required"); + if (!channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) { + throw new TypeError("qmux requires a reliable ordered data channel"); + } + if (channel.protocol !== protocol) throw new TypeError("data-channel protocol does not match the agreed ALPN"); + this.protocol = protocol; + this.#socket = new Channel(peer, channel, protocol); + this.closed = this.#closed.promise; + // SCTP's negotiated limit is known only after the data channel opens. + this.#session = this.#socket.opened.then(() => { + if (this.#closing) throw new Error("transport closed before opening"); + const config = { maxRecordSize: BigInt(this.#socket.maxRecordSize), maxDatagramFrameSize: 0n }; + const session = server + ? Session.accept(this.#socket, { config, protocol: `qmux-01.${protocol}` }) + : new Session(this.#socket, { config }); + this.#active = session; + void session.closed.then(this.#closed.resolve, this.#closed.reject); + return session; + }); + this.ready = this.#session.then((session) => session.ready); + void this.ready.catch((error) => { + this.#closed.reject(error); + this.#socket.close(); + }); + void this.closed.catch(() => {}); + this.incomingBidirectionalStreams = incoming( + this.#session.then((session) => session.incomingBidirectionalStreams), + ); + this.incomingUnidirectionalStreams = incoming( + this.#session.then((session) => session.incomingUnidirectionalStreams), + ); + let writer: WritableStreamDefaultWriter; + this.datagrams = { + maxDatagramSize: 0, + incomingHighWaterMark: 1, + incomingMaxAge: null, + outgoingHighWaterMark: 1, + outgoingMaxAge: null, + readable: incoming(this.#session.then((session) => session.datagrams.readable)), + writable: new WritableStream({ + start: async () => { + writer = (await this.#session).datagrams.writable.getWriter(); + }, + write: (data) => writer.write(data), + close: () => writer.close(), + abort: (reason) => writer.abort(reason), + }), + }; + } + + /** Create a reliable ordered data channel, leaving the peer connection with its caller. */ + static connect({ peer, protocol }: ConnectProps): Transport { + if (!protocol || /\s/.test(protocol)) throw new TypeError("a negotiated MoQ ALPN is required"); + const channel = peer.createDataChannel("moq", { ordered: true, protocol }); + try { + return new Transport({ peer, channel, protocol }, false); + } catch (error) { + channel.close(); + throw error; + } + } + + /** Adopt an incoming reliable ordered data channel, leaving the peer connection with its caller. */ + static accept(props: AcceptProps): Transport { + return new Transport(props, true); + } + + /** Open a bidirectional qmux stream. */ + async createBidirectionalStream(options?: WebTransportSendStreamOptions): Promise { + return (await this.#session).createBidirectionalStream(options); + } + + /** Open a unidirectional qmux stream. */ + async createUnidirectionalStream(options?: WebTransportSendStreamOptions): Promise> { + return (await this.#session).createUnidirectionalStream(options); + } + + /** Close the qmux session and its data channel. */ + close(info: WebTransportCloseInfo = {}) { + if (this.#closing) return; + if (this.#active) { + this.#active.close(info); + this.#closing = true; + } else { + this.#closing = true; + this.#closed.resolve(info); + this.#socket.close(); + } + } + + /** Refuse HTTP/3 statistics, which this data-channel binding does not provide. */ + async getStats(): Promise { + throw new Error("WebTransport connection statistics are unavailable over WebRTC"); + } +} diff --git a/js/p2p/tsconfig.build.json b/js/p2p/tsconfig.build.json new file mode 100644 index 00000000000..2bd3a373587 --- /dev/null +++ b/js/p2p/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["src/**/*.test.ts", "src/mock.ts"] +} diff --git a/js/p2p/tsconfig.json b/js/p2p/tsconfig.json new file mode 100644 index 00000000000..d49d1326bbf --- /dev/null +++ b/js/p2p/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { "rootDir": "./src", "outDir": "dist", "types": ["bun"] }, + "include": ["src"] +} diff --git a/package.json b/package.json index 7f5668975df..078b408bb87 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "workspaces": [ "doc", "js/net", + "js/p2p", "js/clock", "js/pattern", "js/auth", @@ -48,6 +49,7 @@ "test/interop/clients/js-native", "test/drain", "test/video", + "test/p2p", "test/wasm" ] } diff --git a/quest/m1/p2p/README.md b/quest/m1/p2p/README.md index 9d858397b13..ef30d0ec1b4 100644 --- a/quest/m1/p2p/README.md +++ b/quest/m1/p2p/README.md @@ -139,7 +139,6 @@ Backend choice does not change the policy that watching tabs never re-serve. ## Required -- [Data channel transport](/quest/m1/p2p/transport.md) - `@moq/p2p` speaks qmux over one ordered RTCDataChannel behind the WebTransport shape `@moq/net` consumes - [Peer grants](/quest/m1/p2p/peer-grant.md) - the relay issues a node-bound, asymmetrically signed grant a browser can verify; HS256 keys issue none - [Signaling and policy](/quest/m1/p2p/signal.md) - opted-in peers find each other under the prefix, the application picks who to dial, and the roster-size gate decides whether STUN is used - [Native data channel transport](/quest/m1/p2p/webrtc.md) - `moq-tokio` holds a moq-net session with a browser over str0m with a full ICE agent diff --git a/quest/m1/p2p/signal.md b/quest/m1/p2p/signal.md index f65f875cf52..0aa5afab47b 100644 --- a/quest/m1/p2p/signal.md +++ b/quest/m1/p2p/signal.md @@ -96,5 +96,4 @@ there is no equal-scope shortcut. ## Required - [Routes](/quest/m1/cluster-routing/routes.md) - the ROUTE_START node id the roster keys on -- [Data channel transport](/quest/m1/p2p/transport.md) - [Peer grants](/quest/m1/p2p/peer-grant.md) - the node-bound, asymmetrically signed credential a direct session presents; HS256 keys issue none diff --git a/quest/m1/p2p/transport.md b/quest/m1/p2p/transport.md deleted file mode 100644 index 75019a006af..00000000000 --- a/quest/m1/p2p/transport.md +++ /dev/null @@ -1,42 +0,0 @@ -# [M] Data channel transport - -## Goal - -`@moq/p2p` exports a transport with the DOM `WebTransport` shape over an -`RTCPeerConnection` that `connect` and `accept` in `@moq/net` consume without -change: qmux over one reliable, ordered data channel, one record per message. -The moq-lite draft gains the binding. - -## Plan - -`@moq/qmux` and `MockTransport` are the models: the contract is the DOM -interface, and `transportOf` in `js/net` gains a `webrtc` arm so stats and -logs name it. The negotiated moq ALPN is handed to the transport by the -caller (signaling agrees it before the peer connection exists), because -`accept()` reads `transport.protocol` to pick the SETUP flavor. - -A small object with the `WebSocketStream` shape (`opened`, `closed`, `close`) -wraps the channel and is handed to the qmux `Session` with the protocol -override, so the WebSocket binding's code path is reused rather than -duplicated. The readable enqueues one `Uint8Array` per message with -`binaryType` set to `arraybuffer`; the writable calls `send` per record and -derives `desiredSize` from `bufferedAmount` against -`bufferedAmountLowThreshold`. `max_record_size` defaults to 16 KiB and is -clamped to the negotiated `maxMessageSize`; a record that would exceed it is -split at a frame boundary, never chunked mid-frame. The channel is always -created with `ordered: true` and no retransmit limit, with no option to -change it (decided 2026-10-08, when unordered qmux was dropped). - -Tests: framing, the record-size clamp, and backpressure run under `bun test` -against an in-memory channel pair; the real thing runs under the Playwright -driver in `test/p2p`, two peer connections in one page, completing SETUP -through `accept()` and `connect()`. - -Draft: `draft-lcurley-moq-lite.md` Transports gains a row for qmux over -RTCDataChannel (one record per message, no datagrams, like WebSocket), and -the sentence declaring P2P out of scope goes. `just drafts check` passes. - -## Related - -- [Signaling and policy](/quest/m1/p2p/signal.md) - supplies the peer connection and the agreed ALPN -- [Native data channel transport](/quest/m1/p2p/webrtc.md) - the same binding in Rust diff --git a/quest/m1/p2p/webrtc.md b/quest/m1/p2p/webrtc.md index e60c6e0f459..f4ab936f466 100644 --- a/quest/m1/p2p/webrtc.md +++ b/quest/m1/p2p/webrtc.md @@ -39,7 +39,6 @@ candidate is offered and selected. Browser interop is the harness's job. ## Related -- [Data channel transport](/quest/m1/p2p/transport.md) - the browser side of the same binding - [moq-cli joins](/quest/m1/p2p/cli.md) - the first consumer - [Relay STUN](/quest/m1/p2p/relay-stun.md) - a relay-side STUN responder this client can be pointed at - [Native pairs over ICE and QUIC](/quest/m1/p2p/native-quic.md) - reuses the ICE gathering module this lifts out of `moq-rtc` diff --git a/sh/gh/nightly.sh b/sh/gh/nightly.sh index dd245f38d7d..ae0d8325758 100755 --- a/sh/gh/nightly.sh +++ b/sh/gh/nightly.sh @@ -41,6 +41,7 @@ case "${1:-}" in done run just js catalog-bench run just js arrivals-bench + run just js p2p-bench run just js signals-bench ;; *) diff --git a/test/justfile b/test/justfile index d3d6056e18e..a17872a439f 100644 --- a/test/justfile +++ b/test/justfile @@ -186,3 +186,9 @@ bare-fin: # Explore JSON snapshot codec sequences with a fresh replayable seed. json-properties: bash json-properties.sh + +# Complete MoQ SETUP and transfer a frame over a real browser data-channel pair. +p2p: + cd .. && bun install --frozen-lockfile + cd p2p && bunx playwright install chromium + cd p2p && bun test ./transport.browser.ts diff --git a/test/p2p/index.html b/test/p2p/index.html new file mode 100644 index 00000000000..51f28a623eb --- /dev/null +++ b/test/p2p/index.html @@ -0,0 +1,2 @@ + +MoQ P2P transport test diff --git a/test/p2p/package.json b/test/p2p/package.json new file mode 100644 index 00000000000..ffbfd3e870f --- /dev/null +++ b/test/p2p/package.json @@ -0,0 +1,19 @@ +{ + "name": "@moq/p2p-test", + "private": true, + "type": "module", + "scripts": { + "check": "tsc --noEmit" + }, + "dependencies": { + "@moq/net": "workspace:*", + "@moq/p2p": "workspace:*" + }, + "devDependencies": { + "@types/bun": "^1.4.2", + "@typescript/lib-dom": "npm:@types/web@^0.0.350", + "playwright": "^1.63.0", + "typescript": "7.0.2", + "vite": "^8.3.2" + } +} diff --git a/test/p2p/src/main.ts b/test/p2p/src/main.ts new file mode 100644 index 00000000000..f83fe03e14a --- /dev/null +++ b/test/p2p/src/main.ts @@ -0,0 +1,120 @@ +import * as Moq from "@moq/net"; +import { Transport } from "@moq/p2p"; + +export interface Report { + client: string; + server: string; + version: string; + bytes: number; + peerStates: string[]; +} + +declare global { + interface Window { + checkTransport(): Promise; + } +} + +async function gathered(peer: RTCPeerConnection) { + if (peer.iceGatheringState === "complete") return; + await new Promise((resolve) => { + const changed = () => { + if (peer.iceGatheringState !== "complete") return; + peer.removeEventListener("icegatheringstatechange", changed); + resolve(); + }; + peer.addEventListener("icegatheringstatechange", changed); + changed(); + }); +} + +window.checkTransport = async () => { + const left = new RTCPeerConnection({ iceServers: [] }); + const right = new RTCPeerConnection({ iceServers: [] }); + const protocol = "moq-lite-07-wip"; + const transport = Transport.connect({ peer: left, protocol }); + const incoming = new Promise((resolve, reject) => { + right.addEventListener( + "datachannel", + ({ channel }) => { + try { + resolve(Transport.accept({ peer: right, channel, protocol })); + } catch (error) { + channel.close(); + reject(error); + } + }, + { once: true }, + ); + }); + const publishing = new Moq.Origin.Producer(); + const consuming = new Moq.Origin.Producer(); + const path = Moq.Path.from("peer/data"); + const broadcast = publishing.createBroadcast(path); + broadcast.announce(); + const track = broadcast.createTrack("data", { timescale: Moq.Time.Timescale.MILLI }); + let client: Awaited> | undefined; + let server: Awaited> | undefined; + try { + await left.setLocalDescription(await left.createOffer()); + await gathered(left); + if (!left.localDescription) throw new Error("missing offer"); + await right.setRemoteDescription(left.localDescription); + await right.setLocalDescription(await right.createAnswer()); + await gathered(right); + if (!right.localDescription) throw new Error("missing answer"); + await left.setRemoteDescription(right.localDescription); + const accepted = await incoming; + const url = new URL("https://peer.invalid/"); + [client, server] = await Promise.all([ + Moq.Connection.connect({ url, transport, consume: consuming }), + Moq.Connection.accept({ url, transport: accepted, publish: publishing.consume() }), + ]); + const request = consuming.request(path); + try { + while (!request.active.peek()) await request.active.changed(); + const active = request.active.peek(); + if (!active) throw new Error("broadcast disappeared"); + const subscriber = active.track("data").subscribe().ordered(); + try { + const demand = track.demand().used; + while (!demand.peek()) await demand.changed(); + const payload = Uint8Array.from({ length: 256 * 1024 }, (_, i) => i % 251); + track.writeFrame({ payload, timestamp: Moq.Time.Timestamp.now() }); + const frame = await subscriber.readFrame(); + if ( + !frame || + frame.payload.byteLength !== payload.byteLength || + frame.payload.some((value, i) => value !== payload[i]) + ) { + throw new Error("data-channel frame payload changed"); + } + const report: Report = { + client: client.transport, + server: server.transport, + version: client.version, + bytes: frame.payload.byteLength, + peerStates: [], + }; + subscriber.close(); + await Promise.all([client.close(), server.close()]); + report.peerStates = [left.signalingState, right.signalingState]; + return report; + } finally { + subscriber.close(); + } + } finally { + request.close(); + } + } finally { + client?.abort(); + server?.abort(); + transport.close(); + track.close(); + broadcast.close(); + publishing.close(); + consuming.close(); + left.close(); + right.close(); + } +}; diff --git a/test/p2p/transport.browser.ts b/test/p2p/transport.browser.ts new file mode 100644 index 00000000000..847335cc485 --- /dev/null +++ b/test/p2p/transport.browser.ts @@ -0,0 +1,56 @@ +/** Real RTCDataChannel SETUP and media transfer through the public MoQ API. @module */ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { type Browser, chromium } from "playwright"; +import { build } from "vite"; +import type { Report } from "./src/main.ts"; + +let dist: string; +let server: ReturnType; +let browser: Browser; + +beforeAll(async () => { + dist = mkdtempSync(join(tmpdir(), "moq-p2p-")); + await build({ + configFile: false, + root: import.meta.dir, + logLevel: "warn", + build: { target: "esnext", outDir: dist, emptyOutDir: true }, + }); + server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + async fetch(req) { + const path = new URL(req.url).pathname; + const file = Bun.file(join(dist, path === "/" ? "index.html" : path)); + return (await file.exists()) ? new Response(file) : new Response("not found", { status: 404 }); + }, + }); + browser = await chromium.launch({ channel: "chromium", headless: true }); +}, 120_000); + +afterAll(async () => { + await browser?.close(); + server?.stop(); + if (dist) rmSync(dist, { recursive: true, force: true }); +}); + +test("two peer connections complete MoQ SETUP and transfer a frame without a relay", async () => { + const page = await browser.newPage(); + const errors: string[] = []; + page.on("pageerror", (error) => errors.push(error.message)); + try { + await page.goto(`http://127.0.0.1:${server.port}/`); + const report: Report = await page.evaluate(() => window.checkTransport()); + expect(report.client).toBe("webrtc"); + expect(report.server).toBe("webrtc"); + expect(report.version).toBe("moq-lite-07-wip"); + expect(report.bytes).toBe(256 * 1024); + expect(report.peerStates).toEqual(["stable", "stable"]); + expect(errors).toEqual([]); + } finally { + await page.close(); + } +}, 60_000); diff --git a/test/p2p/tsconfig.json b/test/p2p/tsconfig.json new file mode 100644 index 00000000000..60699cb84ee --- /dev/null +++ b/test/p2p/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../js/tsconfig.json", + "compilerOptions": { "types": ["bun", "vite/client"], "noEmit": true }, + "include": ["transport.browser.ts", "src"] +}