feat(media): @shade/media — seekable sealed media (SMF1), live channels, media routes and live relay
SMF1 seals a film, video, image or song once into a file any Range-capable store can serve; the reader fetches only segments under the playhead and checks each against a digest table pinned by the grant's root digest. Live channels use a sender-key chain with per-frame Ed25519 signatures, sticky init frames and keyframe snapshots for late joiners, and epoch rotation to remove a viewer. Server side: a disk-backed media store with signed owner uploads and a WebSocket relay with bounded backlog. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
104
packages/shade-media/src/source.ts
Normal file
104
packages/shade-media/src/source.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Where sealed bytes come from. A reader needs exactly two things of a
|
||||
* store — its size, and a byte range — which is why a film can live on the
|
||||
* relay, behind nginx, in an S3 bucket or on a USB disk without the reader
|
||||
* knowing which.
|
||||
*/
|
||||
|
||||
import { MediaFormatError } from './errors.js';
|
||||
|
||||
export interface RangeSource {
|
||||
size(): Promise<number>;
|
||||
/** Exactly `length` bytes from `offset`; fewer only past the end. */
|
||||
read(offset: number, length: number): Promise<Uint8Array>;
|
||||
}
|
||||
|
||||
export class MemorySource implements RangeSource {
|
||||
constructor(private readonly bytes: Uint8Array) {}
|
||||
async size(): Promise<number> {
|
||||
return this.bytes.length;
|
||||
}
|
||||
async read(offset: number, length: number): Promise<Uint8Array> {
|
||||
return this.bytes.subarray(offset, offset + length);
|
||||
}
|
||||
}
|
||||
|
||||
export interface HttpRangeSourceOptions {
|
||||
/** Extra headers on every request — the read token rides here. */
|
||||
headers?: Record<string, string>;
|
||||
fetch?: typeof fetch;
|
||||
/** Attempts per range on a network error or 5xx. Default 3. */
|
||||
retries?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP Range reads. Works against the Shade media routes and any server that
|
||||
* honours `Range` (nginx, S3, `bun --serve`).
|
||||
*/
|
||||
export class HttpRangeSource implements RangeSource {
|
||||
private knownSize: number | null = null;
|
||||
private readonly fetchFn: typeof fetch;
|
||||
private readonly headers: Record<string, string>;
|
||||
private readonly retries: number;
|
||||
|
||||
constructor(
|
||||
private readonly url: string,
|
||||
opts: HttpRangeSourceOptions = {},
|
||||
) {
|
||||
this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
||||
this.headers = opts.headers ?? {};
|
||||
this.retries = Math.max(1, opts.retries ?? 3);
|
||||
}
|
||||
|
||||
async size(): Promise<number> {
|
||||
if (this.knownSize !== null) return this.knownSize;
|
||||
const res = await this.attempt(() =>
|
||||
this.fetchFn(this.url, { method: 'HEAD', headers: this.headers }),
|
||||
);
|
||||
const len = Number(res.headers.get('content-length'));
|
||||
if (!Number.isSafeInteger(len) || len < 0) {
|
||||
throw new MediaFormatError(`HEAD ${this.url} gave no usable Content-Length`);
|
||||
}
|
||||
this.knownSize = len;
|
||||
return len;
|
||||
}
|
||||
|
||||
async read(offset: number, length: number): Promise<Uint8Array> {
|
||||
if (length === 0) return new Uint8Array(0);
|
||||
const res = await this.attempt(() =>
|
||||
this.fetchFn(this.url, {
|
||||
headers: { ...this.headers, Range: `bytes=${offset}-${offset + length - 1}` },
|
||||
}),
|
||||
);
|
||||
const body = new Uint8Array(await res.arrayBuffer());
|
||||
if (res.status === 206) return body;
|
||||
// A server that ignores Range sends the whole file with 200. Correct, if
|
||||
// wasteful — slice it rather than fail, but only if it really is whole.
|
||||
if (res.status === 200 && body.length >= offset + length) {
|
||||
return body.subarray(offset, offset + length);
|
||||
}
|
||||
throw new MediaFormatError(`GET ${this.url} answered ${res.status} to a Range request`);
|
||||
}
|
||||
|
||||
private async attempt(run: () => Promise<Response>): Promise<Response> {
|
||||
let lastErr: unknown;
|
||||
for (let i = 0; i < this.retries; i++) {
|
||||
try {
|
||||
const res = await run();
|
||||
if (res.status >= 500) {
|
||||
lastErr = new Error(`HTTP ${res.status} from ${this.url}`);
|
||||
} else if (!res.ok) {
|
||||
// 4xx will not get better by asking again — a bad token, a missing file.
|
||||
throw new MediaFormatError(`HTTP ${res.status} from ${this.url}: ${await res.text().catch(() => '')}`);
|
||||
} else {
|
||||
return res;
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof MediaFormatError) throw e;
|
||||
lastErr = e;
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 150 * 2 ** i));
|
||||
}
|
||||
throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user