/** * 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/); }); });