feat(media): one library for several relays — films in S3, records and live pins in Postgres
FileMediaStore ties a library to one disk on one machine. SHADE_MEDIA_S3_URL + SHADE_MEDIA_PG_URL (or `media serve --s3 --pg`) put sealed bytes in any S3 bucket and the records every instance must agree on in Postgres. - ObjectMediaStore: each upload streams as multipart to its own object key; the commit is an INSERT whose primary key admits one record per id, so racing uploads on any instances are decided once and the loser deletes its object. Delete drops the record first. sweep() reclaims unreferenced objects and dead multipart uploads past a 24 h grace. - S3Bucket: Shade's own SigV4 client. Bun 1.3.5's S3Client buffers a whole upload (512 MiB in, 543 MiB RSS), end(error) does not abort, and slice(0, n).stream() returned the whole object. Here: at most three parts in memory (512 MiB through, 11 MiB RSS), payload-hashed signatures, AbortMultipartUpload, ranged reads checked for length. - PostgresMediaIndex, PostgresLivePinStore, createSharedMediaBackend in @shade/storage-postgres. LivePinStore.put now refuses a key change (LivePinTakenError) in every store, atomically in Postgres. - The container logs a backend it cannot use and runs on without media. Verified: SigV4 reproduces AWS's published example signature; SeaweedFS with signature checking accepts it and refuses a wrong secret (403); Postgres 16: racing inserts over 8 pools (1 of 24 wins), racing pins, BIGINT sizes; two relays over one backend; CLI relays behind a round-robin proxy: upload, bit-identical download, Chromium playback seeked to 24 s with ranges served by both; the bucket holds no plaintext, name or MP4 marker. Suites: media 87, storage-postgres 18, server 55, cli 15, all green. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
153
packages/shade-storage-postgres/tests/postgres-media.test.ts
Normal file
153
packages/shade-storage-postgres/tests/postgres-media.test.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* 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, 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';
|
||||
|
||||
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`;
|
||||
});
|
||||
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 || 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/);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user