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>
This commit is contained in:
2026-10-19 00:31:06 +02:00
parent 0a706cdb47
commit 7d45be8712
7 changed files with 133 additions and 9 deletions

View File

@@ -14,7 +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';
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)}`;
@@ -162,7 +162,13 @@ export class MediaClient {
},
});
if (res.status !== 200 && res.status !== 201) return fail(res, 'start');
return (await res.json()) as Status;
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);
@@ -172,7 +178,7 @@ export class MediaClient {
return;
}
const { chunk } = opened;
const window = Math.max(1, opened.window ?? 1);
const window = Math.min(MAX_CLIENT_WINDOW, Math.max(1, opened.window ?? 1));
let acked = 0;
let complete = false;
const todo: number[] = [];

View File

@@ -24,7 +24,7 @@ export { MediaClient, openGrant, openAlbum, readAlbum, mediaUrl } from './client
export { ALBUM_KIND, ALBUM_MIME, MAX_ALBUM_ITEMS, encodeAlbum, parseAlbum, isAlbum, albumMeta, isMediaGrant } from './album.js';
export type { Album } from './album.js';
export type { PutOptions } from './client.js';
export { MAX_PIECE_BYTES, DEFAULT_CHUNK_BYTES, MAX_UPLOAD_BYTES, OFFSET_HEADER, UPLOAD_WINDOW, chunkFor } from './upload.js';
export { MAX_PIECE_BYTES, DEFAULT_CHUNK_BYTES, MAX_UPLOAD_BYTES, MAX_CLIENT_WINDOW, OFFSET_HEADER, UPLOAD_WINDOW, chunkFor, statusProblem } from './upload.js';
export { LivePublisher, LiveSubscriber, epochKeys, chainStep, MAX_SKIP, MAX_SKIPPED_KEYS } from './live/channel.js';
export type { FrameOptions, PublisherOptions, GrantOptions, ReceivedFrame } from './live/channel.js';
export { encodeContent, decodeContent, decodeFrame, FLAG_STICKY, FLAG_KEYFRAME, FLAG_END } from './live/frame.js';

View File

@@ -40,6 +40,23 @@ export const OFFSET_HEADER = 'x-shade-offset';
/** Pieces past `received` a relay takes at once — what an upload holds in its memory, at most. */
export const UPLOAD_WINDOW = 4;
/** Most pieces a client keeps in flight, whatever window a relay offers. */
export const MAX_CLIENT_WINDOW = 16;
/**
* Why a relay's upload status cannot be used, or null. A client checks it
* before trusting it: a zero chunk would never get through the file, a huge
* one would hold it all in memory, a huge window opens a request per piece.
*/
export function statusProblem(st: { chunk?: unknown; window?: unknown; received?: unknown; landed?: unknown }, size: number): string | null {
const int = (v: unknown) => typeof v === 'number' && Number.isSafeInteger(v);
if (!int(st.chunk) || (st.chunk as number) < MiB || (st.chunk as number) > MAX_PIECE_BYTES) return `chunk ${String(st.chunk)} out of range`;
if (st.window !== undefined && (!int(st.window) || (st.window as number) < 1)) return `window ${String(st.window)} out of range`;
if (!int(st.received) || (st.received as number) < 0 || (st.received as number) > size) return `received ${String(st.received)} out of range`;
if (st.landed !== undefined && (!Array.isArray(st.landed) || !st.landed.every((n) => int(n) && n >= 0))) return 'landed is not a list of piece numbers';
return null;
}
/** The piece size for a file of `size` bytes: the default, or larger so it fits in 10 000 pieces. */
export function chunkFor(size: number): number {
const need = Math.ceil(size / MAX_PIECES / MiB) * MiB;

View File

@@ -202,6 +202,26 @@ describe('pieces', () => {
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();