105 lines
3.6 KiB
TypeScript
105 lines
3.6 KiB
TypeScript
|
|
/**
|
||
|
|
* 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));
|
||
|
|
}
|
||
|
|
}
|