Files
Shade/packages/shade-storage-postgres/tests/postgres-media.test.ts
Sterister f1b4c1ade1 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>
2026-10-18 22:44:19 +02:00

223 lines
11 KiB
TypeScript

/**
* Shared media backend: the Postgres index and pins, and two relays over one
* bucket. Needs PostgreSQL (SHADE_TEST_PG_URL); the relay test also an S3
* API (SHADE_TEST_S3_URL, a bucket that may be written to):
*
* docker run -d --rm -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=test postgres:16-alpine
* docker run -d --rm -p 127.0.0.1:58333:8333 chrislusf/seaweedfs server -s3 -dir=/data
* SHADE_TEST_PG_URL=postgres://postgres:test@127.0.0.1:55432/postgres \
* SHADE_TEST_S3_URL=http://key:secret@127.0.0.1:58333/shade-media-test bun test postgres-media
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import postgres, { type Sql } from 'postgres';
import { Hono } from 'hono';
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, 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;
const rec = (id: string, owner: string, size: number, createdAt = 1): IndexedMedia => ({
id,
owner,
size,
readTokenHash: null,
key: `objects/${id}/${'00'.repeat(16)}.smf`,
createdAt,
});
const hexId = (n: number) => n.toString(16).padStart(32, '0');
describe.skipIf(PG_URL === undefined)('Postgres media index and live pins', () => {
let sql: Sql;
beforeAll(async () => {
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();
});
test('records: insert once, sizes past 2^31, owner sums, newest first, remove returns the key', async () => {
const index = await PostgresMediaIndex.fromClient(sql);
const big = 40 * 1024 ** 3; // a 40 GiB film
await index.insert(rec(hexId(1), 'alice', big, 10));
await index.insert(rec(hexId(2), 'alice', 5, 20));
await index.insert(rec(hexId(3), 'bob', 7, 30));
await expect(index.insert(rec(hexId(1), 'mallory', 1))).rejects.toBeInstanceOf(MediaExistsError);
expect((await index.get(hexId(1)))!.owner).toBe('alice');
expect(await index.usage('alice')).toBe(big + 5);
expect(await index.totalBytes()).toBe(big + 12);
expect((await index.list('alice')).map((r) => r.id)).toEqual([hexId(2), hexId(1)]);
expect('key' in (await index.list('alice'))[0]!).toBe(false);
expect((await index.remove(hexId(1)))!.key).toBe(rec(hexId(1), 'alice', 1).key);
expect(await index.remove(hexId(1))).toBeNull();
expect(await index.usage('alice')).toBe(5);
});
test('racing inserts of one id over separate connections: exactly one wins', async () => {
const pools = Array.from({ length: 8 }, () => postgres(PG_URL!, { max: 2 }));
try {
const indexes = await Promise.all(pools.map((p) => PostgresMediaIndex.fromClient(p)));
const results = await Promise.allSettled(indexes.flatMap((ix, i) => [0, 1, 2].map((j) => ix.insert(rec(hexId(99), `o${i}-${j}`, 1)))));
expect(results.filter((r) => r.status === 'fulfilled').length).toBe(1);
expect(results.filter((r) => r.status === 'rejected' && r.reason instanceof MediaExistsError).length).toBe(23);
} finally {
await Promise.all(pools.map((p) => p.end()));
}
});
test('pins: refreshed by their own key, refused to another, even when two relays race to create one', async () => {
const pins = await PostgresLivePinStore.fromClient(sql, 1000);
const pin = { channelId: 'ch1', signingKey: 'K1', readTokenHash: 'h', pinnedAt: 100, lastSeen: 100 };
await pins.put(pin);
await pins.put({ ...pin, lastSeen: 150 });
expect((await pins.get('ch1'))!.lastSeen).toBe(150);
await expect(pins.put({ ...pin, signingKey: 'K2' })).rejects.toBeInstanceOf(LivePinTakenError);
expect((await pins.get('ch1'))!.signingKey).toBe('K1');
const pools = [postgres(PG_URL!), postgres(PG_URL!)];
try {
const [a, b] = await Promise.all(pools.map((p) => PostgresLivePinStore.fromClient(p)));
for (let i = 0; i < 20; i++) {
const id = `race-${i}`;
const r = await Promise.allSettled([
a!.put({ ...pin, channelId: id, signingKey: 'A', lastSeen: 160 }),
b!.put({ ...pin, channelId: id, signingKey: 'B', lastSeen: 160 }),
]);
expect(r.filter((x) => x.status === 'fulfilled').length).toBe(1);
}
} finally {
await Promise.all(pools.map((p) => p.end()));
}
// Idle past the TTL: released, and the channel may be pinned anew.
await pins.put({ ...pin, channelId: 'other', lastSeen: 5000 });
expect(await pins.get('ch1')).toBeNull();
await pins.put({ ...pin, signingKey: 'K2', lastSeen: 5000 });
expect((await pins.get('ch1'))!.signingKey).toBe('K2');
});
});
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)}`;
const s3Url = `${S3_URL!.replace(/\/$/, '')}/${prefix}`;
// Separate backends, separate pools: as two containers would be.
const backends = await Promise.all([0, 1].map(() => createSharedMediaBackend({ s3Url, pgUrl: PG_URL! })));
const servers = backends.map((be) => {
const svc = createMediaService({ owners: 'any', store: be.store, pins: be.pins });
const app = new Hono().route('/', svc.app);
const server = Bun.serve({ port: 0, fetch: (req) => app.fetch(req), maxRequestBodySize: 1024 ** 3 });
return { server, svc, base: `http://localhost:${server.port}` };
});
const [a, b] = servers as [(typeof servers)[0], (typeof servers)[0]];
try {
const owner = OwnerKey.generate();
const plain = new Uint8Array(20 * 1024 * 1024 + 99).map((_, i) => (i * 7) & 0xff);
const grant = await new MediaClient(a.base, owner).uploadBytes(plain, { meta: { name: 'Delt.mkv' } });
const r = await openGrant(grant, { url: grant.url!.replace(a.base, b.base) });
expect(r.meta.name).toBe('Delt.mkv');
expect(await r.read(17 * 1024 * 1024, 3 * 1024 * 1024 + 99)).toEqual(plain.subarray(17 * 1024 * 1024));
const { bytes, result } = await sealMediaBytes(new Uint8Array(2 * MIN_SEGMENT_SIZE).fill(3));
const race = await Promise.allSettled([a, b].map((s) => new MediaClient(s.base, owner).putSealed(result, bytes)));
expect(race.filter((x) => x.status === 'fulfilled').length).toBe(1);
const listed = await new MediaClient(b.base, owner).list();
expect(listed.items.length).toBe(2);
expect(listed.usage).toBe(listed.items.reduce((n, i) => n + i.size, 0));
expect(await new MediaClient(b.base, owner).delete(grant.mediaId)).toBe(true);
expect(await new MediaClient(a.base, owner).delete(result.mediaId)).toBe(true);
expect(await new MediaClient(a.base, owner).list().then((l) => l.items.length)).toBe(0);
// Nothing left in the bucket, and nothing for the sweeper.
const { bucket, prefix: p } = S3Bucket.fromUrl(s3Url);
expect((await bucket.list(`${p}objects/`)).objects).toEqual([]);
expect(await backends[0]!.sweep()).toEqual({ objects: 0, uploads: 0 });
} finally {
for (const s of servers) {
s.server.stop(true);
s.svc.stop();
}
await Promise.all(backends.map((be) => be.close()));
}
}, 120_000);
test('a bucket it cannot use is refused at start, not at the first upload', async () => {
const u = new URL(S3_URL!);
u.password = 'wrong-secret';
await expect(createSharedMediaBackend({ s3Url: u.toString(), pgUrl: PG_URL! })).rejects.toThrow(/403|Access|Signature/);
});
});