feat(media): uploads in pieces — resumable, and a relay's memory no longer grows with the film

Bun.serve reads a request body as fast as the client sends it, whether the
handler takes it or not. Whenever the store was slower than the client, one
PUT of a film put the whole film in the relay's memory: a 512 MiB upload
peaked at 762 MiB (disk) and 1011 MiB (S3).

A sealed file over 16 MiB now goes up as POST /v1/media/:id/upload plus
16 MiB PATCH pieces, each signed over its offset and length, up to 4 in
flight and landing in any order. Uploads under way are durable: on disk
uploads/<id>.part + .json + .log (the log names a piece only after fsync),
and in S3 a row in shade_media_uploads beside the multipart upload, where
piece n is part n+1. A dropped connection, a relay restart or the next piece
landing on another instance costs only the pieces in flight. The client asks
how far the upload got and sends the rest. Uploads count against quota and
are swept after 24 h without a piece. An upload still receiving pieces is
never swept, however old its multipart upload is.

The sweep is now part of every MediaStore and runs from createMediaService
(onSweep) instead of two copies of the timer. No route takes more than
64 MiB, so Bun's 128 MiB cap stays and the container's body limit covers
every route. `media put` shows progress.

bench/media-store.ts: the relay's peak RSS is 330–369 MiB at both 512 MiB
and 1.5 GiB (worst of 3 runs, both stores).

Also found:
- Bun 1.3.5 fetch never finishes sending a Bun.file().slice() body, so the
  client reads each piece itself.
- postgres.js reads a NULL element of a TEXT[] as the string "NULL", so etags
  are selected as JSON.

Tests:
- tests/upload.test.ts (11).
- S3 across two instances (+2).
- PG index (+1).
- media 114, storage-postgres 21, server 55, cli 15.
- All 27 packages type-check.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 23:39:25 +02:00
parent 5f7c6ff4b4
commit bd4882e1b8
22 changed files with 2076 additions and 101 deletions

View File

@@ -14,6 +14,7 @@ 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, OFFSET_HEADER } from './upload.js';
export function mediaUrl(server: string, mediaId: Uint8Array): string {
return `${server.replace(/\/$/, '')}/v1/media/${toHex(mediaId)}`;
@@ -29,8 +30,18 @@ export interface PutOptions {
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;
}
/** 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;
@@ -55,18 +66,23 @@ export class MediaClient {
const readTokenHash = readToken === null ? '' : toHex(await sha256(readToken));
const id = toHex(result.mediaId);
const url = mediaUrl(this.server, result.mediaId);
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 res.text().catch(() => '')}`);
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 res.text().catch(() => '')}`);
}
opts.onProgress?.(size, size);
} else {
await this.putInPieces(url, id, size, readTokenHash, body, opts.onProgress);
}
return mediaGrantFrom(result, {
url,
@@ -75,6 +91,170 @@ export class MediaClient {
});
}
/**
* 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 res.text().catch(() => '');
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');
return (await res.json()) as Status;
};
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.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: 'PATCH',
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: 'PATCH',
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);