Files
Shade/packages/shade-media/tests/upload.test.ts
Sterister bd4882e1b8 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>
2026-10-18 23:39:25 +02:00

288 lines
14 KiB
TypeScript

/**
* Uploads in pieces (`upload.ts`): a film goes up in bounded requests, a
* dropped connection or a relay restart costs one piece, and the relay
* refuses every piece that is not the next one.
*/
import { describe, test, expect, afterAll } from 'bun:test';
import { appendFile, mkdtemp, rm, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Hono } from 'hono';
import { createMediaRoutes, FileMediaStore, MemoryMediaStore, BadPieceError } from '../src/server.js';
import type { MediaStore } from '../src/server.js';
import { MediaClient, OwnerKey, openGrant, sealMediaBytes, chunkFor, DEFAULT_CHUNK_BYTES, MAX_PIECE_BYTES, OFFSET_HEADER } from '../src/index.js';
import { UPLOAD_WINDOW } from '../src/upload.js';
import { toHex } from '../src/bytes.js';
const MiB = 1024 * 1024;
const dirs: string[] = [];
async function tempDir(): Promise<string> {
const d = await mkdtemp(join(tmpdir(), 'shade-upload-'));
dirs.push(d);
return d;
}
afterAll(async () => {
for (const d of dirs) await rm(d, { recursive: true, force: true });
});
function pattern(n: number, seed = 1): Uint8Array {
const out = new Uint8Array(n);
for (let i = 0; i < n; i++) out[i] = (i * 31 + (i >> 9) + seed) & 0xff;
return out;
}
function serve(store: MediaStore) {
const app = new Hono().route('/', createMediaRoutes(store));
const server = Bun.serve({ port: 0, fetch: (req) => app.fetch(req) });
return { app, server, base: `http://localhost:${server.port}` };
}
/** A sealed file a little over two pieces: three requests, the last one short. */
const sealed = sealMediaBytes(pattern(2 * DEFAULT_CHUNK_BYTES + 3 * MiB + 77), { meta: { name: 'Film.mkv' } });
describe('pieces', () => {
test('chunkFor: the default, larger only when 10 000 pieces would not hold the file', () => {
expect(chunkFor(1)).toBe(DEFAULT_CHUNK_BYTES);
expect(chunkFor(10_000 * DEFAULT_CHUNK_BYTES)).toBe(DEFAULT_CHUNK_BYTES);
expect(chunkFor(10_000 * DEFAULT_CHUNK_BYTES + 1)).toBe(DEFAULT_CHUNK_BYTES + MiB);
expect(chunkFor(10_000 * MAX_PIECE_BYTES * 2)).toBe(MAX_PIECE_BYTES);
});
for (const [name, make] of [
['memory', async () => new MemoryMediaStore()],
['disk', async () => new FileMediaStore(await tempDir())],
] as const) {
test(`${name}: a film in pieces plays back bit for bit, with progress after each piece`, async () => {
const { bytes, result } = await sealed;
const { server, base } = serve(await make());
try {
const seen: number[] = [];
const grant = await new MediaClient(base, OwnerKey.generate()).putSealed(result, new Blob([bytes]), {
meta: { name: 'Film.mkv' },
onProgress: (sent) => seen.push(sent),
});
// Pieces fly side by side, so they are answered in any order; the count only grows.
expect(seen.length).toBe(4);
expect(seen[0]).toBe(0);
expect(seen.at(-1)).toBe(bytes.length);
expect([...seen].sort((x, y) => x - y)).toEqual(seen);
const reader = await openGrant(grant);
expect(await reader.read(0, reader.size)).toEqual(pattern(2 * DEFAULT_CHUNK_BYTES + 3 * MiB + 77));
} finally {
server.stop(true);
}
});
}
test('a dropped connection costs one piece: lost before the relay saw it, and lost after it stored it', async () => {
const { bytes, result } = await sealed;
const { server, base } = serve(new MemoryMediaStore());
try {
let patches = 0;
let sentBytes = 0;
const flaky: typeof fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
if (init?.method === 'PATCH') {
patches++;
// Piece 2, first try: the connection drops before the relay gets it.
if (patches === 2) throw new Error('connection reset');
sentBytes += Number(new Headers(init.headers).get('content-length'));
const res = await fetch(input, init);
// Piece 3, first try: stored, but the answer never arrives.
if (patches === 4) throw new Error('socket hang up');
return res;
}
return fetch(input, init);
}) as typeof fetch;
const grant = await new MediaClient(base, OwnerKey.generate(), { fetch: flaky }).putSealed(result, bytes);
const reader = await openGrant(grant);
expect(await reader.read(0, reader.size)).toEqual(pattern(2 * DEFAULT_CHUNK_BYTES + 3 * MiB + 77));
// Piece 3 went once and was not sent again: the client asked how far the upload got.
expect(sentBytes).toBe(bytes.length);
} finally {
server.stop(true);
}
});
test('a relay restart in the middle: the upload resumes from the disk, a piece the log does not name is sent again', async () => {
const { bytes, result } = await sealed;
const dir = await tempDir();
const owner = OwnerKey.generate();
const id = toHex(result.mediaId);
const first = serve(new FileMediaStore(dir));
// Two pieces in, by hand, then the relay goes away.
const start = (base: string) =>
fetch(`${base}/v1/media/${id}/upload`, {
method: 'POST',
headers: { 'x-shade-size': String(bytes.length), ...owner.headers({ op: 'upload', id, size: bytes.length, readTokenHash: '' }) },
});
const piece = (base: string, offset: number, length: number) =>
fetch(`${base}/v1/media/${id}/upload`, {
method: 'PATCH',
headers: { [OFFSET_HEADER]: String(offset), ...owner.headers({ op: 'piece', id, offset, length }) },
body: bytes.slice(offset, offset + length),
});
expect((await start(first.base)).status).toBe(201);
expect((await piece(first.base, 0, DEFAULT_CHUNK_BYTES)).status).toBe(200);
expect((await piece(first.base, DEFAULT_CHUNK_BYTES, DEFAULT_CHUNK_BYTES)).status).toBe(200);
first.server.stop(true);
// A crash in the middle of piece 3 left part of it on disk, and no log entry.
await appendFile(join(dir, 'uploads', `${id}.part`), bytes.slice(2 * DEFAULT_CHUNK_BYTES, 2 * DEFAULT_CHUNK_BYTES + 1000));
const second = serve(new FileMediaStore(dir));
try {
const resumed = await start(second.base);
expect(resumed.status).toBe(200);
expect(await resumed.json()).toMatchObject({ received: 2 * DEFAULT_CHUNK_BYTES, chunk: DEFAULT_CHUNK_BYTES });
// The client does the rest: it asks, and sends only piece 3.
const grant = await new MediaClient(second.base, owner).putSealed(result, bytes, { readToken: null });
const reader = await openGrant(grant);
expect(await reader.read(0, reader.size)).toEqual(pattern(2 * DEFAULT_CHUNK_BYTES + 3 * MiB + 77));
expect(await stat(join(dir, 'uploads', `${id}.part`)).catch(() => null)).toBeNull();
} finally {
second.server.stop(true);
}
});
test('pieces land in any order within the window; a piece twice is a no-op; only from the owner who started it', async () => {
const store = new MemoryMediaStore();
const { app } = serve(store);
const owner = OwnerKey.generate();
const id = 'c'.repeat(32);
const chunk = DEFAULT_CHUNK_BYTES;
const size = 10 * chunk + 5; // promised; never finished here
const bytes = pattern(size);
const req = (method: string, headers: Record<string, string>, body?: Uint8Array) =>
app.fetch(new Request(`http://relay/v1/media/${id}/upload`, { method, headers, ...(body !== undefined ? { body } : {}) }));
const start = () => req('POST', { 'x-shade-size': String(size), ...owner.headers({ op: 'upload', id, size, readTokenHash: '' }) });
const piece = (offset: number, length = Math.min(chunk, size - offset), who = owner) =>
req(
'PATCH',
{ 'content-length': String(length), [OFFSET_HEADER]: String(offset), ...who.headers({ op: 'piece', id, offset, length }) },
bytes.slice(offset, offset + length),
);
const startRes = await start();
expect(startRes.status).toBe(201);
expect(await startRes.json()).toEqual({ id, size, chunk, window: UPLOAD_WINDOW, received: 0, landed: [] });
const ahead = await piece(UPLOAD_WINDOW * chunk);
expect(ahead.status).toBe(409);
expect(await ahead.json()).toEqual({ error: 'OFFSET', received: 0 });
// Inside the window, before the pieces ahead of it: taken, and reported as landed.
expect(await (await piece(3 * chunk)).json()).toEqual({ id, received: 0 });
expect((await (await start()).json()).landed).toEqual([3]);
expect((await piece(1)).status).toBe(400); // not where a piece starts
expect((await piece(0, chunk - 1)).status).toBe(400); // short, and not the last
expect((await piece(0, chunk, OwnerKey.generate())).status).toBe(404); // someone else's upload
// A signature over one offset does not carry another.
const replay = await req(
'PATCH',
{ 'content-length': String(chunk), [OFFSET_HEADER]: '0', ...owner.headers({ op: 'piece', id, offset: chunk, length: chunk }) },
bytes.slice(0, chunk),
);
expect(replay.status).toBe(401);
expect(await (await piece(chunk)).json()).toEqual({ id, received: 0 });
expect(await (await piece(0)).json()).toEqual({ id, received: 2 * chunk });
// Again (a retry that crossed its answer): nothing changes.
expect(await (await piece(0)).json()).toEqual({ id, received: 2 * chunk });
expect(await (await piece(2 * chunk)).json()).toEqual({ id, received: 4 * chunk }); // piece 3 was waiting
expect((await (await start()).json()).landed).toEqual([]);
// Starting again on other terms is refused; on the same terms it is a resume.
const other = await req('POST', { 'x-shade-size': String(size + 1), ...owner.headers({ op: 'upload', id, size: size + 1, readTokenHash: '' }) });
expect(other.status).toBe(409);
expect((await other.json()).error).toBe('UPLOAD_CONFLICT');
// The upload's size counts against the owner already: it is promised space.
expect(await store.usage(owner.id)).toBe(size);
const abort = await req('DELETE', owner.headers({ op: 'abort', id }));
expect(abort.status).toBe(200);
expect(await store.usage(owner.id)).toBe(0);
expect((await piece(4 * chunk)).status).toBe(404);
});
test('a single PUT holds one piece at most; bigger files are told to go up in pieces', async () => {
const { app } = serve(new MemoryMediaStore());
const owner = OwnerKey.generate();
const id = '0'.repeat(32);
const size = MAX_PIECE_BYTES + 1;
// Refused on the headers, before any of the body is read.
const res = await app.fetch(
new Request(`http://relay/v1/media/${id}`, {
method: 'PUT',
headers: { 'content-length': String(size), ...owner.headers({ op: 'put', id, size, readTokenHash: '' }) },
body: new Uint8Array(16),
}),
);
expect(res.status).toBe(413);
expect((await res.json()).error).toBe('USE_UPLOAD');
});
test('a file whose footer is wrong is refused when its last piece lands, and nothing is kept', async () => {
const { bytes, result } = await sealed;
const store = new FileMediaStore(await tempDir());
const { server, base } = serve(store);
try {
const broken = bytes.slice();
broken[broken.length - 3]! ^= 0xff;
const owner = OwnerKey.generate();
await expect(new MediaClient(base, owner).putSealed(result, broken)).rejects.toThrow(/422/);
expect(await store.getUpload(toHex(result.mediaId))).toBeNull();
expect(await store.usage(owner.id)).toBe(0);
expect(await store.get(toHex(result.mediaId))).toBeNull();
} finally {
server.stop(true);
}
});
test('disk: the same piece twice at once is written once to the log; pieces out of order fill in', async () => {
const { bytes, result } = await sealed;
const dir = await tempDir();
const store = new FileMediaStore(dir);
const id = toHex(result.mediaId);
const chunk = DEFAULT_CHUNK_BYTES;
await store.openUpload({ id, owner: 'o', size: bytes.length, readTokenHash: null, chunk, createdAt: 1 });
expect(await store.appendUpload(id, chunk, bytes.slice(chunk, 2 * chunk))).toBe(0);
const one = bytes.slice(0, chunk);
expect(await Promise.all([store.appendUpload(id, 0, one), store.appendUpload(id, 0, one)])).toEqual([2 * chunk, 2 * chunk]);
expect((await stat(join(dir, 'uploads', `${id}.log`))).size).toBe(8); // pieces 1 and 0, once each
await expect(store.appendUpload(id, (UPLOAD_WINDOW + 2) * chunk, one)).rejects.toBeInstanceOf(BadPieceError); // past the end
// A restart keeps what landed, in the order it landed.
const again = new FileMediaStore(dir);
expect(await again.getUpload(id)).toMatchObject({ received: 2 * chunk, landed: [] });
await again.appendUpload(id, 2 * chunk, bytes.slice(2 * chunk));
const rec = await again.completeUpload(id, async () => {});
expect(rec.size).toBe(bytes.length);
const body = await again.body(id, 0, bytes.length);
expect(new Uint8Array(await new Response(body).arrayBuffer())).toEqual(bytes);
});
test('sweep: an upload nobody sent a piece to within the grace period is dropped; a live one is kept', async () => {
const dir = await tempDir();
let now = Date.now();
const store = new FileMediaStore(dir, { uploadGraceMs: 60_000, now: () => now });
const terms = { owner: 'o', size: 4 * MiB, readTokenHash: null, chunk: DEFAULT_CHUNK_BYTES, createdAt: now };
await store.openUpload({ ...terms, id: 'a'.repeat(32) });
expect(await store.sweep()).toEqual({ objects: 0, uploads: 0 });
now += 61_000;
expect(await store.sweep()).toEqual({ objects: 0, uploads: 1 });
expect(await store.getUpload('a'.repeat(32))).toBeNull();
expect(await store.totalBytes()).toBe(0);
});
test('the read token chosen at the start guards the finished file', async () => {
const { bytes, result } = await sealed;
const { server, base } = serve(new MemoryMediaStore());
try {
const grant = await new MediaClient(base, OwnerKey.generate()).putSealed(result, bytes);
expect(grant.readToken).toBeDefined();
expect((await fetch(grant.url!, { method: 'HEAD' })).status).toBe(404);
const reader = await openGrant(grant);
expect(await reader.read(0, 1000)).toEqual(pattern(2 * DEFAULT_CHUNK_BYTES + 3 * MiB + 77).subarray(0, 1000));
} finally {
server.stop(true);
}
});
});