Files
Shade/packages/shade-storage-postgres/src/shared-media.ts

49 lines
2.0 KiB
TypeScript
Raw Normal View History

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>
2026-10-18 22:28:58 +02:00
import postgres from 'postgres';
import { ObjectMediaStore, S3Bucket } from '@shade/media/server';
feat(media): live channels across relay instances; viewers hear when a channel goes live With several relays sharing pins, a viewer and the publisher could land on different instances and never meet. LiveRelayOptions.mesh: each relay claims the channels whose publisher it holds (LivePublisherLocator, Postgres table shade_live_publishers, heartbeat 10 s). A relay whose viewers want a channel published elsewhere subscribes to that relay once, with a viewer's own read token, and fans out locally, verifying every frame against the pin (a peer or a poisoned locator row cannot forge one). Re-following replays a backlog; frames are passed on once (seq). Viewers follow a publisher that moves. A token that fails the in-memory pin is checked against the shared pin before refusal, so a publisher back with a new read token is honoured on every instance. SHADE_MEDIA_RELAY_URL / `media serve --advertise`. Relays now send {"type":"state","live"} when a channel goes live or quiet after a viewer joined; handled by the TS client (browser) and Android's LiveWatcher. Fixed on the way: - The relay never saw its publisher leave: Hono gives each event its own WSContext and the close handler compared identity. Channels stayed "live" with nobody publishing; a replaced publisher was never closed. - FileMediaStore on an unusable directory raised an unhandled rejection at start; now each call fails with the reason. Verified: 5 mesh tests (follow, late join, publisher moving A→B with dedupe, forging peer refused, new read token) + state test, each fix mutation-checked; Postgres locator + two media services over Postgres; CLI relays with --advertise behind a round-robin HTTP+WS balancer: publisher on A, Chromium viewer on B, "live", 208 lines. Suites: media 93, storage-postgres 20, server 55; Kotlin 92 (1 skipped), 0 failures. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:44:19 +02:00
import type { LivePinStore, LivePublisherLocator, MediaStore } from '@shade/media/server';
import { PostgresLivePinStore, PostgresLivePublisherLocator, PostgresMediaIndex } from './postgres-media-store.js';
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>
2026-10-18 22:28:58 +02:00
export interface SharedMediaBackend {
store: MediaStore;
pins: LivePinStore;
feat(media): live channels across relay instances; viewers hear when a channel goes live With several relays sharing pins, a viewer and the publisher could land on different instances and never meet. LiveRelayOptions.mesh: each relay claims the channels whose publisher it holds (LivePublisherLocator, Postgres table shade_live_publishers, heartbeat 10 s). A relay whose viewers want a channel published elsewhere subscribes to that relay once, with a viewer's own read token, and fans out locally, verifying every frame against the pin (a peer or a poisoned locator row cannot forge one). Re-following replays a backlog; frames are passed on once (seq). Viewers follow a publisher that moves. A token that fails the in-memory pin is checked against the shared pin before refusal, so a publisher back with a new read token is honoured on every instance. SHADE_MEDIA_RELAY_URL / `media serve --advertise`. Relays now send {"type":"state","live"} when a channel goes live or quiet after a viewer joined; handled by the TS client (browser) and Android's LiveWatcher. Fixed on the way: - The relay never saw its publisher leave: Hono gives each event its own WSContext and the close handler compared identity. Channels stayed "live" with nobody publishing; a replaced publisher was never closed. - FileMediaStore on an unusable directory raised an unhandled rejection at start; now each call fails with the reason. Verified: 5 mesh tests (follow, late join, publisher moving A→B with dedupe, forging peer refused, new read token) + state test, each fix mutation-checked; Postgres locator + two media services over Postgres; CLI relays with --advertise behind a round-robin HTTP+WS balancer: publisher on A, Chromium viewer on B, "live", 208 lines. Suites: media 93, storage-postgres 20, server 55; Kotlin 92 (1 skipped), 0 failures. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:44:19 +02:00
/** Where each live channel's publisher is, for relays that follow one another. */
locator: LivePublisherLocator;
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>
2026-10-18 22:28:58 +02:00
/** 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<void>;
}
/**
* 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<SharedMediaBackend> {
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);
feat(media): live channels across relay instances; viewers hear when a channel goes live With several relays sharing pins, a viewer and the publisher could land on different instances and never meet. LiveRelayOptions.mesh: each relay claims the channels whose publisher it holds (LivePublisherLocator, Postgres table shade_live_publishers, heartbeat 10 s). A relay whose viewers want a channel published elsewhere subscribes to that relay once, with a viewer's own read token, and fans out locally, verifying every frame against the pin (a peer or a poisoned locator row cannot forge one). Re-following replays a backlog; frames are passed on once (seq). Viewers follow a publisher that moves. A token that fails the in-memory pin is checked against the shared pin before refusal, so a publisher back with a new read token is honoured on every instance. SHADE_MEDIA_RELAY_URL / `media serve --advertise`. Relays now send {"type":"state","live"} when a channel goes live or quiet after a viewer joined; handled by the TS client (browser) and Android's LiveWatcher. Fixed on the way: - The relay never saw its publisher leave: Hono gives each event its own WSContext and the close handler compared identity. Channels stayed "live" with nobody publishing; a replaced publisher was never closed. - FileMediaStore on an unusable directory raised an unhandled rejection at start; now each call fails with the reason. Verified: 5 mesh tests (follow, late join, publisher moving A→B with dedupe, forging peer refused, new read token) + state test, each fix mutation-checked; Postgres locator + two media services over Postgres; CLI relays with --advertise behind a round-robin HTTP+WS balancer: publisher on A, Chromium viewer on B, "live", 208 lines. Suites: media 93, storage-postgres 20, server 55; Kotlin 92 (1 skipped), 0 failures. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:44:19 +02:00
const locator = await PostgresLivePublisherLocator.fromClient(sql);
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>
2026-10-18 22:28:58 +02:00
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,
feat(media): live channels across relay instances; viewers hear when a channel goes live With several relays sharing pins, a viewer and the publisher could land on different instances and never meet. LiveRelayOptions.mesh: each relay claims the channels whose publisher it holds (LivePublisherLocator, Postgres table shade_live_publishers, heartbeat 10 s). A relay whose viewers want a channel published elsewhere subscribes to that relay once, with a viewer's own read token, and fans out locally, verifying every frame against the pin (a peer or a poisoned locator row cannot forge one). Re-following replays a backlog; frames are passed on once (seq). Viewers follow a publisher that moves. A token that fails the in-memory pin is checked against the shared pin before refusal, so a publisher back with a new read token is honoured on every instance. SHADE_MEDIA_RELAY_URL / `media serve --advertise`. Relays now send {"type":"state","live"} when a channel goes live or quiet after a viewer joined; handled by the TS client (browser) and Android's LiveWatcher. Fixed on the way: - The relay never saw its publisher leave: Hono gives each event its own WSContext and the close handler compared identity. Channels stayed "live" with nobody publishing; a replaced publisher was never closed. - FileMediaStore on an unusable directory raised an unhandled rejection at start; now each call fails with the reason. Verified: 5 mesh tests (follow, late join, publisher moving A→B with dedupe, forging peer refused, new read token) + state test, each fix mutation-checked; Postgres locator + two media services over Postgres; CLI relays with --advertise behind a round-robin HTTP+WS balancer: publisher on A, Chromium viewer on B, "live", 208 lines. Suites: media 93, storage-postgres 20, server 55; Kotlin 92 (1 skipped), 0 failures. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:44:19 +02:00
locator,
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>
2026-10-18 22:28:58 +02:00
describe: `s3 ${new URL(opts.s3Url).host}/${bucket.bucket}/${prefix}`,
sweep: () => store.sweep(),
close: () => sql.end(),
};
} catch (e) {
await sql.end();
throw e;
}
}