Files
Shade/packages/shade-media/tests/upload.test.ts
Sterister 7d45be8712 fix(media): an uploader checks the relay's upload status before trusting it
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>
2026-10-19 00:31:06 +02:00

308 lines
15 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 === 'PUT') {
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: 'PUT',
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(
'PUT',
{ '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(
'PUT',
{ '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 relay whose upload status is unusable is refused at once, not looped on', async () => {
const bytes = new Uint8Array(DEFAULT_CHUNK_BYTES + 4096);
const { result, bytes: sealed } = await sealMediaBytes(bytes);
for (const bad of [
{ chunk: 0, received: 0 },
{ chunk: MAX_PIECE_BYTES * 4, received: 0 },
{ chunk: DEFAULT_CHUNK_BYTES, received: -1 },
{ chunk: DEFAULT_CHUNK_BYTES, received: 0, window: 0 },
{ chunk: DEFAULT_CHUNK_BYTES, received: 0, landed: ['x'] },
]) {
let calls = 0;
const relay = (async () => {
calls++;
return Response.json({ id: 'x', size: result.sealedSize, ...bad }, { status: 201 });
}) as unknown as typeof fetch;
await expect(new MediaClient('http://relay', OwnerKey.generate(), { fetch: relay }).putSealed(result, sealed)).rejects.toThrow(/unusable/);
expect(calls).toBe(1);
}
});
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);
}
});
});