Files
Shade/packages/shade-media/src/server/live-relay.ts

477 lines
17 KiB
TypeScript
Raw Normal View History

/**
* The live relay: one WebSocket in from the publisher, fan-out to viewers.
*
* GET /v1/live/:channelId (WebSocket)
*
* First text message decides the role:
* { "type": "publish", "hello": "<signed JSON>", "signature": "<b64u>" }
* { "type": "subscribe", "token": "<b64u read token>" }
*
* The relay holds no keys. It *does* verify every frame's Ed25519 signature
* against the key the channel was pinned with — cheap, and it means a relay
* never stores or forwards a frame its viewers would reject anyway.
*
* Backlog, per channel, so a viewer who joins late has something to start
* from: every sticky frame of the current epoch (codec init), plus the
* frames since the N-th most recent keyframe, capped in bytes and count.
* It is live data — ciphertext held for minutes — and lives in memory; the
* channel *pins* (which key owns which channel) are persistent, so a relay
* restart cannot let someone else claim a channel id a viewer already holds.
*
* A viewer that cannot keep up is not allowed to grow the relay's memory:
* past a high-water mark its non-sticky frames are dropped until its socket
* drains and the next keyframe comes along, which is exactly where a video
* decoder can pick up again.
*/
import { ed25519 } from '@noble/curves/ed25519.js';
import { Hono } from 'hono';
import { upgradeWebSocket } from 'hono/bun';
import type { WSContext } from 'hono/ws';
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import { enc, equalBytes, fromB64u, randomBytes, sha256, toB64u, toHex } from '../bytes.js';
import { decodeFrame, FLAG_END, FLAG_KEYFRAME, FLAG_STICKY } from '../live/frame.js';
import { MAX_SKEW_MS, verifyPublishOwner } from '../owner.js';
import { Ed25519Verifier } from '../ed25519.js';
export interface LivePin {
channelId: string; // base64url
signingKey: string; // base64url
readTokenHash: string; // base64url SHA-256
pinnedAt: number;
lastSeen: number;
}
export interface LivePinStore {
get(channelId: string): Promise<LivePin | null>;
feat(media): one library for several relays — films in S3, records and live pins in Postgres FileMediaStore ties a library to one disk on one machine. SHADE_MEDIA_S3_URL + SHADE_MEDIA_PG_URL (or `media serve --s3 --pg`) put sealed bytes in any S3 bucket and the records every instance must agree on in Postgres. - ObjectMediaStore: each upload streams as multipart to its own object key; the commit is an INSERT whose primary key admits one record per id, so racing uploads on any instances are decided once and the loser deletes its object. Delete drops the record first. sweep() reclaims unreferenced objects and dead multipart uploads past a 24 h grace. - S3Bucket: Shade's own SigV4 client. Bun 1.3.5's S3Client buffers a whole upload (512 MiB in, 543 MiB RSS), end(error) does not abort, and slice(0, n).stream() returned the whole object. Here: at most three parts in memory (512 MiB through, 11 MiB RSS), payload-hashed signatures, AbortMultipartUpload, ranged reads checked for length. - PostgresMediaIndex, PostgresLivePinStore, createSharedMediaBackend in @shade/storage-postgres. LivePinStore.put now refuses a key change (LivePinTakenError) in every store, atomically in Postgres. - The container logs a backend it cannot use and runs on without media. Verified: SigV4 reproduces AWS's published example signature; SeaweedFS with signature checking accepts it and refuses a wrong secret (403); Postgres 16: racing inserts over 8 pools (1 of 24 wins), racing pins, BIGINT sizes; two relays over one backend; CLI relays behind a round-robin proxy: upload, bit-identical download, Chromium playback seeked to 24 s with ranges served by both; the bucket holds no plaintext, name or MP4 marker. Suites: media 87, storage-postgres 18, server 55, cli 15, all green. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:28:58 +02:00
/**
* Create or refresh a pin. Must throw `LivePinTakenError` if the channel is
* pinned to another signing key — atomically, so two relays sharing the
* store cannot both pin one channel to different keys.
*/
put(pin: LivePin): Promise<void>;
}
feat(media): one library for several relays — films in S3, records and live pins in Postgres FileMediaStore ties a library to one disk on one machine. SHADE_MEDIA_S3_URL + SHADE_MEDIA_PG_URL (or `media serve --s3 --pg`) put sealed bytes in any S3 bucket and the records every instance must agree on in Postgres. - ObjectMediaStore: each upload streams as multipart to its own object key; the commit is an INSERT whose primary key admits one record per id, so racing uploads on any instances are decided once and the loser deletes its object. Delete drops the record first. sweep() reclaims unreferenced objects and dead multipart uploads past a 24 h grace. - S3Bucket: Shade's own SigV4 client. Bun 1.3.5's S3Client buffers a whole upload (512 MiB in, 543 MiB RSS), end(error) does not abort, and slice(0, n).stream() returned the whole object. Here: at most three parts in memory (512 MiB through, 11 MiB RSS), payload-hashed signatures, AbortMultipartUpload, ranged reads checked for length. - PostgresMediaIndex, PostgresLivePinStore, createSharedMediaBackend in @shade/storage-postgres. LivePinStore.put now refuses a key change (LivePinTakenError) in every store, atomically in Postgres. - The container logs a backend it cannot use and runs on without media. Verified: SigV4 reproduces AWS's published example signature; SeaweedFS with signature checking accepts it and refuses a wrong secret (403); Postgres 16: racing inserts over 8 pools (1 of 24 wins), racing pins, BIGINT sizes; two relays over one backend; CLI relays behind a round-robin proxy: upload, bit-identical download, Chromium playback seeked to 24 s with ranges served by both; the bucket holds no plaintext, name or MP4 marker. Suites: media 87, storage-postgres 18, server 55, cli 15, all green. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:28:58 +02:00
export class LivePinTakenError extends Error {
override readonly name = 'LivePinTakenError';
constructor(channelId: string) {
super(`channel ${channelId} is pinned to another key`);
}
}
export class MemoryLivePinStore implements LivePinStore {
private readonly pins = new Map<string, LivePin>();
async get(id: string): Promise<LivePin | null> {
return this.pins.get(id) ?? null;
}
async put(pin: LivePin): Promise<void> {
feat(media): one library for several relays — films in S3, records and live pins in Postgres FileMediaStore ties a library to one disk on one machine. SHADE_MEDIA_S3_URL + SHADE_MEDIA_PG_URL (or `media serve --s3 --pg`) put sealed bytes in any S3 bucket and the records every instance must agree on in Postgres. - ObjectMediaStore: each upload streams as multipart to its own object key; the commit is an INSERT whose primary key admits one record per id, so racing uploads on any instances are decided once and the loser deletes its object. Delete drops the record first. sweep() reclaims unreferenced objects and dead multipart uploads past a 24 h grace. - S3Bucket: Shade's own SigV4 client. Bun 1.3.5's S3Client buffers a whole upload (512 MiB in, 543 MiB RSS), end(error) does not abort, and slice(0, n).stream() returned the whole object. Here: at most three parts in memory (512 MiB through, 11 MiB RSS), payload-hashed signatures, AbortMultipartUpload, ranged reads checked for length. - PostgresMediaIndex, PostgresLivePinStore, createSharedMediaBackend in @shade/storage-postgres. LivePinStore.put now refuses a key change (LivePinTakenError) in every store, atomically in Postgres. - The container logs a backend it cannot use and runs on without media. Verified: SigV4 reproduces AWS's published example signature; SeaweedFS with signature checking accepts it and refuses a wrong secret (403); Postgres 16: racing inserts over 8 pools (1 of 24 wins), racing pins, BIGINT sizes; two relays over one backend; CLI relays behind a round-robin proxy: upload, bit-identical download, Chromium playback seeked to 24 s with ranges served by both; the bucket holds no plaintext, name or MP4 marker. Suites: media 87, storage-postgres 18, server 55, cli 15, all green. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:28:58 +02:00
const have = this.pins.get(pin.channelId);
if (have !== undefined && have.signingKey !== pin.signingKey) throw new LivePinTakenError(pin.channelId);
this.pins.set(pin.channelId, pin);
}
}
/**
* Pins in one JSON file, rewritten atomically. A relay has few channels
* (hundreds, not millions) and pins change only when one is created, so a
* file is enough and needs no database. Pins idle past `ttlMs` are dropped.
*/
export class FileLivePinStore implements LivePinStore {
private pins: Map<string, LivePin> | null = null;
private writing: Promise<void> = Promise.resolve();
constructor(
private readonly path: string,
private readonly ttlMs = 30 * 24 * 3600 * 1000,
) {}
private async load(): Promise<Map<string, LivePin>> {
if (this.pins !== null) return this.pins;
const pins = new Map<string, LivePin>();
try {
for (const p of JSON.parse(await readFile(this.path, 'utf8')) as LivePin[]) pins.set(p.channelId, p);
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
}
this.pins = pins;
return pins;
}
async get(id: string): Promise<LivePin | null> {
return (await this.load()).get(id) ?? null;
}
async put(pin: LivePin): Promise<void> {
const pins = await this.load();
feat(media): one library for several relays — films in S3, records and live pins in Postgres FileMediaStore ties a library to one disk on one machine. SHADE_MEDIA_S3_URL + SHADE_MEDIA_PG_URL (or `media serve --s3 --pg`) put sealed bytes in any S3 bucket and the records every instance must agree on in Postgres. - ObjectMediaStore: each upload streams as multipart to its own object key; the commit is an INSERT whose primary key admits one record per id, so racing uploads on any instances are decided once and the loser deletes its object. Delete drops the record first. sweep() reclaims unreferenced objects and dead multipart uploads past a 24 h grace. - S3Bucket: Shade's own SigV4 client. Bun 1.3.5's S3Client buffers a whole upload (512 MiB in, 543 MiB RSS), end(error) does not abort, and slice(0, n).stream() returned the whole object. Here: at most three parts in memory (512 MiB through, 11 MiB RSS), payload-hashed signatures, AbortMultipartUpload, ranged reads checked for length. - PostgresMediaIndex, PostgresLivePinStore, createSharedMediaBackend in @shade/storage-postgres. LivePinStore.put now refuses a key change (LivePinTakenError) in every store, atomically in Postgres. - The container logs a backend it cannot use and runs on without media. Verified: SigV4 reproduces AWS's published example signature; SeaweedFS with signature checking accepts it and refuses a wrong secret (403); Postgres 16: racing inserts over 8 pools (1 of 24 wins), racing pins, BIGINT sizes; two relays over one backend; CLI relays behind a round-robin proxy: upload, bit-identical download, Chromium playback seeked to 24 s with ranges served by both; the bucket holds no plaintext, name or MP4 marker. Suites: media 87, storage-postgres 18, server 55, cli 15, all green. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:28:58 +02:00
const have = pins.get(pin.channelId);
if (have !== undefined && have.signingKey !== pin.signingKey) throw new LivePinTakenError(pin.channelId);
pins.set(pin.channelId, pin);
const cutoff = Date.now() - this.ttlMs;
for (const [k, p] of pins) if (p.lastSeen < cutoff) pins.delete(k);
const snapshot = JSON.stringify([...pins.values()]);
this.writing = this.writing.then(async () => {
await mkdir(dirname(this.path), { recursive: true });
const tmp = `${this.path}.${toHex(randomBytes(4))}.tmp`;
await writeFile(tmp, snapshot, { mode: 0o600 });
await rename(tmp, this.path);
});
await this.writing;
}
}
export interface LiveRelayOptions {
pins: LivePinStore;
/**
* Owner keys (base64url) allowed to publish. A publisher then co-signs its
* hello with one of them. Unset = anyone may open a channel.
*/
allowedOwners?: readonly string[];
/** Channels held at once (live state, not pins). Default 1000. */
maxChannels?: number;
/** Keyframes of history kept for late joiners. Default 3. */
backlogKeyframes?: number;
/** Byte cap on a channel's backlog (sticky frames excluded). Default 32 MiB. */
maxBacklogBytes?: number;
/** Frame-count cap on a channel's backlog. Default 5000. */
maxBacklogFrames?: number;
/** Viewer socket buffer past which frames are dropped until the next keyframe. Default 8 MiB. */
viewerHighWater?: number;
/** How long an idle channel (no publisher, no viewers) keeps its backlog. Default 10 min. */
idleRetentionMs?: number;
/** Largest frame accepted. Default 16 MiB + headers. */
maxFrameBytes?: number;
now?: () => number;
}
interface Viewer {
ws: WSContext;
lagging: boolean;
}
interface Channel {
id: string;
pin: LivePin;
verifier: Ed25519Verifier;
publisher: WSContext | null;
viewers: Set<Viewer>;
epoch: number;
sticky: Uint8Array[];
backlog: { frame: Uint8Array; keyframe: boolean }[];
backlogBytes: number;
sawKeyframe: boolean;
ended: boolean;
idleSince: number;
}
type Role = { kind: 'none' } | { kind: 'pub'; ch: Channel } | { kind: 'sub'; ch: Channel; viewer: Viewer };
function bufferedAmount(ws: WSContext): number {
const raw = ws.raw as { getBufferedAmount?: () => number } | undefined;
return raw?.getBufferedAmount?.() ?? 0;
}
function toBytes(data: unknown): Uint8Array | null {
if (data instanceof Uint8Array) return data;
if (data instanceof ArrayBuffer) return new Uint8Array(data);
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
return null;
}
export interface LiveRelay {
app: Hono;
/** Channels currently held, for metrics and tests. */
/** `framesIn`: frames accepted from publishers since the relay started. */
stats(): { channels: number; viewers: number; backlogBytes: number; framesIn: number };
/** Drop idle channels now (also runs on a timer). */
sweep(): void;
stop(): void;
}
export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
const now = opts.now ?? Date.now;
const keepKeyframes = Math.max(1, opts.backlogKeyframes ?? 3);
const maxBytes = opts.maxBacklogBytes ?? 32 * 1024 * 1024;
const maxFrames = opts.maxBacklogFrames ?? 5000;
const highWater = opts.viewerHighWater ?? 8 * 1024 * 1024;
const idleMs = opts.idleRetentionMs ?? 10 * 60 * 1000;
let framesIn = 0;
const maxFrameBytes = opts.maxFrameBytes ?? 16 * 1024 * 1024 + 256;
const channels = new Map<string, Channel>();
const allowedOwners = opts.allowedOwners !== undefined ? new Set(opts.allowedOwners) : null;
const maxChannels = opts.maxChannels ?? 1000;
async function channelFor(id: string): Promise<Channel | null> {
const have = channels.get(id);
if (have !== undefined) return have;
const pin = await opts.pins.get(id);
if (pin === null) return null;
if (channels.size >= maxChannels) {
sweep();
if (channels.size >= maxChannels) throw new Error('relay is at its channel limit');
}
const ch: Channel = {
id,
pin,
verifier: new Ed25519Verifier(fromB64u(pin.signingKey, 32)),
publisher: null,
viewers: new Set(),
epoch: -1,
sticky: [],
backlog: [],
backlogBytes: 0,
sawKeyframe: false,
ended: false,
idleSince: now(),
};
channels.set(id, ch);
return ch;
}
function trim(ch: Channel): void {
// Keep from the keepKeyframes-th most recent keyframe onward…
let seen = 0;
let cut = 0;
for (let i = ch.backlog.length - 1; i >= 0; i--) {
if (ch.backlog[i]!.keyframe && ++seen === keepKeyframes) {
cut = i;
break;
}
}
// …then enforce the hard caps, oldest first.
let drop = cut;
let bytes = ch.backlogBytes;
for (let i = 0; i < drop; i++) bytes -= ch.backlog[i]!.frame.length;
while (drop < ch.backlog.length && (bytes > maxBytes || ch.backlog.length - drop > maxFrames)) {
bytes -= ch.backlog[drop]!.frame.length;
drop++;
}
if (drop > 0) {
ch.backlog.splice(0, drop);
ch.backlogBytes = bytes;
}
}
function deliver(v: Viewer, frame: Uint8Array, sticky: boolean, keyframe: boolean, sawKeyframe: boolean): void {
if (!sticky) {
if (v.lagging) {
// Resume only where a decoder can: a keyframe (or any frame, on a
// channel that has none — a log stream).
if (bufferedAmount(v.ws) > highWater / 4 || (sawKeyframe && !keyframe)) return;
v.lagging = false;
} else if (bufferedAmount(v.ws) > highWater) {
v.lagging = true;
return;
}
}
v.ws.send(frame as Uint8Array<ArrayBuffer>);
}
function notifyPublisher(ch: Channel): void {
ch.publisher?.send(JSON.stringify({ type: 'viewers', count: ch.viewers.size }));
}
async function accept(ch: Channel, frame: Uint8Array): Promise<string | null> {
if (frame.length > maxFrameBytes) return 'frame too large';
let f;
try {
f = decodeFrame(frame);
} catch (e) {
return (e as Error).message;
}
if (toB64u(f.header.channelId) !== ch.id) return 'frame for another channel';
if (!(await ch.verifier.verify(f.signature, f.signed))) return 'bad frame signature';
const { epoch, flags } = f.header;
if (epoch < ch.epoch) return null; // a stale frame from before a rotation: drop quietly
if (epoch > ch.epoch) {
ch.epoch = epoch;
ch.sticky = [];
ch.backlog = [];
ch.backlogBytes = 0;
ch.sawKeyframe = false;
}
const sticky = (flags & FLAG_STICKY) !== 0;
const keyframe = (flags & FLAG_KEYFRAME) !== 0;
const copy = frame.slice();
if (sticky) {
ch.sticky.push(copy);
} else {
if (keyframe) ch.sawKeyframe = true;
ch.backlog.push({ frame: copy, keyframe });
ch.backlogBytes += copy.length;
trim(ch);
}
if ((flags & FLAG_END) !== 0) ch.ended = true;
framesIn++;
for (const v of ch.viewers) deliver(v, copy, sticky, keyframe, ch.sawKeyframe);
return null;
}
function sweep(): void {
const t = now();
for (const [id, ch] of channels) {
if (ch.publisher === null && ch.viewers.size === 0 && t - ch.idleSince > idleMs) channels.delete(id);
}
}
const timer = setInterval(sweep, 60_000);
(timer as { unref?: () => void }).unref?.();
const app = new Hono();
app.get(
'/v1/live/:channelId',
upgradeWebSocket((c) => {
const channelId = c.req.param('channelId') ?? '';
let role: Role = { kind: 'none' };
let busy: Promise<void> = Promise.resolve();
const fail = (ws: WSContext, message: string, code = 1008) => {
ws.send(JSON.stringify({ type: 'error', message }));
ws.close(code, message.slice(0, 120));
};
async function onControl(ws: WSContext, text: string): Promise<void> {
let msg: Record<string, unknown>;
try {
msg = JSON.parse(text);
} catch {
return fail(ws, 'control message is not JSON');
}
if (role.kind !== 'none') return fail(ws, 'role already chosen');
if (!/^[A-Za-z0-9_-]{22}$/.test(channelId)) return fail(ws, 'bad channel id');
if (msg.type === 'publish') {
if (typeof msg.hello !== 'string' || typeof msg.signature !== 'string') return fail(ws, 'bad publish');
let hello: Record<string, unknown>;
try {
hello = JSON.parse(msg.hello);
} catch {
return fail(ws, 'hello is not JSON');
}
if (
hello.kind !== 'shade.live-hello/v1' ||
hello.channelId !== channelId ||
typeof hello.signingKey !== 'string' ||
typeof hello.readTokenHash !== 'string' ||
typeof hello.at !== 'number' ||
Math.abs(now() - hello.at) > MAX_SKEW_MS
) {
return fail(ws, 'hello rejected');
}
let signingKey: Uint8Array;
try {
signingKey = fromB64u(hello.signingKey, 32);
fromB64u(hello.readTokenHash, 32);
if (!ed25519.verify(fromB64u(msg.signature, 64), enc.encode(msg.hello), signingKey)) {
return fail(ws, 'hello signature does not verify');
}
} catch {
return fail(ws, 'malformed hello');
}
if (allowedOwners !== null) {
const owner = typeof msg.owner === 'string' ? msg.owner : '';
const osig = typeof msg.ownerSignature === 'string' ? msg.ownerSignature : '';
if (!allowedOwners.has(owner) || !verifyPublishOwner(owner, osig, msg.hello)) {
return fail(ws, 'this relay only accepts channels from its owners');
}
}
const existing = await opts.pins.get(channelId);
if (existing !== null && existing.signingKey !== hello.signingKey) {
return fail(ws, 'channel is pinned to another key');
}
const pin: LivePin = {
channelId,
signingKey: hello.signingKey,
readTokenHash: hello.readTokenHash,
pinnedAt: existing?.pinnedAt ?? now(),
lastSeen: now(),
};
feat(media): one library for several relays — films in S3, records and live pins in Postgres FileMediaStore ties a library to one disk on one machine. SHADE_MEDIA_S3_URL + SHADE_MEDIA_PG_URL (or `media serve --s3 --pg`) put sealed bytes in any S3 bucket and the records every instance must agree on in Postgres. - ObjectMediaStore: each upload streams as multipart to its own object key; the commit is an INSERT whose primary key admits one record per id, so racing uploads on any instances are decided once and the loser deletes its object. Delete drops the record first. sweep() reclaims unreferenced objects and dead multipart uploads past a 24 h grace. - S3Bucket: Shade's own SigV4 client. Bun 1.3.5's S3Client buffers a whole upload (512 MiB in, 543 MiB RSS), end(error) does not abort, and slice(0, n).stream() returned the whole object. Here: at most three parts in memory (512 MiB through, 11 MiB RSS), payload-hashed signatures, AbortMultipartUpload, ranged reads checked for length. - PostgresMediaIndex, PostgresLivePinStore, createSharedMediaBackend in @shade/storage-postgres. LivePinStore.put now refuses a key change (LivePinTakenError) in every store, atomically in Postgres. - The container logs a backend it cannot use and runs on without media. Verified: SigV4 reproduces AWS's published example signature; SeaweedFS with signature checking accepts it and refuses a wrong secret (403); Postgres 16: racing inserts over 8 pools (1 of 24 wins), racing pins, BIGINT sizes; two relays over one backend; CLI relays behind a round-robin proxy: upload, bit-identical download, Chromium playback seeked to 24 s with ranges served by both; the bucket holds no plaintext, name or MP4 marker. Suites: media 87, storage-postgres 18, server 55, cli 15, all green. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:28:58 +02:00
try {
await opts.pins.put(pin);
} catch (e) {
// Another relay sharing the pin store won the race for this channel.
if (e instanceof LivePinTakenError) return fail(ws, 'channel is pinned to another key');
throw e;
}
const ch = (await channelFor(channelId))!;
ch.pin = pin;
// A reconnecting publisher replaces the stale socket.
if (ch.publisher !== null && ch.publisher !== ws) ch.publisher.close(4000, 'replaced by a newer publisher');
ch.publisher = ws;
ch.ended = false;
role = { kind: 'pub', ch };
ws.send(JSON.stringify({ type: 'ready', role: 'publisher', epoch: ch.epoch, viewers: ch.viewers.size }));
return;
}
if (msg.type === 'subscribe') {
if (typeof msg.token !== 'string') return fail(ws, 'bad subscribe');
const ch = await channelFor(channelId);
let ok = false;
if (ch !== null) {
try {
ok = equalBytes(await sha256(fromB64u(msg.token)), fromB64u(ch.pin.readTokenHash, 32));
} catch {
ok = false;
}
}
// Same refusal for "no such channel" and "wrong token".
if (ch === null || !ok) return fail(ws, 'not found', 4404);
const viewer: Viewer = { ws, lagging: false };
ch.viewers.add(viewer);
role = { kind: 'sub', ch, viewer };
ws.send(
JSON.stringify({ type: 'ready', role: 'viewer', live: ch.publisher !== null, ended: ch.ended, epoch: ch.epoch }),
);
for (const f of ch.sticky) ws.send(f as Uint8Array<ArrayBuffer>);
for (const b of ch.backlog) deliver(viewer, b.frame, false, b.keyframe, ch.sawKeyframe);
notifyPublisher(ch);
return;
}
return fail(ws, 'unknown control message');
}
return {
onMessage(evt, ws) {
// Serialise per socket: the role is decided asynchronously (a pin
// lookup), and a frame must not race past its own hello.
busy = busy.then(async () => {
if (typeof evt.data === 'string') return onControl(ws, evt.data);
const bytes = toBytes(evt.data);
if (bytes === null) return;
if (role.kind !== 'pub') return fail(ws, 'only the publisher sends frames');
const err = await accept(role.ch, bytes);
if (err !== null) fail(ws, err);
}).catch((e) => fail(ws, String((e as Error)?.message ?? e), 1011));
},
onClose(_evt, ws) {
if (role.kind === 'pub' && role.ch.publisher === ws) {
role.ch.publisher = null;
role.ch.idleSince = now();
} else if (role.kind === 'sub') {
role.ch.viewers.delete(role.viewer);
role.ch.idleSince = now();
notifyPublisher(role.ch);
}
},
};
}),
);
return {
app,
stats() {
let viewers = 0;
let backlogBytes = 0;
for (const ch of channels.values()) {
viewers += ch.viewers.size;
backlogBytes += ch.backlogBytes;
}
return { channels: channels.size, viewers, backlogBytes, framesIn };
},
sweep,
stop() {
clearInterval(timer);
},
};
}