A chunk of 0 looped forever, a huge chunk held the film in memory and a huge window opened a request (a thread on Kotlin) per piece. statusProblem checks chunk, window, received and landed; the client window is capped at 16. Same in MediaUploader, with tests on both sides. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
337 lines
14 KiB
TypeScript
337 lines
14 KiB
TypeScript
/**
|
|
* Client for the media routes: upload sealed files, list and delete your
|
|
* own, and open anything you hold a grant for.
|
|
*/
|
|
|
|
import { ALBUM_MIME, albumMeta, encodeAlbum, parseAlbum } from './album.js';
|
|
import type { Album } from './album.js';
|
|
import { randomBytes, sha256, toB64u, toHex } from './bytes.js';
|
|
import { MediaFormatError } from './errors.js';
|
|
import { mediaGrantFrom, mediaKeysOf } from './grant.js';
|
|
import type { MediaGrant } from './grant.js';
|
|
import { READ_HASH_HEADER, READ_TOKEN_HEADER } from './owner.js';
|
|
import type { OwnerKey } from './owner.js';
|
|
import { MediaReader, sealMediaBytes } from './sealed.js';
|
|
import type { MediaMeta, ReaderOptions, SealOptions, SealResult } from './sealed.js';
|
|
import { HttpRangeSource } from './source.js';
|
|
import { DEFAULT_CHUNK_BYTES, MAX_CLIENT_WINDOW, OFFSET_HEADER, statusProblem } from './upload.js';
|
|
|
|
export function mediaUrl(server: string, mediaId: Uint8Array): string {
|
|
return `${server.replace(/\/$/, '')}/v1/media/${toHex(mediaId)}`;
|
|
}
|
|
|
|
export interface MediaList {
|
|
items: { id: string; size: number; createdAt: number }[];
|
|
usage: number;
|
|
}
|
|
|
|
export interface PutOptions {
|
|
/** Token viewers must present. Default: a fresh random one per file. `null` = public ciphertext. */
|
|
readToken?: Uint8Array | null;
|
|
/** Copied into the grant so a library can list titles without opening each file. */
|
|
meta?: MediaMeta;
|
|
/** Bytes the relay has acknowledged so far, after each piece. */
|
|
onProgress?: (sent: number, total: number) => void;
|
|
}
|
|
|
|
/**
|
|
* What a refusal says, for an error message: the relay's JSON as it is, but
|
|
* not an HTML error page (a proxy's, or Bun's own) poured into a terminal.
|
|
*/
|
|
async function answerText(res: Response): Promise<string> {
|
|
const text = await res.text().catch(() => '');
|
|
if ((res.headers.get('content-type') ?? '').includes('text/html') || /^\s*</.test(text)) return '';
|
|
return text.length > 300 ? `${text.slice(0, 300)}…` : text;
|
|
}
|
|
|
|
/** Failed tries in a row before a resumable upload gives up. */
|
|
const MAX_TRIES = 8;
|
|
|
|
/** The relay is restarting, overloaded or the network dropped: try again. */
|
|
class Transient extends Error {}
|
|
|
|
const backoff = (attempt: number) => Bun.sleep(Math.min(30_000, 500 * 2 ** attempt));
|
|
|
|
export class MediaClient {
|
|
private readonly fetchFn: typeof fetch;
|
|
|
|
constructor(
|
|
private readonly server: string,
|
|
private readonly owner: OwnerKey,
|
|
opts: { fetch?: typeof fetch } = {},
|
|
) {
|
|
this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
}
|
|
|
|
/**
|
|
* Upload an already sealed file. `body` must be exactly `result.sealedSize`
|
|
* bytes — a Blob/`Bun.file` streams from disk without loading the film.
|
|
*/
|
|
async putSealed(result: SealResult, body: Blob | Uint8Array, opts: PutOptions = {}): Promise<MediaGrant> {
|
|
const size = body instanceof Uint8Array ? body.length : body.size;
|
|
if (size !== result.sealedSize) {
|
|
throw new MediaFormatError(`body is ${size} bytes, the seal produced ${result.sealedSize}`);
|
|
}
|
|
const readToken = opts.readToken === undefined ? randomBytes(32) : opts.readToken;
|
|
const readTokenHash = readToken === null ? '' : toHex(await sha256(readToken));
|
|
const id = toHex(result.mediaId);
|
|
const url = mediaUrl(this.server, result.mediaId);
|
|
if (size <= DEFAULT_CHUNK_BYTES) {
|
|
const res = await this.fetchFn(url, {
|
|
method: 'PUT',
|
|
headers: {
|
|
'content-type': 'application/vnd.shade.smf1',
|
|
'content-length': String(size),
|
|
...(readTokenHash !== '' ? { [READ_HASH_HEADER]: readTokenHash } : {}),
|
|
...this.owner.headers({ op: 'put', id, size, readTokenHash }),
|
|
},
|
|
body: body as Blob,
|
|
});
|
|
if (res.status !== 201) {
|
|
throw new Error(`upload failed: HTTP ${res.status} ${await answerText(res)}`);
|
|
}
|
|
opts.onProgress?.(size, size);
|
|
} else {
|
|
await this.putInPieces(url, id, size, readTokenHash, body, opts.onProgress);
|
|
}
|
|
return mediaGrantFrom(result, {
|
|
url,
|
|
...(readToken !== null ? { readToken } : {}),
|
|
...(opts.meta !== undefined ? { meta: opts.meta } : {}),
|
|
});
|
|
}
|
|
|
|
/**
|
|
* A film, in pieces (see `upload.ts`), up to the relay's window of them in
|
|
* flight. A dropped connection or a relay restart costs the pieces in
|
|
* flight, not the upload: a failed piece is sent again after asking the
|
|
* relay whether it landed after all.
|
|
*/
|
|
private async putInPieces(
|
|
url: string,
|
|
id: string,
|
|
size: number,
|
|
readTokenHash: string,
|
|
body: Blob | Uint8Array,
|
|
onProgress?: (sent: number, total: number) => void,
|
|
): Promise<void> {
|
|
const at = `${url}/upload`;
|
|
// One piece per request in memory, read from the file only when it is
|
|
// sent. Read here rather than handed to fetch as a `Bun.file().slice()`:
|
|
// Bun (1.3.5) never finishes sending a sliced file as a request body.
|
|
const cut = async (start: number, end: number): Promise<Uint8Array> => {
|
|
if (body instanceof Uint8Array) return body.subarray(start, end);
|
|
const piece = new Uint8Array(await (body as Blob & { slice(s: number, e: number): Blob }).slice(start, end).arrayBuffer());
|
|
if (piece.length !== end - start) throw new MediaFormatError(`the file shrank: read ${piece.length} of ${end - start} bytes at ${start}`);
|
|
return piece;
|
|
};
|
|
/** A request that did not get an answer (refused, reset, timed out) is worth repeating. */
|
|
const send = async (init: RequestInit): Promise<Response> => {
|
|
try {
|
|
return await this.fetchFn(at, init);
|
|
} catch (e) {
|
|
throw new Transient((e as Error).message);
|
|
}
|
|
};
|
|
const fail = async (res: Response, what: string): Promise<never> => {
|
|
const text = await answerText(res);
|
|
if (res.status >= 500 || res.status === 429) throw new Transient(`${what}: HTTP ${res.status} ${text}`);
|
|
throw new Error(`upload failed: ${what}: HTTP ${res.status} ${text}`);
|
|
};
|
|
/** Retry `fn` while it fails transiently, with backoff; `fn` learns which try it is. */
|
|
const retrying = async <T>(fn: (attempt: number) => Promise<T>): Promise<T> => {
|
|
for (let attempt = 0; ; attempt++) {
|
|
try {
|
|
return await fn(attempt);
|
|
} catch (e) {
|
|
if (!(e instanceof Transient)) throw e;
|
|
if (attempt + 1 >= MAX_TRIES) throw new Error(`upload failed after ${MAX_TRIES} tries: ${e.message}`);
|
|
await backoff(attempt + 1);
|
|
}
|
|
}
|
|
};
|
|
type Status = { chunk: number; window?: number; received: number; landed?: number[]; complete?: boolean };
|
|
/** Start the upload, or learn how far it got. */
|
|
const status = async (): Promise<Status> => {
|
|
const res = await send({
|
|
method: 'POST',
|
|
headers: {
|
|
'x-shade-size': String(size),
|
|
...(readTokenHash !== '' ? { [READ_HASH_HEADER]: readTokenHash } : {}),
|
|
...this.owner.headers({ op: 'upload', id, size, readTokenHash }),
|
|
},
|
|
});
|
|
if (res.status !== 200 && res.status !== 201) return fail(res, 'start');
|
|
const st = (await res.json().catch(() => {
|
|
throw new Transient("start: the relay's answer is not JSON");
|
|
})) as Status;
|
|
if (st.complete === true) return st;
|
|
const problem = statusProblem(st, size);
|
|
if (problem !== null) throw new Error(`upload failed: the relay's upload status is unusable: ${problem}`);
|
|
return st;
|
|
};
|
|
const has = (st: Status, offset: number) => offset < st.received || (st.landed ?? []).includes(offset / st.chunk);
|
|
|
|
const opened = await retrying(status);
|
|
if (opened.complete === true) {
|
|
onProgress?.(size, size);
|
|
return;
|
|
}
|
|
const { chunk } = opened;
|
|
const window = Math.min(MAX_CLIENT_WINDOW, Math.max(1, opened.window ?? 1));
|
|
let acked = 0;
|
|
let complete = false;
|
|
const todo: number[] = [];
|
|
for (let off = 0; off < size; off += chunk) {
|
|
if (has(opened, off)) acked += Math.min(chunk, size - off);
|
|
else todo.push(off);
|
|
}
|
|
onProgress?.(acked, size);
|
|
|
|
/** One piece until the relay has it; true once the relay stored the whole file. */
|
|
const sendPiece = (offset: number) =>
|
|
retrying(async (attempt): Promise<boolean> => {
|
|
if (attempt > 0) {
|
|
// It may have landed before the connection dropped: ask before sending it again.
|
|
const st = await status();
|
|
if (st.complete === true) return true;
|
|
if (has(st, offset)) return false;
|
|
}
|
|
const length = Math.min(chunk, size - offset);
|
|
const piece = await cut(offset, offset + length);
|
|
const res = await send({
|
|
method: 'PUT',
|
|
headers: {
|
|
'content-type': 'application/octet-stream',
|
|
'content-length': String(length),
|
|
[OFFSET_HEADER]: String(offset),
|
|
...this.owner.headers({ op: 'piece', id, offset, length }),
|
|
},
|
|
body: piece as Uint8Array<ArrayBuffer>,
|
|
});
|
|
if (res.status === 201) return true;
|
|
if (res.status === 200) return false;
|
|
// Ahead of the window (pieces before it are still on the way): later.
|
|
if (res.status === 409) {
|
|
const j = (await res.json().catch(() => ({}))) as { error?: string };
|
|
if (j.error === 'OFFSET') throw new Transient('piece ahead of the upload');
|
|
throw new Error(`upload failed: HTTP 409 ${JSON.stringify(j)}`);
|
|
}
|
|
return fail(res, `piece at ${offset}`);
|
|
});
|
|
|
|
let failure: unknown = null;
|
|
const inFlight = new Set<Promise<void>>();
|
|
const flying = new Set<number>();
|
|
/**
|
|
* The relay takes `window` pieces past what it has from the start, so a
|
|
* piece is only sent within `window` of the first one not yet answered:
|
|
* one slow piece holds the window, rather than pieces past it bouncing.
|
|
*/
|
|
const mayLaunch = () => {
|
|
if (todo.length === 0 || inFlight.size >= window) return false;
|
|
const lowest = Math.min(todo[0]!, ...flying);
|
|
return todo[0]! < lowest + window * chunk;
|
|
};
|
|
const launch = (offset: number) => {
|
|
flying.add(offset);
|
|
const p: Promise<void> = sendPiece(offset).then(
|
|
(done) => {
|
|
flying.delete(offset);
|
|
inFlight.delete(p);
|
|
if (done) complete = true;
|
|
acked += Math.min(chunk, size - offset);
|
|
if (!complete) onProgress?.(acked, size);
|
|
},
|
|
(e: unknown) => {
|
|
flying.delete(offset);
|
|
inFlight.delete(p);
|
|
failure ??= e;
|
|
},
|
|
);
|
|
inFlight.add(p);
|
|
};
|
|
while (!complete && failure === null && (todo.length > 0 || inFlight.size > 0)) {
|
|
while (failure === null && !complete && mayLaunch()) launch(todo.shift()!);
|
|
await Promise.race(inFlight);
|
|
}
|
|
await Promise.allSettled(inFlight);
|
|
if (failure !== null) throw failure;
|
|
if (!complete) {
|
|
// Every piece is in but no answer said so (they crossed a completion
|
|
// that failed and was retried): an empty piece at the end finishes it.
|
|
await retrying(async () => {
|
|
const res = await send({
|
|
method: 'PUT',
|
|
headers: { 'content-length': '0', [OFFSET_HEADER]: String(size), ...this.owner.headers({ op: 'piece', id, offset: size, length: 0 }) },
|
|
});
|
|
if (res.status !== 201) return fail(res, 'finish');
|
|
});
|
|
}
|
|
onProgress?.(size, size);
|
|
}
|
|
|
|
/** Seal in memory and upload — images, clips, documents. */
|
|
async uploadBytes(plaintext: Uint8Array, opts: SealOptions & PutOptions = {}): Promise<MediaGrant> {
|
|
const { bytes, result } = await sealMediaBytes(plaintext, opts);
|
|
return this.putSealed(result, bytes, opts.meta !== undefined ? { ...opts, meta: opts.meta } : opts);
|
|
}
|
|
|
|
/** Seal and upload an album; the grant opens every item in it. */
|
|
async uploadAlbum(album: Album, opts: Omit<PutOptions, 'meta'> = {}): Promise<MediaGrant> {
|
|
const meta = albumMeta(album.title);
|
|
return this.uploadBytes(encodeAlbum(album), { ...opts, meta });
|
|
}
|
|
|
|
async delete(mediaId: Uint8Array): Promise<boolean> {
|
|
const id = toHex(mediaId);
|
|
const res = await this.fetchFn(mediaUrl(this.server, mediaId), {
|
|
method: 'DELETE',
|
|
headers: this.owner.headers({ op: 'delete', id }),
|
|
});
|
|
if (res.status === 404) return false;
|
|
if (!res.ok) throw new Error(`delete failed: HTTP ${res.status}`);
|
|
return true;
|
|
}
|
|
|
|
async list(): Promise<MediaList> {
|
|
const res = await this.fetchFn(`${this.server.replace(/\/$/, '')}/v1/media`, {
|
|
headers: this.owner.headers({ op: 'list' }),
|
|
});
|
|
if (!res.ok) throw new Error(`list failed: HTTP ${res.status}`);
|
|
return (await res.json()) as MediaList;
|
|
}
|
|
}
|
|
|
|
/** Open a granted file over HTTP. */
|
|
export function openGrant(
|
|
grant: MediaGrant,
|
|
opts: ReaderOptions & { fetch?: typeof fetch; url?: string } = {},
|
|
): Promise<MediaReader> {
|
|
const url = opts.url ?? grant.url;
|
|
if (url === undefined) throw new MediaFormatError('grant has no URL');
|
|
const source = new HttpRangeSource(url, {
|
|
...(grant.readToken !== undefined ? { headers: { [READ_TOKEN_HEADER]: toB64u(grant.readToken) } } : {}),
|
|
...(opts.fetch !== undefined ? { fetch: opts.fetch } : {}),
|
|
});
|
|
return MediaReader.open(source, mediaKeysOf(grant), opts);
|
|
}
|
|
|
|
/** An album holds at most 10 000 grants of well under 1 KiB each. */
|
|
const MAX_ALBUM_BYTES = 16 * 1024 * 1024;
|
|
|
|
/** Open a granted album and read its items. */
|
|
export async function openAlbum(
|
|
grant: MediaGrant,
|
|
opts: ReaderOptions & { fetch?: typeof fetch; url?: string } = {},
|
|
): Promise<Album> {
|
|
return readAlbum(await openGrant(grant, opts));
|
|
}
|
|
|
|
/** The items of an album already opened as a reader. */
|
|
export async function readAlbum(reader: MediaReader): Promise<Album> {
|
|
if (reader.meta.mime !== ALBUM_MIME) throw new MediaFormatError(`not an album (${reader.meta.mime ?? 'no type'})`);
|
|
if (reader.size > MAX_ALBUM_BYTES) throw new MediaFormatError('album larger than 16 MiB');
|
|
return parseAlbum(await reader.read(0, reader.size));
|
|
}
|