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[0], ReturnType[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[0], ReturnType[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[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[0], ReturnType[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); } }); });