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