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:
@@ -110,7 +110,7 @@ const err = (s: string) => process.stderr.write(`${s}\n`);
|
||||
|
||||
// ─── media ───────────────────────────────────────────────────
|
||||
|
||||
async function mediaServe(flags: Flags): Promise<number> {
|
||||
async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise<number> {
|
||||
const { websocket } = await import('hono/bun');
|
||||
const { createMediaService, parseOwners, mediaMaxRequestBody } = await import('./server.js');
|
||||
const dir = str(flags, 'dir') ?? process.env.SHADE_MEDIA_DIR ?? './shade-media-data';
|
||||
@@ -120,7 +120,23 @@ async function mediaServe(flags: Flags): Promise<number> {
|
||||
const own = (await loadOwnerKey()).id;
|
||||
const listed = parseOwners(str(flags, 'owners') ?? process.env.SHADE_MEDIA_OWNERS);
|
||||
const owners = flags.open === true || listed === 'any' ? 'any' : [own, ...listed];
|
||||
const svc = createMediaService({ dir, owners, dev: flags.dev === true });
|
||||
// --s3 + --pg: the library several relays share (as SHADE_MEDIA_S3_URL/_PG_URL in the container).
|
||||
const s3Url = str(flags, 's3') ?? process.env.SHADE_MEDIA_S3_URL;
|
||||
const pgUrl = str(flags, 'pg') ?? process.env.SHADE_MEDIA_PG_URL;
|
||||
let svc: import('./server.js').MediaService;
|
||||
let where = dir;
|
||||
if (s3Url !== undefined) {
|
||||
if (pgUrl === undefined) throw new UsageError('--s3 needs --pg: the bucket holds the bytes, Postgres the records relays share');
|
||||
if (hooks.sharedBackend === undefined) throw new UsageError('--s3/--pg are not available in this build (no Postgres support)');
|
||||
const backend = await hooks.sharedBackend({ s3Url, pgUrl });
|
||||
svc = createMediaService({ owners, store: backend.store, pins: backend.pins, dev: flags.dev === true });
|
||||
where = backend.describe;
|
||||
const sweep = () => backend.sweep().catch((e: unknown) => err(`! media sweep: ${(e as Error).message}`));
|
||||
setTimeout(sweep, 60_000).unref();
|
||||
setInterval(sweep, 6 * 3600_000).unref();
|
||||
} else {
|
||||
svc = createMediaService({ dir, owners, dev: flags.dev === true });
|
||||
}
|
||||
svc.app.get('/health', (c) => c.json({ ok: true, live: svc.relay.stats() }));
|
||||
const server = Bun.serve({
|
||||
port,
|
||||
@@ -131,7 +147,7 @@ async function mediaServe(flags: Flags): Promise<number> {
|
||||
// Every route here bounds its own body; the 128 MiB default would refuse films.
|
||||
maxRequestBodySize: mediaMaxRequestBody(),
|
||||
});
|
||||
err(`shade media: serving on http://localhost:${server.port} (data in ${dir})`);
|
||||
err(`shade media: serving on http://localhost:${server.port} (data in ${where})`);
|
||||
err(owners === 'any' ? 'open relay: any key may upload and publish' : `owners: ${owners.join(', ')}`);
|
||||
await new Promise(() => {});
|
||||
return 0;
|
||||
@@ -592,8 +608,11 @@ async function liveWatch(pos: string[]): Promise<number> {
|
||||
|
||||
export const MEDIA_HELP = `
|
||||
media serve [--port 3910] [--dir ./shade-media-data] [--owners k1,k2] [--open]
|
||||
[--s3 https://key:secret@host/bucket[/prefix] --pg postgres://…]
|
||||
Run a media relay: sealed store, live relay, watch page.
|
||||
Only this machine's key (and --owners) may upload/publish.
|
||||
--s3/--pg: films in a bucket, records in Postgres, so
|
||||
several relays serve one library.
|
||||
media whoami Print this machine's owner key (to add to a relay's --owners)
|
||||
media put <file|dir>… --server URL [--album T] [--name N] [--mime M] [--web] [--public] [--json]
|
||||
Seal a film/video/image/song, upload it, print a watch link.
|
||||
@@ -619,14 +638,27 @@ export const MEDIA_HELP = `
|
||||
`;
|
||||
|
||||
/** Entry for `shade media …` / `shade live …`. Returns the exit code. */
|
||||
export async function runMediaCli(group: 'media' | 'live', argv: string[]): Promise<number> {
|
||||
/**
|
||||
* What the CLI cannot reach on its own. `@shade/media` does not depend on
|
||||
* Postgres; the `shade` binary does, and hands the shared backend in.
|
||||
*/
|
||||
export interface MediaCliHooks {
|
||||
sharedBackend?: (o: { s3Url: string; pgUrl: string }) => Promise<{
|
||||
store: import('./server.js').MediaStore;
|
||||
pins: import('./server.js').LivePinStore;
|
||||
describe: string;
|
||||
sweep(): Promise<unknown>;
|
||||
}>;
|
||||
}
|
||||
|
||||
export async function runMediaCli(group: 'media' | 'live', argv: string[], hooks: MediaCliHooks = {}): Promise<number> {
|
||||
const [sub, ...rest] = argv;
|
||||
const { pos, flags } = parseArgs(rest);
|
||||
try {
|
||||
if (group === 'media') {
|
||||
switch (sub) {
|
||||
case 'serve':
|
||||
return await mediaServe(flags);
|
||||
return await mediaServe(flags, hooks);
|
||||
case 'whoami':
|
||||
out((await loadOwnerKey()).id);
|
||||
return 0;
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -45,15 +45,29 @@ export interface LivePin {
|
||||
|
||||
export interface LivePinStore {
|
||||
get(channelId: string): Promise<LivePin | null>;
|
||||
/**
|
||||
* 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<void>;
|
||||
}
|
||||
|
||||
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<string, LivePin>();
|
||||
async get(id: string): Promise<LivePin | null> {
|
||||
return this.pins.get(id) ?? null;
|
||||
}
|
||||
async put(pin: LivePin): Promise<void> {
|
||||
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<void> {
|
||||
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.
|
||||
|
||||
333
packages/shade-media/src/server/object-store.ts
Normal file
333
packages/shade-media/src/server/object-store.ts
Normal file
@@ -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,
|
||||
* `<prefix>objects/<id>/<random>.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<IndexedMedia | null>;
|
||||
/** Insert, or throw `MediaExistsError` if the id already has a record — atomically. */
|
||||
insert(rec: IndexedMedia): Promise<void>;
|
||||
/** Remove and return the record, or null if there was none. */
|
||||
remove(id: string): Promise<IndexedMedia | null>;
|
||||
usage(owner: string): Promise<number>;
|
||||
totalBytes(): Promise<number>;
|
||||
/** Newest first. */
|
||||
list(owner: string): Promise<MediaRecord[]>;
|
||||
}
|
||||
|
||||
/** 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<string, IndexedMedia>();
|
||||
async get(id: string): Promise<IndexedMedia | null> {
|
||||
return this.recs.get(id) ?? null;
|
||||
}
|
||||
async insert(rec: IndexedMedia): Promise<void> {
|
||||
if (this.recs.has(rec.id)) throw new MediaExistsError(rec.id);
|
||||
this.recs.set(rec.id, rec);
|
||||
}
|
||||
async remove(id: string): Promise<IndexedMedia | null> {
|
||||
const r = this.recs.get(id) ?? null;
|
||||
this.recs.delete(id);
|
||||
return r;
|
||||
}
|
||||
async usage(owner: string): Promise<number> {
|
||||
let n = 0;
|
||||
for (const r of this.recs.values()) if (r.owner === owner) n += r.size;
|
||||
return n;
|
||||
}
|
||||
async totalBytes(): Promise<number> {
|
||||
let n = 0;
|
||||
for (const r of this.recs.values()) n += r.size;
|
||||
return n;
|
||||
}
|
||||
async list(owner: string): Promise<MediaRecord[]> {
|
||||
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<MediaRecord | null> {
|
||||
return this.index.get(id).then((r) => (r === null ? null : strip(r)));
|
||||
}
|
||||
|
||||
usage(owner: string): Promise<number> {
|
||||
return this.index.usage(owner);
|
||||
}
|
||||
|
||||
totalBytes(): Promise<number> {
|
||||
return this.index.totalBytes();
|
||||
}
|
||||
|
||||
list(owner: string): Promise<MediaRecord[]> {
|
||||
return this.index.list(owner);
|
||||
}
|
||||
|
||||
async begin(id: string): Promise<MediaUpload> {
|
||||
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<void>[] = [];
|
||||
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<ReadableStream<Uint8Array>> {
|
||||
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<Uint8Array>(
|
||||
{
|
||||
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<boolean> {
|
||||
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;
|
||||
}
|
||||
323
packages/shade-media/src/server/s3.ts
Normal file
323
packages/shade-media/src/server/s3.ts
Normal file
@@ -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<string, string>;
|
||||
/** Headers to sign, any case; `host`, `x-amz-date` and `x-amz-content-sha256` are added. */
|
||||
headers: Record<string, string>;
|
||||
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<string, string> {
|
||||
const service = input.service ?? 's3';
|
||||
const date = input.amzDate.slice(0, 8);
|
||||
const headers: Record<string, string> = {};
|
||||
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<string, string>)[name] ?? m;
|
||||
});
|
||||
}
|
||||
|
||||
const tag = (xml: string, name: string) => {
|
||||
const m = new RegExp(`<${name}>([\\s\\S]*?)</${name}>`).exec(xml);
|
||||
return m === null ? undefined : xmlText(m[1]!);
|
||||
};
|
||||
|
||||
const xmlEscape = (s: string) => s.replace(/&/g, '&').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)://<access key>:<secret>@<endpoint host>/<bucket>[/<prefix>][?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.<region>.amazonaws.com` host, else `us-east-1` (what R2, MinIO
|
||||
* and SeaweedFS accept).
|
||||
*/
|
||||
static fromUrl(raw: string, env: Record<string, string | undefined> = 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/<bucket>)');
|
||||
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<string, string>; headers?: Record<string, string>; body?: Uint8Array; ok?: number[] } = {},
|
||||
): Promise<Response> {
|
||||
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<ArrayBuffer> } : {}) });
|
||||
} 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<void> {
|
||||
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<Uint8Array> {
|
||||
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<number | null> {
|
||||
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<void> {
|
||||
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<string, string> = { '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(/<Contents>([\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<string> {
|
||||
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<string> {
|
||||
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<void> {
|
||||
const body = new TextEncoder().encode(
|
||||
`<CompleteMultipartUpload>${etags.map((e, i) => `<Part><PartNumber>${i + 1}</PartNumber><ETag>${xmlEscape(e)}</ETag></Part>`).join('')}</CompleteMultipartUpload>`,
|
||||
);
|
||||
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 (/<Error>/.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(/<Upload>([\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<void> {
|
||||
await this.request('DELETE', key, { query: { uploadId }, ok: [200, 204, 404] });
|
||||
}
|
||||
}
|
||||
@@ -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 `<dir>/media/` — e.g. an
|
||||
* `ObjectMediaStore` (S3 + a shared index) when several relays serve one library.
|
||||
*/
|
||||
store?: MediaStore;
|
||||
/** Live-channel pins, instead of `<dir>/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);
|
||||
|
||||
137
packages/shade-media/tests/object-store.test.ts
Normal file
137
packages/shade-media/tests/object-store.test.ts
Normal file
@@ -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<typeof S3Bucket.fromUrl>);
|
||||
// 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);
|
||||
});
|
||||
36
packages/shade-media/tests/s3.test.ts
Normal file
36
packages/shade-media/tests/s3.test.ts
Normal file
@@ -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/);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user