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

@@ -129,7 +129,16 @@ async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise<number> {
if (pgUrl === undefined) throw new UsageError('--s3 needs --pg: the bucket holds the bytes, Postgres the records relays share');
if (hooks.sharedBackend === undefined) throw new UsageError('--s3/--pg are not available in this build (no Postgres support)');
const backend = await hooks.sharedBackend({ s3Url, pgUrl });
svc = createMediaService({ owners, store: backend.store, pins: backend.pins, dev: flags.dev === true });
// --advertise: the address other relays reach this one at, so they can follow its live channels.
const self = str(flags, 'advertise') ?? process.env.SHADE_MEDIA_RELAY_URL;
if (self === undefined) err('live channels stay on this relay (no --advertise URL for the others to follow)');
svc = createMediaService({
owners,
store: backend.store,
pins: backend.pins,
dev: flags.dev === true,
...(self !== undefined ? { live: { mesh: { self, locator: backend.locator } } } : {}),
});
where = backend.describe;
const sweep = () => backend.sweep().catch((e: unknown) => err(`! media sweep: ${(e as Error).message}`));
setTimeout(sweep, 60_000).unref();
@@ -608,11 +617,13 @@ async function liveWatch(pos: string[]): Promise<number> {
export const MEDIA_HELP = `
media serve [--port 3910] [--dir ./shade-media-data] [--owners k1,k2] [--open]
[--s3 https://key:secret@host/bucket[/prefix] --pg postgres://…]
[--s3 https://key:secret@host/bucket[/prefix] --pg postgres://… [--advertise URL]]
Run a media relay: sealed store, live relay, watch page.
Only this machine's key (and --owners) may upload/publish.
--s3/--pg: films in a bucket, records in Postgres, so
several relays serve one library.
several relays serve one library. --advertise: this
relay's address for the others, so live channels work
whichever relay a viewer lands on.
media whoami Print this machine's owner key (to add to a relay's --owners)
media put <file|dir>… --server URL [--album T] [--name N] [--mime M] [--web] [--public] [--json]
Seal a film/video/image/song, upload it, print a watch link.
@@ -646,6 +657,7 @@ export interface MediaCliHooks {
sharedBackend?: (o: { s3Url: string; pgUrl: string }) => Promise<{
store: import('./server.js').MediaStore;
pins: import('./server.js').LivePinStore;
locator: import('./server.js').LivePublisherLocator;
describe: string;
sweep(): Promise<unknown>;
}>;

View File

@@ -250,6 +250,9 @@ export class LiveWatchClient {
if (msg.type === 'ready') {
this.retry.reset();
this.opts.onState?.(msg.live ? 'live' : 'waiting');
} else if (msg.type === 'state') {
// The publisher arrived or left after we joined.
this.opts.onState?.(msg.live ? 'live' : 'waiting');
} else if (msg.type === 'error') {
this.opts.onError?.(new Error(msg.message ?? 'relay error'));
}

View File

@@ -6,8 +6,8 @@ export { ObjectMediaStore, MemoryMediaIndex } from './server/object-store.js';
export { S3Bucket, S3Error, signV4 } from './server/s3.js';
export type { S3BucketOptions, S3Credentials, S3Object } from './server/s3.js';
export type { MediaIndex, IndexedMedia, ObjectMediaStoreOptions } from './server/object-store.js';
export { createLiveRelay, FileLivePinStore, MemoryLivePinStore, LivePinTakenError } from './server/live-relay.js';
export type { LiveRelay, LiveRelayOptions, LivePin, LivePinStore } from './server/live-relay.js';
export { createLiveRelay, FileLivePinStore, MemoryLivePinStore, LivePinTakenError, MemoryLivePublisherLocator } from './server/live-relay.js';
export type { LiveRelay, LiveRelayOptions, LivePin, LivePinStore, LivePublisherLocator } from './server/live-relay.js';
export { createWatchRoutes } from './server/watch-routes.js';
export type { WatchRoutesOptions } from './server/watch-routes.js';
export { createMediaService, parseOwners, mediaMaxRequestBody, MEDIA_BODY_ROUTE } from './server/service.js';

View File

@@ -60,6 +60,9 @@ export class FileMediaStore implements MediaStore {
constructor(private readonly dir: string) {
this.ready = this.load();
// A directory it cannot use fails every call that awaits `ready`, with
// the reason — not the process, as an unhandled rejection at start.
this.ready.catch(() => {});
}
private objectPath(id: string): string {

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(() => {});
}
},
};
}

View File

@@ -0,0 +1,11 @@
import { describe, test, expect } from 'bun:test';
import { FileMediaStore } from '../src/server.js';
describe('FileMediaStore', () => {
test('a directory it cannot use fails each call with the reason, not the process', async () => {
const store = new FileMediaStore('/proc/shade-cannot-write-here');
await new Promise((r) => setTimeout(r, 20)); // an unhandled rejection would surface here
await expect(store.get('00'.repeat(16))).rejects.toThrow(/ENOENT|EACCES|EROFS|EPERM/);
await expect(store.totalBytes()).rejects.toThrow();
});
});

View File

@@ -0,0 +1,234 @@
import { describe, test, expect } from 'bun:test';
import { websocket } from 'hono/bun';
import { Hono } from 'hono';
import { createLiveRelay, MemoryLivePinStore, MemoryLivePublisherLocator } from '../src/server.js';
import type { LivePublisherLocator } from '../src/server.js';
import { LivePublisher, LivePublishClient, LiveWatchClient, encodeGrant, parseGrant } from '../src/index.js';
import type { LiveGrant, ReceivedFrame } from '../src/index.js';
import { toB64u } from '../src/bytes.js';
const until = async (cond: () => boolean, ms = 10_000) => {
const t = Date.now();
while (!cond()) {
if (Date.now() - t > ms) throw new Error('timed out');
await new Promise((r) => setTimeout(r, 10));
}
};
/** N relays sharing pins and a locator, as N instances behind one hostname would. */
function cluster(n: number, locator: LivePublisherLocator = new MemoryLivePublisherLocator()) {
const pins = new MemoryLivePinStore();
return Array.from({ length: n }, () => {
let app: Hono | null = null;
const server = Bun.serve({ port: 0, fetch: (req, srv) => app!.fetch(req, { server: srv }), websocket });
const base = `http://localhost:${server.port}`;
const relay = createLiveRelay({ pins, mesh: { self: base, locator, pollMs: 50, heartbeatMs: 200, staleMs: 1000 } });
app = new Hono().route('/', relay.app);
return { relay, server, base };
});
}
const chunks = (frames: ReceivedFrame[]) =>
frames.filter((f) => f.content.type === 'chunk').map((f) => (f.content as { bytes: Uint8Array }).bytes[0]!);
describe('live channels across relays (mesh)', () => {
test('publisher on A, viewers on B: waiting first, then live; late join from A\'s backlog; each frame once', async () => {
const [a, b] = cluster(2) as [ReturnType<typeof cluster>[0], ReturnType<typeof cluster>[0]];
try {
const pub = new LivePublisher({ meta: { name: 'cam' } });
const client = new LivePublishClient({ relay: a.base, publisher: pub, readToken: new Uint8Array(32).fill(7) });
await client.whenReady();
const grant = parseGrant(encodeGrant(client.grant('oldest'))) as LiveGrant;
// A viewer on B before anything is sent: B follows A at once, and tells the viewer it is live.
const early: ReceivedFrame[] = [];
const states: string[] = [];
const v1 = new LiveWatchClient(grant, { url: `${b.base.replace('http', 'ws')}/v1/live/${grant.url!.split('/').pop()}`, onFrame: (f) => void early.push(f), onState: (st) => void states.push(st) });
await until(() => b.relay.stats().viewers === 1 && a.relay.stats().viewers === 1);
await until(() => states.at(-1) === 'live');
await client.send({ type: 'init', mime: 'video/webm; codecs="vp8"', bytes: new Uint8Array([0xaa]) }, { sticky: true });
for (let i = 0; i < 30; i++) await client.send({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: i % 10 === 0 });
await until(() => chunks(early).length === 30);
expect(chunks(early)).toEqual(Array.from({ length: 30 }, (_, i) => i));
expect(early.filter((f) => f.content.type === 'init').length).toBe(1);
// A late viewer on B gets B's copy of the backlog: init, then from a keyframe.
const late: ReceivedFrame[] = [];
const v2 = new LiveWatchClient(grant, { url: `${b.base.replace('http', 'ws')}/v1/live/${grant.url!.split('/').pop()}`, onFrame: (f) => void late.push(f) });
await until(() => chunks(late).length >= 10);
expect(late[0]!.content.type).toBe('init');
expect(chunks(late)[0]! % 10).toBe(0);
// Still one subscription from B to A, however many watch on B.
expect(a.relay.stats().viewers).toBe(1);
v1.close();
v2.close();
// Nobody left on B: B stops following A.
await until(() => a.relay.stats().viewers === 0);
client.close();
} finally {
for (const r of [a, b]) {
r.relay.stop();
r.server.stop(true);
}
}
}, 30_000);
test('the publisher moves from A to B; viewers on both follow it', async () => {
const loc = new MemoryLivePublisherLocator();
const [a, b] = cluster(2, loc) as [ReturnType<typeof cluster>[0], ReturnType<typeof cluster>[0]];
try {
const pub = new LivePublisher({ meta: { name: 'logs' } });
const c1 = new LivePublishClient({ relay: a.base, publisher: pub, readToken: new Uint8Array(32).fill(9) });
await c1.whenReady();
const grant = parseGrant(encodeGrant(c1.grant('oldest'))) as LiveGrant;
const id = grant.url!.split('/').pop()!;
const onA: ReceivedFrame[] = [];
const onB: ReceivedFrame[] = [];
const va = new LiveWatchClient(grant, { url: `${a.base.replace('http', 'ws')}/v1/live/${id}`, onFrame: (f) => void onA.push(f) });
const vb = new LiveWatchClient(grant, { url: `${b.base.replace('http', 'ws')}/v1/live/${id}`, onFrame: (f) => void onB.push(f) });
await until(() => a.relay.stats().viewers === 2); // va, and B following
for (let i = 0; i < 5; i++) await c1.send({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: true });
await until(() => chunks(onA).length === 5 && chunks(onB).length === 5);
// The publisher reconnects to B (a deploy moved it). Same publisher, same chain.
// B stops following A; A now follows B, and B's backlog (frames that came
// from A) is replayed to it — A's viewer must still see each frame once.
c1.close();
const c2 = new LivePublishClient({ relay: b.base, publisher: pub, readToken: new Uint8Array(32).fill(9) });
await c2.whenReady();
// A finds the publisher on B within a poll. (What is sent before that
// reaches A's viewers as B's backlog holds it: from a keyframe, like a late join.)
await until(() => b.relay.stats().viewers === 2);
for (let i = 5; i < 10; i++) await c2.send({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: true });
await until(() => chunks(onA).length === 10 && chunks(onB).length === 10);
expect(chunks(onA)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
expect(chunks(onB)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
va.close();
vb.close();
c2.close();
} finally {
for (const r of [a, b]) {
r.relay.stop();
r.server.stop(true);
}
}
}, 30_000);
test('a peer that forges frames gets nothing through: every frame is verified against the pin', async () => {
const locator = new MemoryLivePublisherLocator();
const [b] = cluster(1, locator) as [ReturnType<typeof cluster>[0]];
// An impostor "relay" that the locator points at, sending frames from another key.
const forged: Uint8Array[] = [];
let asked = 0;
const evil = Bun.serve({
port: 0,
fetch: (req, srv) => (srv.upgrade(req) ? undefined : new Response('no', { status: 400 })),
websocket: {
message(ws) {
asked++;
for (const f of forged) ws.send(f);
},
},
});
try {
const pub = new LivePublisher({ meta: { name: 'real' } });
const real = new LivePublishClient({ relay: b.base, publisher: pub, readToken: new Uint8Array(32).fill(3) });
await real.whenReady();
real.close();
await until(() => b.relay.stats().channels === 1);
const grant = parseGrant(encodeGrant(real.grant('oldest'))) as LiveGrant;
const id = grant.url!.split('/').pop()!;
// Frames for this channel id, signed by the forger's key.
const fpub = new LivePublisher({ channelId: pub.channelId });
for (let i = 0; i < 3; i++) forged.push(await fpub.frame({ type: 'chunk', bytes: new Uint8Array([66]) }, { keyframe: true }));
await locator.claim(toB64u(pub.channelId), `http://localhost:${evil.port}`, Date.now());
const got: ReceivedFrame[] = [];
const errors: Error[] = [];
const v = new LiveWatchClient(grant, { url: `${b.base.replace('http', 'ws')}/v1/live/${id}`, onFrame: (f) => void got.push(f), onError: (e) => void errors.push(e) });
await until(() => asked >= 2); // B followed the impostor, was refused frames, and tried again
expect(got.filter((f) => f.content.type === 'chunk')).toEqual([]);
expect(b.relay.stats().framesIn).toBe(0);
v.close();
} finally {
b.relay.stop();
b.server.stop(true);
evil.stop(true);
}
}, 30_000);
test('the publisher comes back with a new read token: viewers with the new grant get in on the other relay too', async () => {
const [a, b] = cluster(2) as [ReturnType<typeof cluster>[0], ReturnType<typeof cluster>[0]];
try {
const pub = new LivePublisher();
const c1 = new LivePublishClient({ relay: a.base, publisher: pub, readToken: new Uint8Array(32).fill(1) });
await c1.whenReady();
const g1 = parseGrant(encodeGrant(c1.grant('oldest'))) as LiveGrant;
const id = g1.url!.split('/').pop()!;
const onB = `${b.base.replace('http', 'ws')}/v1/live/${id}`;
const s1: string[] = [];
const v1 = new LiveWatchClient(g1, { url: onB, onFrame: () => {}, onState: (st) => void s1.push(st) });
await until(() => s1.at(-1) === 'live');
v1.close();
c1.close();
await until(() => a.relay.stats().viewers === 0);
// Same channel, new read token (old links revoked): B must not judge by the pin it read first.
const c2 = new LivePublishClient({ relay: a.base, publisher: pub, readToken: new Uint8Array(32).fill(2) });
await c2.whenReady();
const g2 = parseGrant(encodeGrant(c2.grant('oldest'))) as LiveGrant;
const got: ReceivedFrame[] = [];
const errs: Error[] = [];
const v2 = new LiveWatchClient(g2, { url: onB, onFrame: (f) => void got.push(f), onError: (e) => void errs.push(e) });
await until(() => a.relay.stats().viewers === 1 || errs.length > 0);
expect(errs).toEqual([]);
await c2.send({ type: 'chunk', bytes: new Uint8Array([42]) }, { keyframe: true });
await until(() => chunks(got).includes(42));
// And the old token no longer opens it on B either.
const e1: Error[] = [];
const old = new LiveWatchClient(g1, { url: onB, onFrame: () => {}, onError: (e) => void e1.push(e) });
await until(() => e1.length > 0);
old.close();
v2.close();
c2.close();
} finally {
for (const r of [a, b]) {
r.relay.stop();
r.server.stop(true);
}
}
}, 30_000);
test('viewers hear when the publisher arrives and leaves (and the relay notices it left)', async () => {
const relay = createLiveRelay({ pins: new MemoryLivePinStore() });
const app = new Hono().route('/', relay.app);
const server = Bun.serve({ port: 0, fetch: (req, srv) => app.fetch(req, { server: srv }), websocket });
try {
const pub = new LivePublisher();
const c1 = new LivePublishClient({ relay: `http://localhost:${server.port}`, publisher: pub, readToken: new Uint8Array(32).fill(4) });
await c1.whenReady();
const grant = parseGrant(encodeGrant(c1.grant('oldest'))) as LiveGrant;
c1.close();
await until(() => relay.stats().channels === 1);
await new Promise((r) => setTimeout(r, 50));
// Joins an empty channel: waiting. The publisher comes back: live. It leaves: waiting.
// (Hono gives each event its own WSContext; a relay comparing them by identity never saw a publisher leave.)
const states: string[] = [];
const v = new LiveWatchClient(grant, { onFrame: () => {}, onState: (st) => void states.push(st) });
await until(() => states.at(-1) === 'waiting');
const c2 = new LivePublishClient({ relay: `http://localhost:${server.port}`, publisher: pub, readToken: new Uint8Array(32).fill(4) });
await c2.whenReady();
await until(() => states.at(-1) === 'live');
c2.close();
await until(() => states.at(-1) === 'waiting');
v.close();
} finally {
relay.stop();
server.stop(true);
}
});
});