feat(media): live channels across relay instances; viewers hear when a channel goes live

With several relays sharing pins, a viewer and the publisher could land on
different instances and never meet. LiveRelayOptions.mesh: each relay
claims the channels whose publisher it holds (LivePublisherLocator,
Postgres table shade_live_publishers, heartbeat 10 s). A relay whose
viewers want a channel published elsewhere subscribes to that relay once,
with a viewer's own read token, and fans out locally, verifying every
frame against the pin (a peer or a poisoned locator row cannot forge
one). Re-following replays a backlog; frames are passed on once (seq).
Viewers follow a publisher that moves. A token that fails the in-memory
pin is checked against the shared pin before refusal, so a publisher
back with a new read token is honoured on every instance.
SHADE_MEDIA_RELAY_URL / `media serve --advertise`.

Relays now send {"type":"state","live"} when a channel goes live or quiet
after a viewer joined; handled by the TS client (browser) and Android's
LiveWatcher.

Fixed on the way:
- The relay never saw its publisher leave: Hono gives each event its own
  WSContext and the close handler compared identity. Channels stayed
  "live" with nobody publishing; a replaced publisher was never closed.
- FileMediaStore on an unusable directory raised an unhandled rejection
  at start; now each call fails with the reason.

Verified: 5 mesh tests (follow, late join, publisher moving A→B with
dedupe, forging peer refused, new read token) + state test, each fix
mutation-checked; Postgres locator + two media services over Postgres;
CLI relays with --advertise behind a round-robin HTTP+WS balancer:
publisher on A, Chromium viewer on B, "live", 208 lines. Suites: media
93, storage-postgres 20, server 55; Kotlin 92 (1 skipped), 0 failures.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 22:44:19 +02:00
parent aaec92429d
commit f1b4c1ade1
21 changed files with 704 additions and 36 deletions

View File

@@ -60,6 +60,35 @@ export class LivePinTakenError extends Error {
}
}
/**
* Where a channel's publisher is connected, when several relays share one
* pin store. A relay with viewers but not the publisher looks the channel up
* here and follows the relay that has it (see `LiveRelayOptions.mesh`).
*/
export interface LivePublisherLocator {
/** This relay holds the channel's publisher. Called again as a heartbeat while it does. */
claim(channelId: string, relayUrl: string, at: number): Promise<void>;
/** The publisher left this relay. Only removes a claim that is still this relay's. */
release(channelId: string, relayUrl: string): Promise<void>;
/** The relay holding the publisher, if its claim was refreshed after `freshAfter`. */
find(channelId: string, freshAfter: number): Promise<string | null>;
}
/** One process's locator — for tests, and relays that share memory. */
export class MemoryLivePublisherLocator implements LivePublisherLocator {
private readonly claims = new Map<string, { url: string; at: number }>();
async claim(channelId: string, relayUrl: string, at: number): Promise<void> {
this.claims.set(channelId, { url: relayUrl, at });
}
async release(channelId: string, relayUrl: string): Promise<void> {
if (this.claims.get(channelId)?.url === relayUrl) this.claims.delete(channelId);
}
async find(channelId: string, freshAfter: number): Promise<string | null> {
const c = this.claims.get(channelId);
return c !== undefined && c.at > freshAfter ? c.url : null;
}
}
export class MemoryLivePinStore implements LivePinStore {
private readonly pins = new Map<string, LivePin>();
async get(id: string): Promise<LivePin | null> {
@@ -141,6 +170,24 @@ export interface LiveRelayOptions {
idleRetentionMs?: number;
/** Largest frame accepted. Default 16 MiB + headers. */
maxFrameBytes?: number;
/**
* Several relays, one set of channels. Each relay claims the channels whose
* publisher is connected to it; a relay with viewers of a channel published
* elsewhere subscribes to that relay, once, with a viewer's own read token,
* and fans the frames out to its viewers. It verifies every frame against
* the pin as if the publisher were its own, so a peer cannot forge one.
*/
mesh?: {
/** This relay's base URL as the other relays reach it, e.g. `http://10.0.0.5:3000`. */
self: string;
locator: LivePublisherLocator;
/** Claim refresh. Default 10 s. */
heartbeatMs?: number;
/** A claim older than this is a relay that died. Default 30 s. */
staleMs?: number;
/** How often a channel with viewers looks for a publisher that is not here. Default 2 s. */
pollMs?: number;
};
now?: () => number;
}
@@ -162,10 +209,27 @@ interface Channel {
sawKeyframe: boolean;
ended: boolean;
idleSince: number;
/** Highest seq taken this epoch — a relay followed again resends its backlog. */
lastSeq: number;
/** The relay this one follows for the channel (mesh), when its publisher is there. */
upstream: WebSocket | null;
/** A read token a viewer proved, to subscribe upstream with. */
token: string | null;
/** Pending look-up for a publisher elsewhere. */
poll: ReturnType<typeof setTimeout> | null;
}
type Role = { kind: 'none' } | { kind: 'pub'; ch: Channel } | { kind: 'sub'; ch: Channel; viewer: Viewer };
/**
* Hono hands each event its own WSContext for one socket, so `===` between
* the one seen at `publish` and the one at close is always false: compare the
* socket underneath.
*/
function sameSocket(a: WSContext | null, b: WSContext): boolean {
return a !== null && (a === b || (a.raw !== undefined && a.raw === b.raw));
}
function bufferedAmount(ws: WSContext): number {
const raw = ws.raw as { getBufferedAmount?: () => number } | undefined;
return raw?.getBufferedAmount?.() ?? 0;
@@ -223,11 +287,31 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
sawKeyframe: false,
ended: false,
idleSince: now(),
lastSeq: -1,
upstream: null,
token: null,
poll: null,
};
channels.set(id, ch);
return ch;
}
/** Adopt a pin read from the shared store. A new signing key is a new channel. */
function repin(ch: Channel, pin: LivePin): void {
if (pin.signingKey !== ch.pin.signingKey) {
closeUpstream(ch);
ch.verifier = new Ed25519Verifier(fromB64u(pin.signingKey, 32));
ch.epoch = -1;
ch.sticky = [];
ch.backlog = [];
ch.backlogBytes = 0;
ch.sawKeyframe = false;
ch.lastSeq = -1;
ch.ended = false;
}
ch.pin = pin;
}
function trim(ch: Channel): void {
// Keep from the keepKeyframes-th most recent keyframe onward…
let seen = 0;
@@ -267,11 +351,18 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
v.ws.send(frame as Uint8Array<ArrayBuffer>);
}
/** Tell viewers when the channel goes live or quiet after they joined (the `ready` answer is only the start). */
function notifyViewers(ch: Channel): void {
const live = ch.publisher !== null || ch.upstream !== null;
const msg = JSON.stringify({ type: 'state', live, ended: ch.ended, epoch: ch.epoch });
for (const v of ch.viewers) v.ws.send(msg);
}
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> {
async function accept(ch: Channel, frame: Uint8Array, fromUpstream = false): Promise<string | null> {
if (frame.length > maxFrameBytes) return 'frame too large';
let f;
try {
@@ -289,7 +380,11 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
ch.backlog = [];
ch.backlogBytes = 0;
ch.sawKeyframe = false;
ch.lastSeq = -1;
}
// Following another relay again replays its backlog: pass on each frame once.
if (fromUpstream && f.header.seq <= ch.lastSeq) return null;
ch.lastSeq = Math.max(ch.lastSeq, f.header.seq);
const sticky = (flags & FLAG_STICKY) !== 0;
const keyframe = (flags & FLAG_KEYFRAME) !== 0;
const copy = frame.slice();
@@ -307,10 +402,96 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
return null;
}
const mesh = opts.mesh;
const heartbeatMs = mesh?.heartbeatMs ?? 10_000;
const staleMs = mesh?.staleMs ?? 30_000;
const pollMs = mesh?.pollMs ?? 2_000;
const self = mesh?.self.replace(/\/$/, '');
let stopped = false;
function closeUpstream(ch: Channel): void {
if (ch.poll !== null) {
clearTimeout(ch.poll);
ch.poll = null;
}
const up = ch.upstream;
ch.upstream = null;
up?.close(1000, 'not needed');
}
function schedulePoll(ch: Channel): void {
if (ch.poll !== null || stopped) return;
ch.poll = setTimeout(() => {
ch.poll = null;
void follow(ch);
}, pollMs);
(ch.poll as { unref?: () => void }).unref?.();
}
/** Follow the relay that has this channel's publisher, while viewers here want it. */
async function follow(ch: Channel): Promise<void> {
if (mesh === undefined || stopped) return;
if (ch.publisher !== null || ch.upstream !== null || ch.viewers.size === 0 || ch.token === null) return;
let url: string | null;
try {
url = await mesh.locator.find(ch.id, now() - staleMs);
} catch {
url = null;
}
// Re-check: the publisher may have arrived here while we looked.
if (ch.publisher !== null || ch.upstream !== null || ch.viewers.size === 0) return;
if (url === null || url.replace(/\/$/, '') === self) return schedulePoll(ch);
const ws = new WebSocket(`${url.replace(/^http/, 'ws').replace(/\/$/, '')}/v1/live/${ch.id}`);
ws.binaryType = 'arraybuffer';
ch.upstream = ws;
let chain: Promise<void> = Promise.resolve();
ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe', token: ch.token }));
ws.onmessage = (ev) => {
if (typeof ev.data === 'string') {
// The relay we follow took us: viewers here are live from now.
if (ch.upstream === ws && (JSON.parse(ev.data) as { type?: string }).type === 'ready') notifyViewers(ch);
return;
}
const bytes = new Uint8Array(ev.data as ArrayBuffer);
chain = chain.then(async () => {
if (ch.upstream !== ws) return;
// Verified like a publisher's own: a peer relay is not trusted with frames.
const err = await accept(ch, bytes, true);
if (err !== null) ws.close(1008, err.slice(0, 120));
});
};
ws.onclose = () => {
if (ch.upstream !== ws) return;
ch.upstream = null;
notifyViewers(ch);
// The publisher left that relay (or it died): look again while anyone watches.
if (ch.viewers.size > 0 && ch.publisher === null) schedulePoll(ch);
};
ws.onerror = () => {};
}
async function claim(ch: Channel): Promise<void> {
if (mesh === undefined) return;
await mesh.locator.claim(ch.id, self!, now()).catch(() => {
// The next heartbeat tries again; frames flow to local viewers meanwhile.
});
}
const heartbeat =
mesh !== undefined
? setInterval(() => {
for (const ch of channels.values()) if (ch.publisher !== null) void claim(ch);
}, heartbeatMs)
: null;
(heartbeat as { unref?: () => void } | null)?.unref?.();
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);
if (ch.publisher === null && ch.viewers.size === 0 && t - ch.idleSince > idleMs) {
closeUpstream(ch);
channels.delete(id);
}
}
}
const timer = setInterval(sweep, 60_000);
@@ -395,10 +576,14 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
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');
if (ch.publisher !== null && !sameSocket(ch.publisher, ws)) ch.publisher.close(4000, 'replaced by a newer publisher');
ch.publisher = ws;
ch.ended = false;
// The publisher is here now: stop following another relay, and say so.
closeUpstream(ch);
await claim(ch);
role = { kind: 'pub', ch };
notifyViewers(ch);
ws.send(JSON.stringify({ type: 'ready', role: 'publisher', epoch: ch.epoch, viewers: ch.viewers.size }));
return;
}
@@ -406,12 +591,21 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
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;
let tokenHash: Uint8Array | null = null;
try {
tokenHash = await sha256(fromB64u(msg.token));
} catch {
tokenHash = null;
}
const matches = () => tokenHash !== null && equalBytes(tokenHash, fromB64u(ch!.pin.readTokenHash, 32));
let ok = ch !== null && matches();
if (ch !== null && !ok && ch.publisher === null && mesh !== undefined) {
// The publisher is on another relay and may have come back with a
// new read token: judge by the shared pin, not the copy held here.
const fresh = await opts.pins.get(channelId);
if (fresh !== null) {
repin(ch, fresh);
ok = matches();
}
}
// Same refusal for "no such channel" and "wrong token".
@@ -419,12 +613,14 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
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 }),
);
// The latest proven token: the one the shared pin accepts now.
ch.token = msg.token;
const live = ch.publisher !== null || ch.upstream !== null;
ws.send(JSON.stringify({ type: 'ready', role: 'viewer', live, 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);
if (ch.publisher === null) void follow(ch);
return;
}
return fail(ws, 'unknown control message');
@@ -444,13 +640,21 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
}).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();
if (role.kind === 'pub' && sameSocket(role.ch.publisher, ws)) {
const ch = role.ch;
ch.publisher = null;
ch.idleSince = now();
notifyViewers(ch);
if (mesh !== undefined) {
void mesh.locator.release(ch.id, self!).catch(() => {});
// It may come back on another relay: viewers here follow it there.
if (ch.viewers.size > 0) schedulePoll(ch);
}
} else if (role.kind === 'sub') {
role.ch.viewers.delete(role.viewer);
role.ch.idleSince = now();
notifyPublisher(role.ch);
if (role.ch.viewers.size === 0) closeUpstream(role.ch);
}
},
};
@@ -470,7 +674,13 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
},
sweep,
stop() {
stopped = true;
clearInterval(timer);
if (heartbeat !== null) clearInterval(heartbeat);
for (const ch of channels.values()) {
closeUpstream(ch);
if (mesh !== undefined && ch.publisher !== null) void mesh.locator.release(ch.id, self!).catch(() => {});
}
},
};
}