diff --git a/.scaffold/branches/streaming.md b/.scaffold/branches/streaming.md index 30943d6..9d1b25a 100644 --- a/.scaffold/branches/streaming.md +++ b/.scaffold/branches/streaming.md @@ -30,10 +30,11 @@ decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video - [x] Undertekster: `Film.no.srt` ved siden av filmen forsegles og følger filmen i dens meta; `` i nettleseren (språkvalg, SRT→VTT), ExoPlayer på Android, `media get` skriver dem tilbake - [x] `media put --web`: HEVC/AC3/DTS-filmer (som Chromium nekter) konverteres før forsegling, innebygde tekstundertekster blir spor; advarsel uten flagget - [x] Lokalt bibliotek: `media ls` med navn, `media link ` gir lenken igjen; kanonisk grant-koding (én grant = én lenke) +- [x] Delt mediebibliotek for flere relay-instanser: filmer i S3 (egen SigV4-klient, multipart med begrenset minne), poster og live-pinner i Postgres, feiing av foreldreløse objekter; verifisert mot SeaweedFS med signaturkontroll + Postgres 16, to relayer bak round-robin ## Neste - Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18) -- Postgres/S3-medielager +- Live-kanaler på tvers av instanser (i dag: rut `/v1/live/*` til én instans) ## Senere - Sanntidssamtaler (V5.0): SFrame-nøkler fra samme kjede over WebRTC Insertable Streams diff --git a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/09-shared-s3-postgres.png b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/09-shared-s3-postgres.png new file mode 100644 index 0000000..58f0abe Binary files /dev/null and b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/09-shared-s3-postgres.png differ diff --git a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt index 7edf3b1..8cb4b0b 100644 --- a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt +++ b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt @@ -6,3 +6,4 @@ 06 — Et album («Ferie 2026»): én lenke åpner film, video, lyd, bilde og et nøstet album; forhåndsvisningene dekrypteres i nettleseren, relayen ser bare én ugjennomsiktig fil til 07 — En forseglet film med Testfilm.no.srt og Testfilm.en.srt ved siden av: undertekstene følger filmen kryptert, og nettleseren velger norsk fordi den er satt til bokmål 08 — En ekte MKV-film med HEVC-video og AC3 5.1-lyd: Chromium nekter originalen («no supported streams»); med media put --web spiller den med lyd og den innebygde norske underteksten +09 — To relay-instanser bak en round-robin-lastbalanserer deler ett bibliotek (filmbytes i S3, poster i Postgres): opplastet via den ene, spilt og spolt til 24 s med Range-lesinger fra begge diff --git a/.scaffold/tasks.yaml b/.scaffold/tasks.yaml index b558e33..600eb3d 100644 --- a/.scaffold/tasks.yaml +++ b/.scaffold/tasks.yaml @@ -342,8 +342,8 @@ tasks: context: "packages/shade-media, docs/media.md, test-vectors/media.json, android/.../no/zyon/shade/media/" acceptance: "43 TS-tester + 9 Kotlin-vektortester grønne; film/live/bilde/lyd spilt i headless Chromium; benchmark i bench/media.chart.json." created: 2026-10-18 - updated: 2026-10-19 - completed_at: 2026-10-19 + updated: 2026-10-18 + completed_at: 2026-10-18 - id: media-fmp4-live title: "fMP4 (H.264/AAC) i live-splitteren" description: "Live-splitteren forstår i dag bare WebM; fMP4 gir H.264/AAC fra kameraer og OBS, og Safari." @@ -352,8 +352,8 @@ tasks: priority: medium assignee: claude branch: streaming - created: 2026-10-19 - updated: 2026-10-19 + created: 2026-10-18 + updated: 2026-10-18 completed_at: 2026-10-18 - id: media-android-exoplayer title: "Android-demo: ExoPlayer DataSource for forseglede filmer" @@ -370,17 +370,17 @@ tasks: done: true - text: "Installer og spill på dev-telefonen RFCN504DWJF — ikke tilkoblet ennå" done: false - created: 2026-10-19 - updated: 2026-10-19 + created: 2026-10-18 + updated: 2026-10-18 completed_at: null - id: media-durable-store - title: "Postgres/S3-medielager + deploy av media på relayen" - description: "FileMediaStore er diskbasert; flere relay-instanser trenger delt lager. Deploy krever SHADE_MEDIA_DIR + volum i compose." - status: todo - column: todo + title: "Postgres/S3-medielager for flere relay-instanser" + description: "Gjort: ObjectMediaStore (S3, egen SigV4-klient, multipart med begrenset minne) + PostgresMediaIndex/PostgresLivePinStore; SHADE_MEDIA_S3_URL/SHADE_MEDIA_PG_URL og media serve --s3 --pg. Gjenstår utenfor kortet: live-fan-out på tvers av instanser, og selve deployen (ikke bedt om)." + status: done + column: done priority: low assignee: any branch: streaming - created: 2026-10-19 - updated: 2026-10-19 - completed_at: null + created: 2026-10-18 + updated: 2026-10-18 + completed_at: 2026-10-18 diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ca5fbe..a18ee88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,16 @@ New package **`@shade/media`** — see `docs/media.md`. is copied, the rest becomes H.264/AAC, embedded text subtitles become subtitle tracks, all in one ffmpeg pass. Without the flag, `put` warns when ffprobe sees streams browsers will not play. +- **Shared media library.** `SHADE_MEDIA_S3_URL` + `SHADE_MEDIA_PG_URL` (or + `media serve --s3 --pg`): sealed films in any S3 bucket, records and live + pins in Postgres, so several relay instances serve one library. + `ObjectMediaStore` streams uploads as multipart with bounded memory, decides + racing uploads by the Postgres primary key, and sweeps orphaned objects and + dead multipart uploads. `S3Bucket` is a small SigV4 client of Shade's own + (Bun 1.3.5's `S3Client` buffers whole uploads). `PostgresMediaIndex`, + `PostgresLivePinStore`, `createSharedMediaBackend` in + `@shade/storage-postgres`. A live pin can no longer change key, even between + instances (`LivePinTakenError`). - **Library.** `media put` records each upload and its grant in `$XDG_CONFIG_HOME/shade/media-library.jsonl` (0600, append-only); `media ls` shows names, `media link ` prints a link again. Grants now diff --git a/bun.lock b/bun.lock index 0316e8c..016863b 100644 --- a/bun.lock +++ b/bun.lock @@ -18,7 +18,7 @@ }, "packages/shade-cli": { "name": "@shade/cli", - "version": "4.14.1", + "version": "4.15.0", "bin": { "shade": "src/cli.ts", }, @@ -29,6 +29,7 @@ "@shade/media": "workspace:*", "@shade/sdk": "workspace:*", "@shade/storage-encrypted": "workspace:*", + "@shade/storage-postgres": "workspace:*", "@shade/storage-sqlite": "workspace:*", "@shade/transport": "workspace:*", }, @@ -38,7 +39,7 @@ }, "packages/shade-core": { "name": "@shade/core", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/observability": "workspace:*", }, @@ -51,7 +52,7 @@ }, "packages/shade-crypto-web": { "name": "@shade/crypto-web", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@noble/curves": "^2.0.1", "@noble/hashes": "^2.0.1", @@ -61,7 +62,7 @@ }, "packages/shade-dashboard": { "name": "@shade/dashboard", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/widgets": "workspace:*", "react": "^19.0.0", @@ -76,7 +77,7 @@ }, "packages/shade-files": { "name": "@shade/files", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/crypto-web": "workspace:*", @@ -103,7 +104,7 @@ }, "packages/shade-inbox": { "name": "@shade/inbox", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/proto": "workspace:*", @@ -116,7 +117,7 @@ }, "packages/shade-inbox-server": { "name": "@shade/inbox-server", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/observability": "workspace:*", @@ -134,7 +135,7 @@ }, "packages/shade-key-transparency": { "name": "@shade/key-transparency", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@noble/hashes": "^2.0.1", "@shade/core": "workspace:*", @@ -146,7 +147,7 @@ }, "packages/shade-keychain": { "name": "@shade/keychain", - "version": "4.14.1", + "version": "4.15.0", }, "packages/shade-media": { "name": "@shade/media", @@ -159,7 +160,7 @@ }, "packages/shade-observability": { "name": "@shade/observability", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@noble/hashes": "^2.0.1", }, @@ -177,7 +178,7 @@ }, "packages/shade-observer": { "name": "@shade/observer", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/server": "workspace:*", @@ -189,14 +190,14 @@ }, "packages/shade-proto": { "name": "@shade/proto", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", }, }, "packages/shade-recovery": { "name": "@shade/recovery", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/crypto-web": "workspace:*", @@ -209,7 +210,7 @@ }, "packages/shade-sdk": { "name": "@shade/sdk", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/crypto-web": "workspace:*", @@ -240,7 +241,7 @@ }, "packages/shade-server": { "name": "@shade/server", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/inbox-server": "workspace:*", @@ -263,7 +264,7 @@ }, "packages/shade-storage-encrypted": { "name": "@shade/storage-encrypted", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@noble/hashes": "^2.0.1", "@shade/core": "workspace:*", @@ -285,7 +286,7 @@ }, "packages/shade-storage-indexeddb": { "name": "@shade/storage-indexeddb", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "idb": "^8.0.3", @@ -297,22 +298,24 @@ }, "packages/shade-storage-postgres": { "name": "@shade/storage-postgres", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/inbox-server": "workspace:*", "@shade/key-transparency": "workspace:*", + "@shade/media": "workspace:*", "@shade/server": "workspace:*", "drizzle-orm": "^0.45.2", "postgres": "^3.4.9", }, "devDependencies": { "@shade/crypto-web": "workspace:*", + "hono": "^4.12.18", }, }, "packages/shade-storage-sqlite": { "name": "@shade/storage-sqlite", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/crypto-web": "workspace:*", @@ -325,7 +328,7 @@ }, "packages/shade-streams": { "name": "@shade/streams", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@noble/hashes": "^2.0.1", "@shade/core": "workspace:*", @@ -337,7 +340,7 @@ }, "packages/shade-transfer": { "name": "@shade/transfer", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/crypto-web": "workspace:*", @@ -354,7 +357,7 @@ }, "packages/shade-transport": { "name": "@shade/transport", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/crypto-web": "workspace:*", @@ -365,7 +368,7 @@ }, "packages/shade-transport-bridge": { "name": "@shade/transport-bridge", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/server": "workspace:*", @@ -387,7 +390,7 @@ }, "packages/shade-transport-webrtc": { "name": "@shade/transport-webrtc", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/core": "workspace:*", "@shade/streams": "workspace:*", @@ -396,7 +399,7 @@ }, "packages/shade-vault": { "name": "@shade/vault", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@noble/hashes": "^2.0.1", "@shade/core": "workspace:*", @@ -409,7 +412,7 @@ }, "packages/shade-widgets": { "name": "@shade/widgets", - "version": "4.14.1", + "version": "4.15.0", "dependencies": { "@shade/recovery": "workspace:*", "@shade/sdk": "workspace:*", @@ -802,6 +805,8 @@ "@shade/server/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="], + "@shade/storage-postgres/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="], + "@shade/transport-bridge/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="], "@shade/vault/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="], diff --git a/docs/media.md b/docs/media.md index 8a2db36..1b10c91 100644 --- a/docs/media.md +++ b/docs/media.md @@ -85,6 +85,41 @@ failing. With `SHADE_MEDIA_DIR` unset the routes are not mounted, and the log sa With `SHADE_MEDIA_OWNERS` empty, the relay serves what it has and accepts nothing new. `*` admits every key, which is only safe on a private network. +### Several instances, one library (S3 + Postgres) + +``` +SHADE_MEDIA_S3_URL=https://:@s3.eu-north-1.amazonaws.com/[/] +SHADE_MEDIA_PG_URL=postgres://… # falls back to SHADE_PREKEY_PG_URL +``` + +(`shade media serve --s3 … --pg …` does the same outside the container.) Sealed +bytes go to the bucket, records and live-channel pins to Postgres, and any number of +instances behind one hostname serve one library. Any S3 API works (AWS, R2, MinIO, +SeaweedFS, Garage, B2); credentials left out of the URL come from +`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, the region from an `amazonaws.com` host +or `?region=`. A bucket the credentials cannot use is reported at start; media stays +off and the rest of the server runs. + +- **Uploads stream.** A film goes up as an S3 multipart upload, part by part, with at + most three 16 MiB parts in memory (512 MiB through: 11 MiB of RSS). Every part's + payload is hashed into its signature, so a part damaged in transit is refused. +- **Racing uploads of one id** (on any instances) each go to their own object key; + the primary key in Postgres admits one record, and the loser deletes its object. + Delete removes the record first, so a crash never brings a film back. +- **Sweeping.** Objects no record points at and multipart uploads never completed + (a crash mid-upload) are reclaimed after 24 hours, a minute after start and every + 6 hours. Every instance may sweep at once. +- **Live channels** are pinned in Postgres, so a channel cannot be pinned to two keys + by two instances. Frames still fan out in the memory of the instance the publisher + is connected to: route `/v1/live/*` to one instance (or sticky by channel id). +- The bucket holds only sealed SMF1 bytes. No key, name or plaintext is in it or in + Postgres. + +`S3Bucket` is Shade's own small S3 client (SigV4, checked against AWS's published +signature example and a server that validates signatures), not `Bun.S3Client`: in +Bun 1.3.5 its writer buffers everything written to it (512 MiB in, 543 MiB of RSS), +`end(error)` does not abort, and `slice(0, n).stream()` returned the whole object. + ## In code ```ts @@ -371,6 +406,10 @@ done in v1. A deployment that needs it can pad above this layer. mode across restarts), the HTTP routes and relay over real sockets, and the WebM and fMP4 splitters on real ffmpeg output (keyframes inside a GOP, codec strings for H.264, HEVC, AV1, VP9, AAC and Opus, CMAF `styp`/`prft` prefixes). +- `tests/object-store.test.ts` and `shade-storage-postgres/tests/postgres-media.test.ts` + run against a real S3 API and Postgres when `SHADE_TEST_S3_URL` / + `SHADE_TEST_PG_URL` are set (commands in the files): two relays over one bucket, + racing uploads and pins, sweeping, bounded memory. - `test-vectors/media.json` (`bun run scripts/generate-vectors.ts media.json`): the Kotlin port reads every vector and reproduces every sealed file and signed frame byte for byte (`MediaVectorTest`). diff --git a/packages/shade-cli/package.json b/packages/shade-cli/package.json index 6f543ca..4704f03 100644 --- a/packages/shade-cli/package.json +++ b/packages/shade-cli/package.json @@ -13,6 +13,7 @@ "@shade/media": "workspace:*", "@shade/sdk": "workspace:*", "@shade/storage-encrypted": "workspace:*", + "@shade/storage-postgres": "workspace:*", "@shade/storage-sqlite": "workspace:*", "@shade/transport": "workspace:*" }, diff --git a/packages/shade-cli/src/cli.ts b/packages/shade-cli/src/cli.ts index 6beedf9..1e7abc0 100644 --- a/packages/shade-cli/src/cli.ts +++ b/packages/shade-cli/src/cli.ts @@ -132,7 +132,10 @@ async function main(): Promise { case 'media': case 'live': { const { runMediaCli } = await import('@shade/media/cli'); - process.exitCode = await runMediaCli(cmd, args.slice(1)); + process.exitCode = await runMediaCli(cmd, args.slice(1), { + // Loaded only by `media serve --s3 … --pg …`. + sharedBackend: async (o) => (await import('@shade/storage-postgres')).createSharedMediaBackend(o), + }); break; } case 'help': diff --git a/packages/shade-media/src/cli.ts b/packages/shade-media/src/cli.ts index 60fec5e..5f038e6 100644 --- a/packages/shade-media/src/cli.ts +++ b/packages/shade-media/src/cli.ts @@ -110,7 +110,7 @@ const err = (s: string) => process.stderr.write(`${s}\n`); // ─── media ─────────────────────────────────────────────────── -async function mediaServe(flags: Flags): Promise { +async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise { 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 { 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 { // 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 { 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 … --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 { +/** + * 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; + }>; +} + +export async function runMediaCli(group: 'media' | 'live', argv: string[], hooks: MediaCliHooks = {}): Promise { 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; diff --git a/packages/shade-media/src/server.ts b/packages/shade-media/src/server.ts index 10bc8e5..d3c6ee4 100644 --- a/packages/shade-media/src/server.ts +++ b/packages/shade-media/src/server.ts @@ -2,7 +2,11 @@ export { createMediaRoutes, parseRange } from './server/media-routes.js'; export type { MediaRoutesOptions } from './server/media-routes.js'; export { FileMediaStore, MemoryMediaStore, MediaExistsError } from './server/file-store.js'; export type { MediaStore, MediaRecord, MediaUpload } from './server/file-store.js'; -export { createLiveRelay, FileLivePinStore, MemoryLivePinStore } from './server/live-relay.js'; +export { ObjectMediaStore, MemoryMediaIndex } from './server/object-store.js'; +export { S3Bucket, S3Error, signV4 } from './server/s3.js'; +export type { S3BucketOptions, S3Credentials, S3Object } from './server/s3.js'; +export type { MediaIndex, IndexedMedia, ObjectMediaStoreOptions } from './server/object-store.js'; +export { createLiveRelay, FileLivePinStore, MemoryLivePinStore, LivePinTakenError } from './server/live-relay.js'; export type { LiveRelay, LiveRelayOptions, LivePin, LivePinStore } from './server/live-relay.js'; export { createWatchRoutes } from './server/watch-routes.js'; export type { WatchRoutesOptions } from './server/watch-routes.js'; diff --git a/packages/shade-media/src/server/live-relay.ts b/packages/shade-media/src/server/live-relay.ts index 48e653b..5a4184a 100644 --- a/packages/shade-media/src/server/live-relay.ts +++ b/packages/shade-media/src/server/live-relay.ts @@ -45,15 +45,29 @@ export interface LivePin { export interface LivePinStore { get(channelId: string): Promise; + /** + * Create or refresh a pin. Must throw `LivePinTakenError` if the channel is + * pinned to another signing key — atomically, so two relays sharing the + * store cannot both pin one channel to different keys. + */ put(pin: LivePin): Promise; } +export class LivePinTakenError extends Error { + override readonly name = 'LivePinTakenError'; + constructor(channelId: string) { + super(`channel ${channelId} is pinned to another key`); + } +} + export class MemoryLivePinStore implements LivePinStore { private readonly pins = new Map(); async get(id: string): Promise { return this.pins.get(id) ?? null; } async put(pin: LivePin): Promise { + const have = this.pins.get(pin.channelId); + if (have !== undefined && have.signingKey !== pin.signingKey) throw new LivePinTakenError(pin.channelId); this.pins.set(pin.channelId, pin); } } @@ -90,6 +104,8 @@ export class FileLivePinStore implements LivePinStore { async put(pin: LivePin): Promise { const pins = await this.load(); + const have = pins.get(pin.channelId); + if (have !== undefined && have.signingKey !== pin.signingKey) throw new LivePinTakenError(pin.channelId); pins.set(pin.channelId, pin); const cutoff = Date.now() - this.ttlMs; for (const [k, p] of pins) if (p.lastSeen < cutoff) pins.delete(k); @@ -369,7 +385,13 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay { pinnedAt: existing?.pinnedAt ?? now(), lastSeen: now(), }; - await opts.pins.put(pin); + try { + await opts.pins.put(pin); + } catch (e) { + // Another relay sharing the pin store won the race for this channel. + if (e instanceof LivePinTakenError) return fail(ws, 'channel is pinned to another key'); + throw e; + } const ch = (await channelFor(channelId))!; ch.pin = pin; // A reconnecting publisher replaces the stale socket. diff --git a/packages/shade-media/src/server/object-store.ts b/packages/shade-media/src/server/object-store.ts new file mode 100644 index 0000000..f68ec8c --- /dev/null +++ b/packages/shade-media/src/server/object-store.ts @@ -0,0 +1,333 @@ +/** + * Sealed media in S3-compatible object storage, for relays that run as more + * than one instance (or on disks that cannot hold a film library). + * + * Bodies go to the bucket, records to a `MediaIndex` every instance shares + * (`PostgresMediaIndex` in `@shade/storage-postgres`). Object storage has no + * rename and no create-if-absent, so the two are split the way the file store + * splits object and sidecar: + * + * - every upload streams (multipart) to its own fresh key, + * `objects//.smf`, so two uploads never touch the same + * object; + * - the upload is committed by inserting its record into the index, which + * refuses a second record for one id — that insert is the single point + * where racing uploads (on any instance) are decided, and the loser deletes + * its own object; + * - delete removes the record first, then the object: a crash between the + * two leaves an unreferenced object, never a film that comes back. + * + * Objects no record points at (a crash mid-upload, a lost race whose cleanup + * failed) are removed by `sweep()`, which spares anything younger than the + * grace period: it may be an upload still running on another instance. + * + * The bucket only ever holds sealed SMF1 bytes. Nothing in it, or in the + * index, is a key. + */ + +import { randomBytes, toHex } from '../bytes.js'; +import { MediaExistsError } from './file-store.js'; +import type { MediaRecord, MediaStore, MediaUpload } from './file-store.js'; +import type { S3Bucket } from './s3.js'; +/** A record and the object holding its bytes. */ +export interface IndexedMedia extends MediaRecord { + /** Object key in the bucket. */ + key: string; +} + +/** The shared record of what is in the bucket. Must be safe across instances. */ +export interface MediaIndex { + get(id: string): Promise; + /** Insert, or throw `MediaExistsError` if the id already has a record — atomically. */ + insert(rec: IndexedMedia): Promise; + /** Remove and return the record, or null if there was none. */ + remove(id: string): Promise; + usage(owner: string): Promise; + totalBytes(): Promise; + /** Newest first. */ + list(owner: string): Promise; +} + +/** For tests and single-process use — a relay with more than one instance needs a shared index. */ +export class MemoryMediaIndex implements MediaIndex { + private readonly recs = new Map(); + async get(id: string): Promise { + return this.recs.get(id) ?? null; + } + async insert(rec: IndexedMedia): Promise { + if (this.recs.has(rec.id)) throw new MediaExistsError(rec.id); + this.recs.set(rec.id, rec); + } + async remove(id: string): Promise { + const r = this.recs.get(id) ?? null; + this.recs.delete(id); + return r; + } + async usage(owner: string): Promise { + let n = 0; + for (const r of this.recs.values()) if (r.owner === owner) n += r.size; + return n; + } + async totalBytes(): Promise { + let n = 0; + for (const r of this.recs.values()) n += r.size; + return n; + } + async list(owner: string): Promise { + return [...this.recs.values()] + .filter((r) => r.owner === owner) + .sort((a, b) => b.createdAt - a.createdAt) + .map(({ key: _key, ...rec }) => rec); + } +} + +export interface ObjectMediaStoreOptions { + /** Key prefix inside the bucket, e.g. `shade/` (default none). */ + prefix?: string; + /** Multipart part size. Default 16 MiB (S3's minimum is 5 MiB). An upload holds at most three parts in memory. */ + partSize?: number; + /** Bytes per GET when serving a range. Default 4 MiB. */ + readChunk?: number; + /** `sweep()` spares objects younger than this. Default 24 h — longer than any upload. */ + sweepGraceMs?: number; + now?: () => number; +} + +const ID_RE = /^[0-9a-f]{32}$/; +const MiB = 1024 * 1024; +/** What an upload keeps of its own tail, for `readBack` of the footer. */ +const TAIL_BYTES = 64 * 1024; +/** Parts uploading at once, per upload. */ +const PARTS_IN_FLIGHT = 2; + +function concat(chunks: Uint8Array[], total: number): Uint8Array { + if (chunks.length === 1) return chunks[0]!; + const out = new Uint8Array(total); + let o = 0; + for (const c of chunks) { + out.set(c, o); + o += c.length; + } + return out; +} + +export class ObjectMediaStore implements MediaStore { + private readonly prefix: string; + private readonly partSize: number; + private readonly readChunk: number; + private readonly graceMs: number; + private readonly now: () => number; + + constructor( + private readonly s3: S3Bucket, + private readonly index: MediaIndex, + opts: ObjectMediaStoreOptions = {}, + ) { + this.prefix = opts.prefix ?? ''; + this.partSize = opts.partSize ?? 16 * MiB; + if (this.partSize < 5 * MiB) throw new Error('partSize below the 5 MiB S3 minimum'); + this.readChunk = opts.readChunk ?? 4 * MiB; + this.graceMs = opts.sweepGraceMs ?? 24 * 3600 * 1000; + this.now = opts.now ?? Date.now; + } + + get(id: string): Promise { + return this.index.get(id).then((r) => (r === null ? null : strip(r))); + } + + usage(owner: string): Promise { + return this.index.usage(owner); + } + + totalBytes(): Promise { + return this.index.totalBytes(); + } + + list(owner: string): Promise { + return this.index.list(owner); + } + + async begin(id: string): Promise { + if (!ID_RE.test(id)) throw new Error('bad media id'); + const key = `${this.prefix}objects/${id}/${toHex(randomBytes(16))}.smf`; + const { index, s3, partSize } = this; + const contentType = 'application/vnd.shade.smf1'; + let written = 0; + let buffered: Uint8Array[] = []; + let bufferedBytes = 0; + let uploadId: string | null = null; + const etags: string[] = []; + let parts = 0; + let inFlight: Promise[] = []; + let failed: unknown = null; + // The relay reads the footer back before it commits. The bytes already + // left for the bucket, and a multipart upload cannot be read before it + // completes, so the upload keeps its own last bytes instead. + let tail = new Uint8Array(0); + const remember = (chunk: Uint8Array) => { + if (chunk.length >= TAIL_BYTES) { + tail = chunk.slice(chunk.length - TAIL_BYTES); + } else { + const keep = Math.min(tail.length, TAIL_BYTES - chunk.length); + const next = new Uint8Array(keep + chunk.length); + next.set(tail.subarray(tail.length - keep)); + next.set(chunk, keep); + tail = next; + } + }; + const takeBuffer = () => { + const body = concat(buffered, bufferedBytes); + buffered = []; + bufferedBytes = 0; + return body; + }; + const sendPart = async () => { + if (uploadId === null) uploadId = await s3.createMultipart(key, contentType); + const n = ++parts; + const body = takeBuffer(); + const p = s3.uploadPart(key, uploadId, n, body).then( + (etag) => { + etags[n - 1] = etag; + }, + (e: unknown) => { + failed ??= e; + }, + ); + inFlight.push(p); + // Backpressure: the request body is not read further until a part lands. + if (inFlight.length >= PARTS_IN_FLIGHT) { + await inFlight.shift(); + } + if (failed !== null) throw failed; + }; + const settle = async () => { + await Promise.all(inFlight); + inFlight = []; + if (failed !== null) throw failed; + }; + return { + get written() { + return written; + }, + async write(chunk) { + if (failed !== null) throw failed; + // The body stream may reuse its buffer: keep a copy. + const copy = chunk.slice(); + buffered.push(copy); + bufferedBytes += copy.length; + written += copy.length; + remember(copy); + if (bufferedBytes >= partSize) await sendPart(); + }, + async readBack(offset, length) { + const from = written - tail.length; + if (offset < from || offset + length > written) { + throw new Error(`readBack outside the last ${TAIL_BYTES} bytes of an object upload`); + } + return tail.slice(offset - from, offset - from + length); + }, + async commit(record) { + if (uploadId === null) { + await s3.put(key, takeBuffer(), contentType); + } else { + if (bufferedBytes > 0) await sendPart(); + await settle(); + await s3.completeMultipart(key, uploadId, etags); + } + // Trust, but verify: a part lost on the way must not become a film. + const stored = await s3.head(key); + if (stored !== record.size) { + await s3.delete(key).catch(() => {}); + throw new Error(`object storage holds ${stored ?? 'nothing'} of ${record.size} bytes`); + } + try { + await index.insert({ ...record, key }); + } catch (e) { + await s3.delete(key).catch(() => {}); + throw e; + } + }, + async abort() { + buffered = []; + bufferedBytes = 0; + // Parts still uploading would land after the abort and be billed: let them finish first. + await Promise.allSettled(inFlight); + inFlight = []; + if (uploadId !== null) await s3.abortMultipart(key, uploadId).catch(() => {}); + // Left for sweep() if this fails: an object nothing points at is never served. + await s3.delete(key).catch(() => {}); + }, + }; + } + + async body(id: string, start: number, end: number): Promise> { + const rec = await this.index.get(id); + if (rec === null) throw new Error('not found'); + const { s3, readChunk } = this; + let pos = start; + // One GET per chunk, fetched when the reader wants it: a player that + // reads two seconds and seeks away costs two seconds of bucket traffic. + return new ReadableStream( + { + async pull(controller) { + if (pos >= end) { + controller.close(); + return; + } + const to = Math.min(end, pos + readChunk); + const bytes = await s3.getRange(rec.key, pos, to); + pos = to; + controller.enqueue(bytes); + }, + }, + { highWaterMark: 0 }, + ); + } + + async delete(id: string): Promise { + const rec = await this.index.remove(id); + if (rec === null) return false; + await this.s3.delete(rec.key).catch(() => { + // The record is gone, so the film is gone; sweep() reclaims the bytes. + }); + return true; + } + + /** + * Reclaim what no record points at, older than the grace period: objects + * (a crash between upload and commit) and multipart uploads never finished + * (a crash mid-upload — invisible in a listing, billed all the same). Safe + * to run on every instance at once. + */ + async sweep(): Promise<{ objects: number; uploads: number }> { + const cutoff = this.now() - this.graceMs; + const prefix = `${this.prefix}objects/`; + let objects = 0; + let next: string | undefined; + do { + const page = await this.s3.list(prefix, next); + for (const obj of page.objects) { + const m = /^objects\/([0-9a-f]{32})\/[0-9a-f]{32}\.smf$/.exec(obj.key.slice(this.prefix.length)); + if (m === null) continue; // not ours: leave it + if (!(obj.lastModified < cutoff)) continue; + const rec = await this.index.get(m[1]!); + if (rec?.key === obj.key) continue; + await this.s3.delete(obj.key); + objects++; + } + next = page.next; + } while (next !== undefined); + let uploads = 0; + for (const u of await this.s3.listMultipart(prefix)) { + if (!(u.initiated < cutoff)) continue; + await this.s3.abortMultipart(u.key, u.uploadId); + uploads++; + } + return { objects, uploads }; + } +} + +function strip(r: IndexedMedia): MediaRecord { + const { key: _key, ...rec } = r; + return rec; +} diff --git a/packages/shade-media/src/server/s3.ts b/packages/shade-media/src/server/s3.ts new file mode 100644 index 0000000..0d47112 --- /dev/null +++ b/packages/shade-media/src/server/s3.ts @@ -0,0 +1,323 @@ +/** + * A small S3 client: exactly what the object media store needs, with the + * properties it cannot do without. + * + * Why not `Bun.S3Client` (1.3.5): its writer buffers everything written to + * it (no backpressure — a 64 GiB film would sit in RAM), `end(error)` does + * not abort the upload, and `slice(0, n).stream()` returned the whole object. + * Here a multipart upload is driven part by part, so memory is bounded by + * the parts in flight; an abort is an S3 AbortMultipartUpload; a ranged read + * checks it got exactly the bytes it asked for. + * + * Signing is AWS Signature Version 4 with the payload hashed (no + * UNSIGNED-PAYLOAD), so a part damaged in transit is refused by the server. + * Works against AWS S3, Cloudflare R2, MinIO, SeaweedFS, Garage, Backblaze B2. + */ + +import { createHash, createHmac } from 'node:crypto'; + +export interface S3Credentials { + accessKeyId: string; + secretAccessKey: string; + sessionToken?: string; +} + +export interface S3BucketOptions extends S3Credentials { + /** `https://s3.eu-north-1.amazonaws.com`, `http://127.0.0.1:9000`, … */ + endpoint: string; + bucket: string; + region: string; + /** Bucket in the host name (`bucket.endpoint`) instead of the path. Default: only for amazonaws.com. */ + virtualHosted?: boolean; + /** Attempts per request on a network error or 5xx. Default 4. */ + attempts?: number; + fetch?: typeof fetch; +} + +export interface S3Object { + key: string; + size: number; + lastModified: number; +} + +export class S3Error extends Error { + override readonly name = 'S3Error'; + constructor( + readonly status: number, + readonly code: string, + message: string, + ) { + super(message); + } +} + +const EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'; + +const sha256Hex = (data: Uint8Array | string) => createHash('sha256').update(data).digest('hex'); +const hmac = (key: Uint8Array | string, data: string) => createHmac('sha256', key).update(data).digest(); + +/** RFC 3986 encoding as SigV4 wants it: everything but unreserved characters. */ +function uriEncode(s: string, keepSlash: boolean): string { + let out = ''; + for (const byte of new TextEncoder().encode(s)) { + const c = String.fromCharCode(byte); + if (/[A-Za-z0-9\-._~]/.test(c) || (keepSlash && c === '/')) out += c; + else out += `%${byte.toString(16).toUpperCase().padStart(2, '0')}`; + } + return out; +} + +export interface SignInput { + method: string; + host: string; + /** Path, not yet encoded. */ + path: string; + query: Record; + /** Headers to sign, any case; `host`, `x-amz-date` and `x-amz-content-sha256` are added. */ + headers: Record; + payloadHash: string; + /** `YYYYMMDDTHHMMSSZ`. */ + amzDate: string; + region: string; + service?: string; + credentials: S3Credentials; +} + +/** SigV4 header signing. Returns every header to send, `authorization` included. */ +export function signV4(input: SignInput): Record { + const service = input.service ?? 's3'; + const date = input.amzDate.slice(0, 8); + const headers: Record = {}; + for (const [k, v] of Object.entries(input.headers)) headers[k.toLowerCase()] = v.trim(); + headers.host = input.host; + headers['x-amz-date'] = input.amzDate; + headers['x-amz-content-sha256'] = input.payloadHash; + if (input.credentials.sessionToken !== undefined) headers['x-amz-security-token'] = input.credentials.sessionToken; + const names = Object.keys(headers).sort(); + const canonicalQuery = Object.keys(input.query) + .sort() + .map((k) => `${uriEncode(k, false)}=${uriEncode(input.query[k]!, false)}`) + .join('&'); + const canonical = [ + input.method, + uriEncode(input.path, true), + canonicalQuery, + names.map((n) => `${n}:${headers[n]}\n`).join(''), + names.join(';'), + input.payloadHash, + ].join('\n'); + const scope = `${date}/${input.region}/${service}/aws4_request`; + const toSign = ['AWS4-HMAC-SHA256', input.amzDate, scope, sha256Hex(canonical)].join('\n'); + let k = hmac(`AWS4${input.credentials.secretAccessKey}`, date); + for (const part of [input.region, service, 'aws4_request']) k = hmac(k, part); + const signature = createHmac('sha256', k).update(toSign).digest('hex'); + headers.authorization = `AWS4-HMAC-SHA256 Credential=${input.credentials.accessKeyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${signature}`; + return headers; +} + +const amzDateOf = (ms: number) => new Date(ms).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, ''); + +function xmlText(s: string): string { + return s.replace(/&(lt|gt|amp|quot|apos|#(\d+)|#x([0-9a-fA-F]+));/g, (m, name: string, dec?: string, hex?: string) => { + if (dec !== undefined) return String.fromCodePoint(Number(dec)); + if (hex !== undefined) return String.fromCodePoint(parseInt(hex, 16)); + return ({ lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" } as Record)[name] ?? m; + }); +} + +const tag = (xml: string, name: string) => { + const m = new RegExp(`<${name}>([\\s\\S]*?)`).exec(xml); + return m === null ? undefined : xmlText(m[1]!); +}; + +const xmlEscape = (s: string) => s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + +export class S3Bucket { + readonly bucket: string; + private readonly origin: URL; + private readonly region: string; + private readonly creds: S3Credentials; + private readonly virtualHosted: boolean; + private readonly attempts: number; + private readonly fetch: typeof fetch; + + constructor(opts: S3BucketOptions) { + this.origin = new URL(opts.endpoint); + this.bucket = opts.bucket; + this.region = opts.region; + this.creds = { + accessKeyId: opts.accessKeyId, + secretAccessKey: opts.secretAccessKey, + ...(opts.sessionToken !== undefined ? { sessionToken: opts.sessionToken } : {}), + }; + this.virtualHosted = opts.virtualHosted ?? this.origin.hostname.endsWith('amazonaws.com'); + this.attempts = opts.attempts ?? 4; + this.fetch = opts.fetch ?? fetch; + } + + /** + * `http(s)://:@/[/][?region=…]`. + * Credentials left out of the URL come from `AWS_ACCESS_KEY_ID` / + * `AWS_SECRET_ACCESS_KEY` (or `S3_…`). The region defaults to the one in + * an `s3..amazonaws.com` host, else `us-east-1` (what R2, MinIO + * and SeaweedFS accept). + */ + static fromUrl(raw: string, env: Record = process.env): { bucket: S3Bucket; prefix: string } { + let u: URL; + try { + u = new URL(raw); + } catch { + throw new Error('S3 URL must look like https://key:secret@host/bucket[/prefix]'); + } + if (u.protocol !== 'https:' && u.protocol !== 'http:') throw new Error(`S3 URL must be http(s), not ${u.protocol}`); + const [bucket, ...rest] = u.pathname.split('/').filter((s) => s !== ''); + if (bucket === undefined) throw new Error('S3 URL names no bucket (https://host/)'); + const accessKeyId = u.username !== '' ? decodeURIComponent(u.username) : (env.AWS_ACCESS_KEY_ID ?? env.S3_ACCESS_KEY_ID); + const secretAccessKey = u.password !== '' ? decodeURIComponent(u.password) : (env.AWS_SECRET_ACCESS_KEY ?? env.S3_SECRET_ACCESS_KEY); + if (accessKeyId === undefined || secretAccessKey === undefined) { + throw new Error('S3 credentials missing: put key:secret in the URL, or set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY'); + } + const sessionToken = env.AWS_SESSION_TOKEN ?? env.S3_SESSION_TOKEN; + const region = u.searchParams.get('region') ?? /^s3[.-]([a-z0-9-]+)\.amazonaws\.com$/.exec(u.hostname)?.[1] ?? 'us-east-1'; + return { + bucket: new S3Bucket({ + endpoint: `${u.protocol}//${u.host}`, + bucket, + region, + accessKeyId, + secretAccessKey, + ...(sessionToken !== undefined ? { sessionToken } : {}), + }), + prefix: rest.length > 0 ? `${rest.join('/')}/` : '', + }; + } + + private async request( + method: string, + key: string | null, + opts: { query?: Record; headers?: Record; body?: Uint8Array; ok?: number[] } = {}, + ): Promise { + const host = this.virtualHosted ? `${this.bucket}.${this.origin.host}` : this.origin.host; + const path = this.virtualHosted ? `/${key ?? ''}` : `/${this.bucket}${key !== null ? `/${key}` : ''}`; + const query = opts.query ?? {}; + const qs = Object.entries(query) + .map(([k, v]) => `${uriEncode(k, false)}=${uriEncode(v, false)}`) + .join('&'); + const url = `${this.origin.protocol}//${host}${uriEncode(path, true)}${qs !== '' ? `?${qs}` : ''}`; + const payloadHash = opts.body !== undefined ? sha256Hex(opts.body) : EMPTY_SHA256; + const ok = opts.ok ?? [200]; + let last: unknown; + for (let attempt = 0; attempt < this.attempts; attempt++) { + if (attempt > 0) await new Promise((r) => setTimeout(r, Math.min(4000, 200 * 2 ** attempt))); + const headers = signV4({ + method, + host, + path, + query, + headers: opts.headers ?? {}, + payloadHash, + amzDate: amzDateOf(Date.now()), + region: this.region, + credentials: this.creds, + }); + delete headers.host; // fetch sets it, from the URL + let res: Response; + try { + res = await this.fetch(url, { method, headers, ...(opts.body !== undefined ? { body: opts.body as Uint8Array } : {}) }); + } catch (e) { + last = e; + continue; + } + if (ok.includes(res.status)) return res; + const text = await res.text().catch(() => ''); + const err = new S3Error(res.status, tag(text, 'Code') ?? `HTTP_${res.status}`, `S3 ${method} ${key ?? `bucket ${this.bucket}`}: ${res.status} ${tag(text, 'Message') ?? text.slice(0, 200)}`); + // 5xx and throttling are worth another try; anything else is an answer. + if (res.status < 500 && res.status !== 429) throw err; + last = err; + } + throw last instanceof Error ? last : new Error(String(last)); + } + + async put(key: string, body: Uint8Array, contentType = 'application/octet-stream'): Promise { + await this.request('PUT', key, { body, headers: { 'content-type': contentType } }); + } + + /** Exactly the bytes `[start, end)`, or an error. */ + async getRange(key: string, start: number, end: number): Promise { + const res = await this.request('GET', key, { headers: { range: `bytes=${start}-${end - 1}` }, ok: [206, 200] }); + const bytes = new Uint8Array(await res.arrayBuffer()); + // A 200 is the whole object (a server that ignores Range): take the range out of it. + const got = res.status === 200 ? bytes.subarray(start, end) : bytes; + if (got.length !== end - start) throw new S3Error(res.status, 'SHORT_READ', `S3 GET ${key}: ${got.length} of ${end - start} bytes`); + return got; + } + + /** Size, or null if the object does not exist. */ + async head(key: string): Promise { + const res = await this.request('HEAD', key, { ok: [200, 404] }); + if (res.status === 404) return null; + return Number(res.headers.get('content-length')); + } + + /** Idempotent: deleting what is not there is not an error. */ + async delete(key: string): Promise { + await this.request('DELETE', key, { ok: [200, 204, 404] }); + } + + /** One page of ListObjectsV2. */ + async list(prefix: string, continuationToken?: string): Promise<{ objects: S3Object[]; next?: string }> { + const query: Record = { 'list-type': '2', prefix }; + if (continuationToken !== undefined) query['continuation-token'] = continuationToken; + const xml = await (await this.request('GET', null, { query })).text(); + const objects: S3Object[] = []; + for (const m of xml.matchAll(/([\s\S]*?)<\/Contents>/g)) { + const body = m[1]!; + objects.push({ + key: tag(body, 'Key') ?? '', + size: Number(tag(body, 'Size') ?? 0), + lastModified: Date.parse(tag(body, 'LastModified') ?? ''), + }); + } + const next = tag(xml, 'IsTruncated') === 'true' ? tag(xml, 'NextContinuationToken') : undefined; + return next !== undefined ? { objects, next } : { objects }; + } + + async createMultipart(key: string, contentType = 'application/octet-stream'): Promise { + const xml = await (await this.request('POST', key, { query: { uploads: '' }, headers: { 'content-type': contentType } })).text(); + const id = tag(xml, 'UploadId'); + if (id === undefined) throw new S3Error(200, 'NO_UPLOAD_ID', `S3 CreateMultipartUpload ${key}: no UploadId`); + return id; + } + + /** Returns the part's ETag, for `completeMultipart`. */ + async uploadPart(key: string, uploadId: string, partNumber: number, body: Uint8Array): Promise { + const res = await this.request('PUT', key, { query: { partNumber: String(partNumber), uploadId }, body }); + const etag = res.headers.get('etag'); + if (etag === null) throw new S3Error(200, 'NO_ETAG', `S3 UploadPart ${key} #${partNumber}: no ETag`); + return etag; + } + + async completeMultipart(key: string, uploadId: string, etags: readonly string[]): Promise { + const body = new TextEncoder().encode( + `${etags.map((e, i) => `${i + 1}${xmlEscape(e)}`).join('')}`, + ); + const res = await this.request('POST', key, { query: { uploadId }, body, headers: { 'content-type': 'application/xml' } }); + // S3 may answer 200 and still fail: the error is in the body. + const text = await res.text(); + if (//.test(text)) throw new S3Error(200, tag(text, 'Code') ?? 'COMPLETE_FAILED', `S3 CompleteMultipartUpload ${key}: ${tag(text, 'Message') ?? text.slice(0, 200)}`); + } + + /** Multipart uploads begun under `prefix` and never completed or aborted (first page of up to 1000). */ + async listMultipart(prefix: string): Promise<{ key: string; uploadId: string; initiated: number }[]> { + const xml = await (await this.request('GET', null, { query: { uploads: '', prefix } })).text(); + return [...xml.matchAll(/([\s\S]*?)<\/Upload>/g)].map((m) => ({ + key: tag(m[1]!, 'Key') ?? '', + uploadId: tag(m[1]!, 'UploadId') ?? '', + initiated: Date.parse(tag(m[1]!, 'Initiated') ?? ''), + })); + } + + async abortMultipart(key: string, uploadId: string): Promise { + await this.request('DELETE', key, { query: { uploadId }, ok: [200, 204, 404] }); + } +} diff --git a/packages/shade-media/src/server/service.ts b/packages/shade-media/src/server/service.ts index 4efc2e3..1d954c2 100644 --- a/packages/shade-media/src/server/service.ts +++ b/packages/shade-media/src/server/service.ts @@ -10,13 +10,24 @@ import { join } from 'node:path'; import { FileMediaStore } from './file-store.js'; import { createMediaRoutes } from './media-routes.js'; import type { MediaRoutesOptions } from './media-routes.js'; +import type { MediaStore } from './file-store.js'; import { createLiveRelay, FileLivePinStore } from './live-relay.js'; -import type { LiveRelay, LiveRelayOptions } from './live-relay.js'; +import type { LivePinStore, LiveRelay, LiveRelayOptions } from './live-relay.js'; import { createWatchRoutes } from './watch-routes.js'; export interface MediaServiceOptions { - /** Persistent directory: `media/` for sealed files, `live-pins.json` for channel pins. */ - dir: string; + /** + * Persistent directory: `media/` for sealed files, `live-pins.json` for + * channel pins. Not needed when both `store` and `pins` are given. + */ + dir?: string; + /** + * Where sealed files live, instead of `/media/` — e.g. an + * `ObjectMediaStore` (S3 + a shared index) when several relays serve one library. + */ + store?: MediaStore; + /** Live-channel pins, instead of `/live-pins.json` — shared by relays that share a store. */ + pins?: LivePinStore; /** * Owner keys (base64url) allowed to upload and to open live channels. * `'any'` lets every key in (bounded by quotas) — only for a private relay. @@ -50,6 +61,12 @@ export const MEDIA_BODY_ROUTE = '/v1/media/'; export function createMediaService(opts: MediaServiceOptions): MediaService { const owners = opts.owners === 'any' ? undefined : opts.owners; + const dirFor = (what: string) => { + if (opts.dir === undefined) throw new Error(`createMediaService: no dir, and no ${what} given`); + return opts.dir; + }; + const store = opts.store ?? new FileMediaStore(join(dirFor('store'), 'media')); + const pins = opts.pins ?? new FileLivePinStore(join(dirFor('pins'), 'live-pins.json')); const app = new Hono(); // Sealed bytes are safe to hand to any origin — the key is not here — and // a player on another site needs CORS to make its Range requests. @@ -63,14 +80,14 @@ export function createMediaService(opts: MediaServiceOptions): MediaService { ); app.route( '/', - createMediaRoutes(new FileMediaStore(join(opts.dir, 'media')), { + createMediaRoutes(store, { ...opts.media, ...(owners !== undefined ? { allowedOwners: owners } : {}), }), ); const relay = createLiveRelay({ ...opts.live, - pins: new FileLivePinStore(join(opts.dir, 'live-pins.json')), + pins, ...(owners !== undefined ? { allowedOwners: owners } : {}), }); app.route('/', relay.app); diff --git a/packages/shade-media/tests/object-store.test.ts b/packages/shade-media/tests/object-store.test.ts new file mode 100644 index 0000000..3dbd3d8 --- /dev/null +++ b/packages/shade-media/tests/object-store.test.ts @@ -0,0 +1,137 @@ +/** + * ObjectMediaStore against a real S3 API. Skipped unless SHADE_TEST_S3_URL + * names a bucket that may be emptied, e.g. with SeaweedFS: + * + * docker run -d --rm -p 127.0.0.1:58333:8333 chrislusf/seaweedfs server -s3 -dir=/data + * SHADE_TEST_S3_URL=http://key:secret@127.0.0.1:58333/shade-media-test bun test object-store + */ +import { describe, test, expect, beforeAll } from 'bun:test'; +import { Hono } from 'hono'; +import { createMediaRoutes, MemoryMediaIndex, ObjectMediaStore, S3Bucket } from '../src/server.js'; +import { MediaClient, OwnerKey, openGrant, sealMediaBytes, MIN_SEGMENT_SIZE } from '../src/index.js'; +import { toHex } from '../src/bytes.js'; + +const URL_ = process.env.SHADE_TEST_S3_URL; + +function pattern(n: number): Uint8Array { + const out = new Uint8Array(n); + for (let i = 0; i < n; i++) out[i] = (i * 31 + (i >> 8)) & 0xff; + return out; +} + +function serve(app: Hono) { + const server = Bun.serve({ port: 0, fetch: (req) => app.fetch(req), maxRequestBodySize: 1024 ** 3 }); + return { server, base: `http://localhost:${server.port}` }; +} + +describe.skipIf(URL_ === undefined)('ObjectMediaStore (S3)', () => { + const { bucket: s3, prefix: basePrefix } = URL_ !== undefined ? S3Bucket.fromUrl(URL_) : ({} as ReturnType); + // A fresh prefix per run: runs never see each other's objects. + const prefix = `${basePrefix}run-${Date.now().toString(36)}/`; + const keys = async () => (await s3.list(prefix)).objects.map((o) => o.key); + + beforeAll(async () => { + // SeaweedFS and MinIO create a bucket on PUT; real S3 answers 409 for one that exists. + const u = new URL(URL_!); + await fetch(`${u.protocol}//${u.host}${u.pathname.split('/').slice(0, 2).join('/')}`, { method: 'PUT' }).catch(() => {}); + }); + + test('two relay instances over one bucket and one index: upload on A, play on B, race decided once', async () => { + const index = new MemoryMediaIndex(); + const a = serve(new Hono().route('/', createMediaRoutes(new ObjectMediaStore(s3, index, { prefix, partSize: 5 * 1024 * 1024 })))); + const b = serve(new Hono().route('/', createMediaRoutes(new ObjectMediaStore(s3, index, { prefix })))); + try { + const owner = OwnerKey.generate(); + // Bigger than two parts, not a multiple of one: the multipart path and its last short part. + const plain = pattern(12 * 1024 * 1024 + 4321); + const grant = await new MediaClient(a.base, owner).uploadBytes(plain, { meta: { name: 'Film.mkv' } }); + const onB = await openGrant(grant, { url: grant.url!.replace(a.base, b.base) }); + expect(onB.meta.name).toBe('Film.mkv'); + expect(await onB.read(7 * 1024 * 1024 - 11, 3 * 1024 * 1024)).toEqual(plain.subarray(7 * 1024 * 1024 - 11, 10 * 1024 * 1024 - 11)); + expect(await onB.read(0, plain.length)).toEqual(plain); + + const res = await fetch(grant.url!.replace(a.base, b.base), { headers: { Range: 'bytes=100-1048675', 'x-shade-read': '' } }); + expect(res.status).toBe(404); // the read token still guards the bytes + + // The same sealed file sent to both instances at once: one wins, one gets 409, one object stays. + const { bytes, result } = await sealMediaBytes(pattern(3 * MIN_SEGMENT_SIZE)); + const settled = await Promise.allSettled([ + new MediaClient(a.base, owner).putSealed(result, bytes), + new MediaClient(b.base, owner).putSealed(result, bytes), + ]); + expect(settled.filter((s) => s.status === 'fulfilled').length).toBe(1); + expect(String((settled.find((s) => s.status === 'rejected') as PromiseRejectedResult).reason)).toMatch(/409/); + const id = toHex(result.mediaId); + expect((await keys()).filter((k) => k.includes(id)).length).toBe(1); + + expect((await new MediaClient(b.base, owner).list()).items.length).toBe(2); + 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 keys()).toEqual([]); + } finally { + a.server.stop(true); + b.server.stop(true); + } + }, 60_000); + + test('a refused upload leaves nothing behind; sweep reclaims orphans past the grace period only', async () => { + let clock = Date.now(); + const index = new MemoryMediaIndex(); + const store = new ObjectMediaStore(s3, index, { prefix, now: () => clock, sweepGraceMs: 60_000 }); + const srv = serve(new Hono().route('/', createMediaRoutes(store))); + try { + const { bytes, result } = await sealMediaBytes(pattern(2 * MIN_SEGMENT_SIZE)); + const damaged = bytes.slice(); + damaged[damaged.length - 1]! ^= 0xff; // the footer no longer parses + await expect(new MediaClient(srv.base, OwnerKey.generate()).putSealed(result, damaged)).rejects.toThrow(/422/); + expect(await keys()).toEqual([]); + + // An orphan: bytes that reached the bucket, a record that never did (a crash between the two). + const orphan = `${prefix}objects/${'ab'.repeat(16)}/${'cd'.repeat(16)}.smf`; + await s3.put(orphan, new Uint8Array(100)); + const kept = await new MediaClient(srv.base, OwnerKey.generate()).putSealed(result, bytes); + const foreign = `${prefix}objects/notes.txt`; + await s3.put(foreign, new TextEncoder().encode('not ours')); + + // And an upload that died mid-way: parts in the bucket, never completed. + const dead = await s3.createMultipart(`${prefix}objects/${'ef'.repeat(16)}/${'01'.repeat(16)}.smf`); + await s3.uploadPart(`${prefix}objects/${'ef'.repeat(16)}/${'01'.repeat(16)}.smf`, dead, 1, new Uint8Array(10)); + + expect(await store.sweep()).toEqual({ objects: 0, uploads: 0 }); // everything is younger than the grace period + clock += 120_000; + expect(await store.sweep()).toEqual({ objects: 1, uploads: 1 }); + expect(await s3.listMultipart(prefix)).toEqual([]); + expect((await keys()).sort()).toEqual([foreign, (await index.get(toHex(kept.mediaId)))!.key].sort()); + expect(await (await openGrant(kept)).read(0, 10)).toEqual(pattern(10)); + await s3.delete(foreign); + await store.delete(toHex(kept.mediaId)); + } finally { + srv.server.stop(true); + } + }, 60_000); + + test('a film streams through: memory is bounded by the parts in flight, not the film', async () => { + const partSize = 8 * 1024 * 1024; + const store = new ObjectMediaStore(s3, new MemoryMediaIndex(), { prefix, partSize }); + const chunk = new Uint8Array(1024 * 1024); + const total = 512 * 1024 * 1024; + Bun.gc(true); + const before = process.memoryUsage().rss; + let peak = before; + const id = toHex(new Uint8Array(16).fill(0x5a)); + const up = await store.begin(id); + for (let off = 0; off < total; off += chunk.length) { + chunk.fill((off / chunk.length) & 0xff); + await up.write(chunk); + peak = Math.max(peak, process.memoryUsage().rss); + } + await up.commit({ id, owner: 'o', size: total, readTokenHash: null, createdAt: Date.now() }); + // Three parts (one filling, two uploading) and the HTTP machinery — not 512 MiB. + const grewMiB = (peak - before) / 1024 / 1024; + console.log(`object upload of 512 MiB: RSS grew ${grewMiB.toFixed(0)} MiB`); + expect(grewMiB).toBeLessThan(120); + const body = await store.body(id, 300 * 1024 * 1024 - 1, 300 * 1024 * 1024 + 1); + expect(new Uint8Array(await new Response(body).arrayBuffer())).toEqual(new Uint8Array([299 & 0xff, 300 & 0xff])); + expect(await store.delete(id)).toBe(true); + }, 180_000); +}); diff --git a/packages/shade-media/tests/s3.test.ts b/packages/shade-media/tests/s3.test.ts new file mode 100644 index 0000000..1c5d21b --- /dev/null +++ b/packages/shade-media/tests/s3.test.ts @@ -0,0 +1,36 @@ +import { describe, test, expect } from 'bun:test'; +import { S3Bucket, signV4 } from '../src/server.js'; + +describe('S3 SigV4', () => { + // AWS's worked example, "Signature Calculations for the Authorization + // Header", GET Object with a Range header. + test('matches the published AWS example signature', () => { + const h = signV4({ + method: 'GET', + host: 'examplebucket.s3.amazonaws.com', + path: '/test.txt', + query: {}, + headers: { Range: 'bytes=0-9' }, + payloadHash: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', + amzDate: '20130524T000000Z', + region: 'us-east-1', + credentials: { accessKeyId: 'AKIAIOSFODNN7EXAMPLE', secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' }, + }); + expect(h.authorization).toBe( + 'AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, ' + + 'SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, ' + + 'Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41', + ); + }); + + test('one URL configures a bucket', () => { + const a = S3Bucket.fromUrl('https://AK%2FX:se%2Bcret@s3.eu-north-1.amazonaws.com/films/shade/relay-1', {}); + expect(a.prefix).toBe('shade/relay-1/'); + expect(a.bucket.bucket).toBe('films'); + const b = S3Bucket.fromUrl('http://127.0.0.1:9000/b', { AWS_ACCESS_KEY_ID: 'k', AWS_SECRET_ACCESS_KEY: 's' }); + expect(b.prefix).toBe(''); + expect(() => S3Bucket.fromUrl('http://127.0.0.1:9000/b', {})).toThrow(/credentials/); + expect(() => S3Bucket.fromUrl('http://127.0.0.1:9000/', { AWS_ACCESS_KEY_ID: 'k', AWS_SECRET_ACCESS_KEY: 's' })).toThrow(/bucket/); + expect(() => S3Bucket.fromUrl('ftp://h/b', {})).toThrow(/http/); + }); +}); diff --git a/packages/shade-server/src/standalone.ts b/packages/shade-server/src/standalone.ts index 1629a67..79a9fae 100644 --- a/packages/shade-server/src/standalone.ts +++ b/packages/shade-server/src/standalone.ts @@ -313,12 +313,22 @@ if (vaultDisabled) { // both. Same rule as the vault: a media library that lives in RAM loses every // film on the next redeploy, so no directory means no media, said loudly. // Uploads and live channels are closed to everyone but SHADE_MEDIA_OWNERS. +// Several instances share one library with SHADE_MEDIA_S3_URL (sealed bytes +// in a bucket) + SHADE_MEDIA_PG_URL (records and live pins in Postgres). let mediaService: import('@shade/media/server').MediaService | null = null; +const mediaS3 = process.env.SHADE_MEDIA_S3_URL; +const mediaPg = process.env.SHADE_MEDIA_PG_URL ?? process.env.SHADE_PREKEY_PG_URL; if (process.env.SHADE_DISABLE_MEDIA === '1') { logger.info('Media disabled (SHADE_DISABLE_MEDIA=1)'); -} else if (!process.env.SHADE_MEDIA_DIR) { +} else if (mediaS3 !== undefined && mediaPg === undefined) { + logger.error( + 'Media not enabled — SHADE_MEDIA_S3_URL needs SHADE_MEDIA_PG_URL: the bucket holds the bytes, ' + + 'Postgres the records every instance must agree on.', + ); +} else if (!process.env.SHADE_MEDIA_DIR && mediaS3 === undefined) { logger.warn( - 'Media not enabled — set SHADE_MEDIA_DIR to a directory on a persistent volume. ' + + 'Media not enabled — set SHADE_MEDIA_DIR to a directory on a persistent volume ' + + '(or SHADE_MEDIA_S3_URL + SHADE_MEDIA_PG_URL for a library shared by several instances). ' + 'There is no in-memory fallback on purpose: a library that forgets on redeploy is not a library.', ); } else { @@ -330,13 +340,42 @@ if (process.env.SHADE_DISABLE_MEDIA === '1') { 'Add owner keys (`shade media whoami`), comma-separated.', ); } - mediaService = createMediaService({ dir: process.env.SHADE_MEDIA_DIR, owners }); - app.route('/', mediaService.app); - logger.info('Media enabled', { - routes: ['/v1/media/:id', '/v1/live/:channelId', '/watch/'], - dir: process.env.SHADE_MEDIA_DIR, - owners: owners === 'any' ? 'any' : owners.length, - }); + let where: string = process.env.SHADE_MEDIA_DIR ?? ''; + let backend: import('@shade/storage-postgres').SharedMediaBackend | null = null; + if (mediaS3 !== undefined) { + const { createSharedMediaBackend } = await import('@shade/storage-postgres'); + try { + backend = await createSharedMediaBackend({ s3Url: mediaS3, pgUrl: mediaPg! }); + } catch (e) { + // The rest of the server is still worth running; media says why it is off. + logger.error('Media not enabled — the shared backend (SHADE_MEDIA_S3_URL / SHADE_MEDIA_PG_URL) failed', { + error: e instanceof Error ? e.message : String(e), + }); + } + } + if (backend !== null) { + mediaService = createMediaService({ owners, store: backend.store, pins: backend.pins }); + where = backend.describe; + // Reclaim what crashed uploads left in the bucket. Every instance may + // run it; the grace period spares uploads still in flight anywhere. + const sweep = () => + backend.sweep().then( + (n) => (n.objects + n.uploads > 0 ? logger.info('Media sweep', n) : undefined), + (e: unknown) => logger.warn('Media sweep failed', { error: String(e) }), + ); + setTimeout(sweep, 60_000).unref(); + setInterval(sweep, 6 * 3600_000).unref(); + } else if (mediaS3 === undefined) { + mediaService = createMediaService({ dir: process.env.SHADE_MEDIA_DIR!, owners }); + } + if (mediaService !== null) { + app.route('/', mediaService.app); + logger.info('Media enabled', { + routes: ['/v1/media/:id', '/v1/live/:channelId', '/watch/'], + store: where, + owners: owners === 'any' ? 'any' : owners.length, + }); + } } // ─── Optional: Observer + Dashboard ────────────────────────── diff --git a/packages/shade-storage-postgres/package.json b/packages/shade-storage-postgres/package.json index 6975750..2daf1a4 100644 --- a/packages/shade-storage-postgres/package.json +++ b/packages/shade-storage-postgres/package.json @@ -8,11 +8,13 @@ "@shade/core": "workspace:*", "@shade/inbox-server": "workspace:*", "@shade/key-transparency": "workspace:*", + "@shade/media": "workspace:*", "@shade/server": "workspace:*", "drizzle-orm": "^0.45.2", "postgres": "^3.4.9" }, "devDependencies": { - "@shade/crypto-web": "workspace:*" + "@shade/crypto-web": "workspace:*", + "hono": "^4.12.18" } } diff --git a/packages/shade-storage-postgres/src/ensure-tables.ts b/packages/shade-storage-postgres/src/ensure-tables.ts index 47e2e8c..2f1574b 100644 --- a/packages/shade-storage-postgres/src/ensure-tables.ts +++ b/packages/shade-storage-postgres/src/ensure-tables.ts @@ -280,3 +280,38 @@ export async function ensureInboxServerTables(sql: Sql): Promise { ON shade_inbox_blobs(expires_at) `; } + +/** + * Sealed-media records (`PostgresMediaIndex`) and live-channel pins + * (`PostgresLivePinStore`) for relays that share one bucket. Sizes are + * BIGINT: one film can pass 2 GiB, an owner's library 2^31 bytes easily. + */ +export async function ensureMediaServerTables(sql: Sql): Promise { + await sql` + CREATE TABLE IF NOT EXISTS shade_media_objects ( + media_id TEXT PRIMARY KEY, + owner_pubkey TEXT NOT NULL, + size BIGINT NOT NULL, + read_token_hash TEXT, + object_key TEXT NOT NULL, + created_at BIGINT NOT NULL + ) + `; + await sql` + CREATE INDEX IF NOT EXISTS shade_media_owner_idx + ON shade_media_objects(owner_pubkey, created_at DESC) + `; + await sql` + CREATE TABLE IF NOT EXISTS shade_live_pins ( + channel_id TEXT PRIMARY KEY, + signing_key TEXT NOT NULL, + read_token_hash TEXT NOT NULL, + pinned_at BIGINT NOT NULL, + last_seen BIGINT NOT NULL + ) + `; + await sql` + CREATE INDEX IF NOT EXISTS shade_live_pins_seen_idx + ON shade_live_pins(last_seen) + `; +} diff --git a/packages/shade-storage-postgres/src/index.ts b/packages/shade-storage-postgres/src/index.ts index ef77d7c..37485e1 100644 --- a/packages/shade-storage-postgres/src/index.ts +++ b/packages/shade-storage-postgres/src/index.ts @@ -3,10 +3,14 @@ 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 { createSharedMediaBackend } from './shared-media.js'; +export type { SharedMediaBackend } from './shared-media.js'; export { ensureClientTables, ensurePrekeyServerTables, ensureInboxServerTables, ensureKTLogTables, ensureBlobServerTables, + ensureMediaServerTables, } from './ensure-tables.js'; diff --git a/packages/shade-storage-postgres/src/postgres-media-store.ts b/packages/shade-storage-postgres/src/postgres-media-store.ts new file mode 100644 index 0000000..bd564cc --- /dev/null +++ b/packages/shade-storage-postgres/src/postgres-media-store.ts @@ -0,0 +1,160 @@ +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 { ensureMediaServerTables } from './ensure-tables.js'; + +// "relation already exists, skipping" on every start is not news. +const quiet = () => {}; + +interface MediaRow { + media_id: string; + owner_pubkey: string; + size: string; + read_token_hash: string | null; + object_key: string; + created_at: string; +} + +const toRecord = (r: MediaRow): IndexedMedia => ({ + id: r.media_id, + owner: r.owner_pubkey, + size: Number(r.size), + readTokenHash: r.read_token_hash, + key: r.object_key, + createdAt: Number(r.created_at), +}); + +/** + * The shared record of a media bucket (`ObjectMediaStore`), so any number of + * relay instances serve one library. The primary key on `media_id` is what + * decides racing uploads of one id: exactly one INSERT wins, on any instance. + */ +export class PostgresMediaIndex implements MediaIndex { + private constructor( + private readonly sql: Sql, + private readonly ownsConnection: boolean, + ) {} + + static async create(connectionString: string): Promise { + const sql = postgres(connectionString, { onnotice: quiet }); + await ensureMediaServerTables(sql); + return new PostgresMediaIndex(sql, true); + } + + static async fromClient(sql: Sql): Promise { + await ensureMediaServerTables(sql); + return new PostgresMediaIndex(sql, false); + } + + async close(): Promise { + if (this.ownsConnection) await this.sql.end(); + } + + async get(id: string): Promise { + const rows = await this.sql` + SELECT media_id, owner_pubkey, size::text, read_token_hash, object_key, created_at::text + FROM shade_media_objects WHERE media_id = ${id} + `; + return rows.length === 0 ? null : toRecord(rows[0]!); + } + + async insert(rec: IndexedMedia): Promise { + const rows = await this.sql` + INSERT INTO shade_media_objects (media_id, owner_pubkey, size, read_token_hash, object_key, created_at) + VALUES (${rec.id}, ${rec.owner}, ${rec.size}, ${rec.readTokenHash}, ${rec.key}, ${rec.createdAt}) + ON CONFLICT (media_id) DO NOTHING + RETURNING media_id + `; + if (rows.length === 0) throw new MediaExistsError(rec.id); + } + + async remove(id: string): Promise { + const rows = await this.sql` + DELETE FROM shade_media_objects WHERE media_id = ${id} + RETURNING media_id, owner_pubkey, size::text, read_token_hash, object_key, created_at::text + `; + return rows.length === 0 ? null : toRecord(rows[0]!); + } + + async usage(owner: string): Promise { + const rows = await this.sql<{ n: string }[]>` + SELECT COALESCE(SUM(size), 0)::text AS n FROM shade_media_objects WHERE owner_pubkey = ${owner} + `; + return Number(rows[0]!.n); + } + + async totalBytes(): Promise { + const rows = await this.sql<{ n: string }[]>`SELECT COALESCE(SUM(size), 0)::text AS n FROM shade_media_objects`; + return Number(rows[0]!.n); + } + + async list(owner: string): Promise { + const rows = await this.sql` + SELECT media_id, owner_pubkey, size::text, read_token_hash, object_key, created_at::text + FROM shade_media_objects WHERE owner_pubkey = ${owner} + ORDER BY created_at DESC + `; + return rows.map((r) => { + const { key: _key, ...rec } = toRecord(r); + return rec; + }); + } +} + +/** + * Live-channel pins shared by relay instances. A channel is pinned to the + * first signing key that opens it; the upsert only refreshes a pin whose key + * matches, so two relays cannot pin one channel to two keys. + */ +export class PostgresLivePinStore implements LivePinStore { + private constructor( + private readonly sql: Sql, + private readonly ownsConnection: boolean, + private readonly ttlMs: number, + ) {} + + static async create(connectionString: string, ttlMs = 30 * 24 * 3600 * 1000): Promise { + const sql = postgres(connectionString, { onnotice: quiet }); + await ensureMediaServerTables(sql); + return new PostgresLivePinStore(sql, true, ttlMs); + } + + static async fromClient(sql: Sql, ttlMs = 30 * 24 * 3600 * 1000): Promise { + await ensureMediaServerTables(sql); + return new PostgresLivePinStore(sql, false, ttlMs); + } + + async close(): Promise { + if (this.ownsConnection) await this.sql.end(); + } + + async get(channelId: string): Promise { + const rows = await this.sql<{ channel_id: string; signing_key: string; read_token_hash: string; pinned_at: string; last_seen: string }[]>` + SELECT channel_id, signing_key, read_token_hash, pinned_at::text, last_seen::text + FROM shade_live_pins WHERE channel_id = ${channelId} + `; + if (rows.length === 0) return null; + const r = rows[0]!; + return { + channelId: r.channel_id, + signingKey: r.signing_key, + readTokenHash: r.read_token_hash, + pinnedAt: Number(r.pinned_at), + lastSeen: Number(r.last_seen), + }; + } + + async put(pin: LivePin): Promise { + // Pins idle past the TTL are released, as in FileLivePinStore. + await this.sql`DELETE FROM shade_live_pins WHERE last_seen < ${pin.lastSeen - this.ttlMs}`; + const rows = await this.sql` + INSERT INTO shade_live_pins (channel_id, signing_key, read_token_hash, pinned_at, last_seen) + VALUES (${pin.channelId}, ${pin.signingKey}, ${pin.readTokenHash}, ${pin.pinnedAt}, ${pin.lastSeen}) + ON CONFLICT (channel_id) DO UPDATE + SET read_token_hash = EXCLUDED.read_token_hash, last_seen = EXCLUDED.last_seen + WHERE shade_live_pins.signing_key = EXCLUDED.signing_key + RETURNING channel_id + `; + if (rows.length === 0) throw new LivePinTakenError(pin.channelId); + } +} diff --git a/packages/shade-storage-postgres/src/shared-media.ts b/packages/shade-storage-postgres/src/shared-media.ts new file mode 100644 index 0000000..c1ca2d2 --- /dev/null +++ b/packages/shade-storage-postgres/src/shared-media.ts @@ -0,0 +1,44 @@ +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'; + +export interface SharedMediaBackend { + store: MediaStore; + pins: LivePinStore; + /** Where the bytes go, for logs — no credentials. */ + describe: string; + /** Reclaim unreferenced objects and dead uploads; safe on every instance at once. */ + sweep(): Promise<{ objects: number; uploads: number }>; + close(): Promise; +} + +/** + * A media backend several relay instances can share: sealed bytes in an S3 + * bucket, records and live pins in Postgres. Both the Shade container + * (`SHADE_MEDIA_S3_URL` + `SHADE_MEDIA_PG_URL`) and `shade media serve --s3 + * --pg` build it here, so they behave alike. Tables are created on first use. + */ +export async function createSharedMediaBackend(opts: { s3Url: string; pgUrl: string }): Promise { + const { bucket, prefix } = S3Bucket.fromUrl(opts.s3Url); + // "relation already exists, skipping" on every start is not news. + const sql = postgres(opts.pgUrl, { onnotice: () => {} }); + try { + const index = await PostgresMediaIndex.fromClient(sql); + const pins = await PostgresLivePinStore.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. + await bucket.list(`${prefix}objects/`); + return { + store, + pins, + describe: `s3 ${new URL(opts.s3Url).host}/${bucket.bucket}/${prefix}`, + sweep: () => store.sweep(), + close: () => sql.end(), + }; + } catch (e) { + await sql.end(); + throw e; + } +} diff --git a/packages/shade-storage-postgres/tests/postgres-media.test.ts b/packages/shade-storage-postgres/tests/postgres-media.test.ts new file mode 100644 index 0000000..f981455 --- /dev/null +++ b/packages/shade-storage-postgres/tests/postgres-media.test.ts @@ -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/); + }); +});