How Large Uploads Work
easy 38 minA large file goes up in small numbered pieces.
A server, a client and a network that loses things
Read it, run it, change a line and run it again.
Loading editor…
Runs here. To stay small, one 'MB' in this program is 1,000 bytes. The places and numbers are the same as in the text. All losses come from a fixed list or a fixed seed.
The same in JavaScript
// Browser client. One piece in memory at a time, the server's number wins.const PIECE = 4_000_000;const hex = (buffer) => [...new Uint8Array(buffer)].map((b) => b.toString(16).padStart(2, "0")).join("");const sha256 = async (bytes) => hex(await crypto.subtle.digest("SHA-256", bytes));const sleep = (ms) => new Promise((done) => setTimeout(done, ms));async function fingerprint(file) { const head = await file.slice(0, 1_000_000).arrayBuffer(); return [file.name, file.size, file.lastModified, await sha256(head)].join("|");}/** Repeats the same request after silence or a busy server. Never guesses what happened. */async function again(url, options, tries = 12) { for (let n = 0; n < tries; n++) { try { const reply = await fetch(url, { ...options, signal: AbortSignal.timeout(60_000) }); if (![408, 429, 500, 502, 503, 504].includes(reply.status)) return reply; } catch { // No reply: the request or the reply was lost. The same request follows. } await sleep(Math.random() * Math.min(30_000, 1_000 * 2 ** n)); } throw new Error("paused"); // keep the session, let the user continue later}async function upload(file, onSaved) { const key = "upload:" + (await fingerprint(file)); let id = localStorage.getItem(key); let offset = 0; if (id) { const reply = await again("/uploads/" + id, { method: "GET" }); if (reply.ok) offset = (await reply.json()).offset; else if (reply.status === 404 || reply.status === 410) id = null; // gone: start again else throw new Error("status " + reply.status); } if (!id) { const reply = await again("/uploads", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: file.name, size: file.size }), }); if (!reply.ok) throw new Error("status " + reply.status); ({ id, offset } = await reply.json()); localStorage.setItem(key, id); // saved before the first piece leaves } let damaged = 0; while (offset < file.size) { const bytes = await file.slice(offset, Math.min(offset + PIECE, file.size)).arrayBuffer(); const reply = await again("/uploads/" + id, { method: "PATCH", headers: { "Upload-Offset": String(offset), "X-Piece-SHA256": await sha256(bytes) }, body: bytes, }); if (![200, 400, 409].includes(reply.status)) throw new Error("status " + reply.status); damaged = reply.status === 400 ? damaged + 1 : 0; if (damaged > 5) throw new Error("this piece keeps arriving damaged"); const answer = await reply.json(); if (answer.offset === undefined) throw new Error("the request was refused"); offset = answer.offset; // also after 409: this is where we continue onSaved(offset / file.size); } // Hash of hashes, read from the file the user chose now. const all = []; for (let at = 0; at < file.size; at += PIECE) { all.push(await sha256(await file.slice(at, at + PIECE).arrayBuffer())); } const whole = await sha256(new TextEncoder().encode(all.join(""))); const reply = await again("/uploads/" + id + "/finish", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sha256: whole }), }); if (!reply.ok) throw new Error("not finished: " + reply.status); localStorage.removeItem(key); return (await reply.json()).file;}The same in TypeScript
// Server side, as a function from Request to Response. Fits any runtime with the fetch types.import { createHash, randomUUID } from "node:crypto";interface Session { owner: string; size: number; offset: number; hashes: string[]; keys: string[]; // where each piece is stored, in order file: string | null;}/** A shared database. advance() changes the row only if the offset is still `from`. */export interface Sessions { create(s: Session): Promise<string>; get(id: string): Promise<Session | null>; advance(id: string, from: number, to: number, hash: string, key: string): Promise<boolean>; publish(id: string): Promise<string>; // joins by reference; a second call returns the same file}/** Object storage. A put has returned only when the bytes are safe. */export interface Pieces { put(key: string, data: Uint8Array): Promise<void>; remove(key: string): Promise<void>;}const MAX_PIECE = 4_000_000;const MAX_FILE = 5_000_000_000;const sha = (data: Uint8Array | string) => createHash("sha256").update(data).digest("hex");const json = (status: number, body: object) => Response.json(body, { status });/** Reads at most `limit` bytes. Counts what really arrives, whatever the headers say. */async function read(body: ReadableStream<Uint8Array> | null, limit: number): Promise<Uint8Array | null> { const parts: Uint8Array[] = []; let n = 0; const reader = body?.getReader(); while (reader) { const { done, value } = await reader.read(); if (done) break; n += value.length; if (n > limit) { await reader.cancel(); return null; } parts.push(value); } return Buffer.concat(parts);}export function uploads(sessions: Sessions, pieces: Pieces, userOf: (r: Request) => string) { return async (request: Request): Promise<Response> => { const [, , id, action] = new URL(request.url).pathname.split("/"); const user = userOf(request); if (request.method === "POST" && !id) { const { size } = (await request.json()) as { size: number }; if (!Number.isSafeInteger(size) || size < 1 || size > MAX_FILE) return json(413, { error: "size" }); const made = await sessions.create({ owner: user, size, offset: 0, hashes: [], keys: [], file: null }); return json(201, { id: made, offset: 0 }); } const s = await sessions.get(id ?? ""); if (!s || s.owner !== user) return json(404, { error: "no such upload" }); if (request.method === "GET") return json(200, { offset: s.offset }); if (request.method === "PATCH") { const offset = Number(request.headers.get("upload-offset") ?? NaN); if (!Number.isSafeInteger(offset) || offset < 0) return json(400, { error: "offset" }); const data = await read(request.body, MAX_PIECE); if (!data || offset + data.length > s.size) return json(413, { error: "too long" }); const hash = sha(data); if (!data.length || hash !== request.headers.get("x-piece-sha256")) return json(400, { offset: s.offset }); if (offset === s.offset) { const key = id + "/" + offset + "/" + randomUUID(); // a name of its own for every copy await pieces.put(key, data); // 1. bytes if (await sessions.advance(id, offset, offset + data.length, hash, key)) { // 2. number return json(200, { offset: offset + data.length }); // 3. reply } await pieces.remove(key); // another request was faster } const now = (await sessions.get(id))?.offset ?? s.offset; return json(offset + data.length <= now ? 200 : 409, { offset: now }); } if (request.method === "POST" && action === "finish") { if (s.file) return json(200, { file: s.file }); if (s.offset !== s.size) return json(409, { offset: s.offset }); const { sha256 } = (await request.json()) as { sha256: string }; if (sha(s.hashes.join("")) !== sha256) return json(422, { error: "hash differs" }); return json(200, { file: await sessions.publish(id) }); } return json(405, { error: "method" }); };}