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:
2026-10-18 22:28:58 +02:00
parent 01f8471fb5
commit aaec92429d
24 changed files with 1464 additions and 63 deletions

View File

@@ -110,7 +110,7 @@ const err = (s: string) => process.stderr.write(`${s}\n`);
// ─── media ───────────────────────────────────────────────────
async function mediaServe(flags: Flags): Promise<number> {
async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise<number> {
const { websocket } = await import('hono/bun');
const { createMediaService, parseOwners, mediaMaxRequestBody } = await import('./server.js');
const dir = str(flags, 'dir') ?? process.env.SHADE_MEDIA_DIR ?? './shade-media-data';
@@ -120,7 +120,23 @@ async function mediaServe(flags: Flags): Promise<number> {
const own = (await loadOwnerKey()).id;
const listed = parseOwners(str(flags, 'owners') ?? process.env.SHADE_MEDIA_OWNERS);
const owners = flags.open === true || listed === 'any' ? 'any' : [own, ...listed];
const svc = createMediaService({ dir, owners, dev: flags.dev === true });
// --s3 + --pg: the library several relays share (as SHADE_MEDIA_S3_URL/_PG_URL in the container).
const s3Url = str(flags, 's3') ?? process.env.SHADE_MEDIA_S3_URL;
const pgUrl = str(flags, 'pg') ?? process.env.SHADE_MEDIA_PG_URL;
let svc: import('./server.js').MediaService;
let where = dir;
if (s3Url !== undefined) {
if (pgUrl === undefined) throw new UsageError('--s3 needs --pg: the bucket holds the bytes, Postgres the records relays share');
if (hooks.sharedBackend === undefined) throw new UsageError('--s3/--pg are not available in this build (no Postgres support)');
const backend = await hooks.sharedBackend({ s3Url, pgUrl });
svc = createMediaService({ owners, store: backend.store, pins: backend.pins, dev: flags.dev === true });
where = backend.describe;
const sweep = () => backend.sweep().catch((e: unknown) => err(`! media sweep: ${(e as Error).message}`));
setTimeout(sweep, 60_000).unref();
setInterval(sweep, 6 * 3600_000).unref();
} else {
svc = createMediaService({ dir, owners, dev: flags.dev === true });
}
svc.app.get('/health', (c) => c.json({ ok: true, live: svc.relay.stats() }));
const server = Bun.serve({
port,
@@ -131,7 +147,7 @@ async function mediaServe(flags: Flags): Promise<number> {
// Every route here bounds its own body; the 128 MiB default would refuse films.
maxRequestBodySize: mediaMaxRequestBody(),
});
err(`shade media: serving on http://localhost:${server.port} (data in ${dir})`);
err(`shade media: serving on http://localhost:${server.port} (data in ${where})`);
err(owners === 'any' ? 'open relay: any key may upload and publish' : `owners: ${owners.join(', ')}`);
await new Promise(() => {});
return 0;
@@ -592,8 +608,11 @@ async function liveWatch(pos: string[]): Promise<number> {
export const MEDIA_HELP = `
media serve [--port 3910] [--dir ./shade-media-data] [--owners k1,k2] [--open]
[--s3 https://key:secret@host/bucket[/prefix] --pg postgres://…]
Run a media relay: sealed store, live relay, watch page.
Only this machine's key (and --owners) may upload/publish.
--s3/--pg: films in a bucket, records in Postgres, so
several relays serve one library.
media whoami Print this machine's owner key (to add to a relay's --owners)
media put <file|dir>… --server URL [--album T] [--name N] [--mime M] [--web] [--public] [--json]
Seal a film/video/image/song, upload it, print a watch link.
@@ -619,14 +638,27 @@ export const MEDIA_HELP = `
`;
/** Entry for `shade media …` / `shade live …`. Returns the exit code. */
export async function runMediaCli(group: 'media' | 'live', argv: string[]): Promise<number> {
/**
* What the CLI cannot reach on its own. `@shade/media` does not depend on
* Postgres; the `shade` binary does, and hands the shared backend in.
*/
export interface MediaCliHooks {
sharedBackend?: (o: { s3Url: string; pgUrl: string }) => Promise<{
store: import('./server.js').MediaStore;
pins: import('./server.js').LivePinStore;
describe: string;
sweep(): Promise<unknown>;
}>;
}
export async function runMediaCli(group: 'media' | 'live', argv: string[], hooks: MediaCliHooks = {}): Promise<number> {
const [sub, ...rest] = argv;
const { pos, flags } = parseArgs(rest);
try {
if (group === 'media') {
switch (sub) {
case 'serve':
return await mediaServe(flags);
return await mediaServe(flags, hooks);
case 'whoami':
out((await loadOwnerKey()).id);
return 0;