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:
@@ -314,4 +314,11 @@ export async function ensureMediaServerTables(sql: Sql): Promise<void> {
|
||||
CREATE INDEX IF NOT EXISTS shade_live_pins_seen_idx
|
||||
ON shade_live_pins(last_seen)
|
||||
`;
|
||||
await sql`
|
||||
CREATE TABLE IF NOT EXISTS shade_live_publishers (
|
||||
channel_id TEXT PRIMARY KEY,
|
||||
relay_url TEXT NOT NULL,
|
||||
seen_at BIGINT NOT NULL
|
||||
)
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ export { PostgresPrekeyStore } from './postgres-prekey-store.js';
|
||||
export { PostgresInboxStore } from './postgres-inbox-store.js';
|
||||
export { PostgresKTLogStore } from './postgres-kt-store.js';
|
||||
export { PostgresBlobStore } from './postgres-blob-store.js';
|
||||
export { PostgresMediaIndex, PostgresLivePinStore } from './postgres-media-store.js';
|
||||
export { PostgresMediaIndex, PostgresLivePinStore, PostgresLivePublisherLocator } from './postgres-media-store.js';
|
||||
export { createSharedMediaBackend } from './shared-media.js';
|
||||
export type { SharedMediaBackend } from './shared-media.js';
|
||||
export {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import postgres, { type Sql } from 'postgres';
|
||||
import { LivePinTakenError, MediaExistsError } from '@shade/media/server';
|
||||
import type { IndexedMedia, LivePin, LivePinStore, MediaIndex, MediaRecord } from '@shade/media/server';
|
||||
import type { IndexedMedia, LivePin, LivePinStore, LivePublisherLocator, MediaIndex, MediaRecord } from '@shade/media/server';
|
||||
import { ensureMediaServerTables } from './ensure-tables.js';
|
||||
|
||||
// "relation already exists, skipping" on every start is not news.
|
||||
@@ -158,3 +158,36 @@ export class PostgresLivePinStore implements LivePinStore {
|
||||
if (rows.length === 0) throw new LivePinTakenError(pin.channelId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Which relay holds each live channel's publisher, so relays sharing pins
|
||||
* can follow one another (`LiveRelayOptions.mesh`). One row per channel: a
|
||||
* channel's publisher is on one relay at a time, and the newest claim wins.
|
||||
*/
|
||||
export class PostgresLivePublisherLocator implements LivePublisherLocator {
|
||||
private constructor(private readonly sql: Sql) {}
|
||||
|
||||
static async fromClient(sql: Sql): Promise<PostgresLivePublisherLocator> {
|
||||
await ensureMediaServerTables(sql);
|
||||
return new PostgresLivePublisherLocator(sql);
|
||||
}
|
||||
|
||||
async claim(channelId: string, relayUrl: string, at: number): Promise<void> {
|
||||
await this.sql`
|
||||
INSERT INTO shade_live_publishers (channel_id, relay_url, seen_at)
|
||||
VALUES (${channelId}, ${relayUrl}, ${at})
|
||||
ON CONFLICT (channel_id) DO UPDATE SET relay_url = EXCLUDED.relay_url, seen_at = EXCLUDED.seen_at
|
||||
`;
|
||||
}
|
||||
|
||||
async release(channelId: string, relayUrl: string): Promise<void> {
|
||||
await this.sql`DELETE FROM shade_live_publishers WHERE channel_id = ${channelId} AND relay_url = ${relayUrl}`;
|
||||
}
|
||||
|
||||
async find(channelId: string, freshAfter: number): Promise<string | null> {
|
||||
const rows = await this.sql<{ relay_url: string }[]>`
|
||||
SELECT relay_url FROM shade_live_publishers WHERE channel_id = ${channelId} AND seen_at > ${freshAfter}
|
||||
`;
|
||||
return rows[0]?.relay_url ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import postgres from 'postgres';
|
||||
import { ObjectMediaStore, S3Bucket } from '@shade/media/server';
|
||||
import type { LivePinStore, MediaStore } from '@shade/media/server';
|
||||
import { PostgresLivePinStore, PostgresMediaIndex } from './postgres-media-store.js';
|
||||
import type { LivePinStore, LivePublisherLocator, MediaStore } from '@shade/media/server';
|
||||
import { PostgresLivePinStore, PostgresLivePublisherLocator, PostgresMediaIndex } from './postgres-media-store.js';
|
||||
|
||||
export interface SharedMediaBackend {
|
||||
store: MediaStore;
|
||||
pins: LivePinStore;
|
||||
/** Where each live channel's publisher is, for relays that follow one another. */
|
||||
locator: LivePublisherLocator;
|
||||
/** Where the bytes go, for logs — no credentials. */
|
||||
describe: string;
|
||||
/** Reclaim unreferenced objects and dead uploads; safe on every instance at once. */
|
||||
@@ -26,6 +28,7 @@ export async function createSharedMediaBackend(opts: { s3Url: string; pgUrl: str
|
||||
try {
|
||||
const index = await PostgresMediaIndex.fromClient(sql);
|
||||
const pins = await PostgresLivePinStore.fromClient(sql);
|
||||
const locator = await PostgresLivePublisherLocator.fromClient(sql);
|
||||
const store = new ObjectMediaStore(bucket, index, { prefix });
|
||||
// Fail at start, not at the first upload: a bucket that is not there, or
|
||||
// credentials it refuses, show up here.
|
||||
@@ -33,6 +36,7 @@ export async function createSharedMediaBackend(opts: { s3Url: string; pgUrl: str
|
||||
return {
|
||||
store,
|
||||
pins,
|
||||
locator,
|
||||
describe: `s3 ${new URL(opts.s3Url).host}/${bucket.bucket}/${prefix}`,
|
||||
sweep: () => store.sweep(),
|
||||
close: () => sql.end(),
|
||||
|
||||
@@ -11,10 +11,12 @@
|
||||
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
|
||||
import postgres, { type Sql } from 'postgres';
|
||||
import { Hono } from 'hono';
|
||||
import { createMediaService, LivePinTakenError, MediaExistsError, S3Bucket } from '@shade/media/server';
|
||||
import { createMediaService, LivePinTakenError, MediaExistsError, MemoryMediaStore, S3Bucket } from '@shade/media/server';
|
||||
import type { IndexedMedia } from '@shade/media/server';
|
||||
import { MediaClient, OwnerKey, openGrant, sealMediaBytes, MIN_SEGMENT_SIZE } from '@shade/media';
|
||||
import { createSharedMediaBackend, PostgresLivePinStore, PostgresMediaIndex } from '../src/index.js';
|
||||
import { MediaClient, OwnerKey, openGrant, sealMediaBytes, MIN_SEGMENT_SIZE, LivePublisher, LivePublishClient, LiveWatchClient, encodeGrant, parseGrant } from '@shade/media';
|
||||
import type { LiveGrant, ReceivedFrame } from '@shade/media';
|
||||
import { websocket } from 'hono/bun';
|
||||
import { createSharedMediaBackend, PostgresLivePinStore, PostgresLivePublisherLocator, PostgresMediaIndex } from '../src/index.js';
|
||||
|
||||
const PG_URL = process.env.SHADE_TEST_PG_URL;
|
||||
const S3_URL = process.env.SHADE_TEST_S3_URL;
|
||||
@@ -35,6 +37,7 @@ describe.skipIf(PG_URL === undefined)('Postgres media index and live pins', () =
|
||||
sql = postgres(PG_URL!);
|
||||
await sql`DROP TABLE IF EXISTS shade_media_objects`;
|
||||
await sql`DROP TABLE IF EXISTS shade_live_pins`;
|
||||
await sql`DROP TABLE IF EXISTS shade_live_publishers`;
|
||||
});
|
||||
afterAll(async () => {
|
||||
await sql.end();
|
||||
@@ -101,6 +104,72 @@ describe.skipIf(PG_URL === undefined)('Postgres media index and live pins', () =
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(PG_URL === undefined)('Postgres live publisher locator', () => {
|
||||
test('newest claim wins, release only removes its own, stale claims are not found', async () => {
|
||||
const sql = postgres(PG_URL!, { onnotice: () => {} });
|
||||
try {
|
||||
const loc = await PostgresLivePublisherLocator.fromClient(sql);
|
||||
await loc.claim('c', 'http://a', 1000);
|
||||
expect(await loc.find('c', 0)).toBe('http://a');
|
||||
await loc.claim('c', 'http://b', 2000);
|
||||
await loc.release('c', 'http://a'); // a late release from the old relay
|
||||
expect(await loc.find('c', 0)).toBe('http://b');
|
||||
expect(await loc.find('c', 2000)).toBeNull(); // not refreshed since: a dead relay
|
||||
await loc.release('c', 'http://b');
|
||||
expect(await loc.find('c', 0)).toBeNull();
|
||||
} finally {
|
||||
await sql.end();
|
||||
}
|
||||
});
|
||||
|
||||
test('two media services over Postgres: publish on one, watch on the other', async () => {
|
||||
const pools = [postgres(PG_URL!, { onnotice: () => {} }), postgres(PG_URL!, { onnotice: () => {} })];
|
||||
const relays = await Promise.all(
|
||||
pools.map(async (p) => {
|
||||
let app: Hono | null = null;
|
||||
const server = Bun.serve({ port: 0, fetch: (req, srv) => app!.fetch(req, { server: srv }), websocket });
|
||||
const self = `http://localhost:${server.port}`;
|
||||
const svc = createMediaService({
|
||||
owners: 'any',
|
||||
store: new MemoryMediaStore(),
|
||||
pins: await PostgresLivePinStore.fromClient(p),
|
||||
live: { mesh: { self, locator: await PostgresLivePublisherLocator.fromClient(p), pollMs: 100 } },
|
||||
});
|
||||
app = new Hono().route('/', svc.app);
|
||||
return { server, svc, self };
|
||||
}),
|
||||
);
|
||||
const [a, b] = relays as [(typeof relays)[0], (typeof relays)[0]];
|
||||
try {
|
||||
const pub = new LivePublisher({ meta: { name: 'logg' } });
|
||||
const c = new LivePublishClient({ relay: a.self, publisher: pub, readToken: new Uint8Array(32).fill(5) });
|
||||
await c.whenReady();
|
||||
const grant = parseGrant(encodeGrant(c.grant('oldest'))) as LiveGrant;
|
||||
const got: ReceivedFrame[] = [];
|
||||
const v = new LiveWatchClient(grant, { url: grant.url!.replace(a.self.replace('http', 'ws'), b.self.replace('http', 'ws')), onFrame: (f) => void got.push(f) });
|
||||
const deadline = Date.now() + 10_000;
|
||||
while (b.svc.relay.stats().viewers < 1 || a.svc.relay.stats().viewers < 1) {
|
||||
if (Date.now() > deadline) throw new Error('B never followed A');
|
||||
await Bun.sleep(20);
|
||||
}
|
||||
for (let i = 0; i < 5; i++) await c.send({ type: 'text', text: `linje ${i}` }, { keyframe: true });
|
||||
while (got.length < 5) {
|
||||
if (Date.now() > deadline) throw new Error(`got ${got.length} of 5`);
|
||||
await Bun.sleep(20);
|
||||
}
|
||||
expect(got.map((f) => (f.content as { text: string }).text)).toEqual([0, 1, 2, 3, 4].map((i) => `linje ${i}`));
|
||||
v.close();
|
||||
c.close();
|
||||
} finally {
|
||||
for (const r of relays) {
|
||||
r.svc.stop();
|
||||
r.server.stop(true);
|
||||
}
|
||||
await Promise.all(pools.map((p) => p.end()));
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
describe.skipIf(PG_URL === undefined || S3_URL === undefined)('two relays, one shared backend', () => {
|
||||
test('upload on one relay, play, list and delete on the other; a race for one id is decided once', async () => {
|
||||
const prefix = `relay-test-${Date.now().toString(36)}`;
|
||||
|
||||
Reference in New Issue
Block a user