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:
@@ -112,6 +112,11 @@ const err = (s: string) => process.stderr.write(`${s}\n`);
|
||||
|
||||
// ─── media ───────────────────────────────────────────────────
|
||||
|
||||
function reportSweep(r: { objects: number; uploads: number } | Error): void {
|
||||
if (r instanceof Error) err(`! media sweep: ${r.message}`);
|
||||
else if (r.objects + r.uploads > 0) err(`media sweep: ${r.uploads} abandoned upload(s), ${r.objects} orphaned object(s) reclaimed`);
|
||||
}
|
||||
|
||||
async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise<number> {
|
||||
const { websocket } = await import('hono/bun');
|
||||
const { createMediaService, parseOwners, mediaMaxRequestBody } = await import('./server.js');
|
||||
@@ -140,15 +145,13 @@ async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise<number> {
|
||||
store: backend.store,
|
||||
pins: backend.pins,
|
||||
dev: flags.dev === true,
|
||||
onSweep: reportSweep,
|
||||
...(self !== undefined ? { live: { mesh: { self, locator: backend.locator } } } : {}),
|
||||
});
|
||||
where = backend.describe;
|
||||
closeBackend = () => backend.close();
|
||||
const sweep = () => backend.sweep().catch((e: unknown) => err(`! media sweep: ${(e as Error).message}`));
|
||||
setTimeout(sweep, 60_000).unref();
|
||||
setInterval(sweep, 6 * 3600_000).unref();
|
||||
} else {
|
||||
svc = createMediaService({ dir, owners, dev: flags.dev === true });
|
||||
svc = createMediaService({ dir, owners, dev: flags.dev === true, onSweep: reportSweep });
|
||||
}
|
||||
svc.app.get('/health', (c) => c.json({ ok: true, live: svc.relay.stats() }));
|
||||
const server = Bun.serve({
|
||||
@@ -157,7 +160,7 @@ async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise<number> {
|
||||
fetch: (req, srv) => svc.app.fetch(req, { server: srv }),
|
||||
websocket,
|
||||
idleTimeout: 0,
|
||||
// Every route here bounds its own body; the 128 MiB default would refuse films.
|
||||
// One upload piece at most: films go up in pieces, so no request holds one in memory.
|
||||
maxRequestBodySize: mediaMaxRequestBody(),
|
||||
});
|
||||
err(`shade media: serving on http://localhost:${server.port} (data in ${where})`);
|
||||
@@ -255,6 +258,27 @@ async function putSubtitles(ctx: PutCtx, video: string, flags: Flags): Promise<S
|
||||
return tracks;
|
||||
}
|
||||
|
||||
/**
|
||||
* How far a film's upload got, on stderr: a line redrawn in place on a
|
||||
* terminal, every tenth otherwise (a log). Small files say nothing.
|
||||
*/
|
||||
function uploadProgress(name: string, total: number): ((sent: number) => void) | undefined {
|
||||
if (total <= 16 * 1024 * 1024) return undefined;
|
||||
const gib = (n: number) => (n / 1024 ** 3).toFixed(2);
|
||||
const tty = process.stderr.isTTY === true;
|
||||
let lastTenth = -1;
|
||||
return (sent) => {
|
||||
const pct = Math.floor((sent / total) * 100);
|
||||
const line = ` uploading ${name}: ${pct}% (${gib(sent)} of ${gib(total)} GiB)`;
|
||||
if (tty) {
|
||||
process.stderr.write(`\r${line}\x1b[K${sent === total ? '\n' : ''}`);
|
||||
} else if (Math.floor(pct / 10) > lastTenth) {
|
||||
lastTenth = Math.floor(pct / 10);
|
||||
err(line);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function putOpts(flags: Flags): { readToken?: null } {
|
||||
return flags.public === true ? { readToken: null } : {};
|
||||
}
|
||||
@@ -294,7 +318,12 @@ async function putFile(ctx: PutCtx, file: string, flags: Flags, as: { name?: str
|
||||
try {
|
||||
err(`sealing ${meta.name ?? basename(file)} (${(size / 1048576).toFixed(1)} MiB)…`);
|
||||
const result = await sealFile(source, tmp, { meta });
|
||||
const grant = await ctx.client.putSealed(result, Bun.file(tmp), { meta, ...putOpts(flags) });
|
||||
const progress = uploadProgress(meta.name ?? basename(file), result.sealedSize);
|
||||
const grant = await ctx.client.putSealed(result, Bun.file(tmp), {
|
||||
meta,
|
||||
...putOpts(flags),
|
||||
...(progress !== undefined ? { onProgress: progress } : {}),
|
||||
});
|
||||
await ctx.library.add(ctx.server, grant, result.sealedSize);
|
||||
return grant;
|
||||
} finally {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -24,6 +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 { 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';
|
||||
|
||||
@@ -22,6 +22,9 @@ export const MAX_SKEW_MS = 10 * 60 * 1000;
|
||||
|
||||
export type OwnerOp =
|
||||
| { op: 'put'; id: string; size: number; readTokenHash: string }
|
||||
| { op: 'upload'; id: string; size: number; readTokenHash: string }
|
||||
| { op: 'piece'; id: string; offset: number; length: number }
|
||||
| { op: 'abort'; id: string }
|
||||
| { op: 'delete'; id: string }
|
||||
| { op: 'list' }
|
||||
| { op: 'publish'; hello: string };
|
||||
@@ -30,6 +33,12 @@ export function ownerMessage(o: OwnerOp, at: number): Uint8Array {
|
||||
switch (o.op) {
|
||||
case 'put':
|
||||
return enc.encode(`shade.media-put/v1|${o.id}|${o.size}|${o.readTokenHash}|${at}`);
|
||||
case 'upload':
|
||||
return enc.encode(`shade.media-upload/v1|${o.id}|${o.size}|${o.readTokenHash}|${at}`);
|
||||
case 'piece':
|
||||
return enc.encode(`shade.media-piece/v1|${o.id}|${o.offset}|${o.length}|${at}`);
|
||||
case 'abort':
|
||||
return enc.encode(`shade.media-abort/v1|${o.id}|${at}`);
|
||||
case 'delete':
|
||||
return enc.encode(`shade.media-delete/v1|${o.id}|${at}`);
|
||||
case 'list':
|
||||
|
||||
@@ -1,14 +1,31 @@
|
||||
export { createMediaRoutes, parseRange } from './server/media-routes.js';
|
||||
export type { MediaRoutesOptions } from './server/media-routes.js';
|
||||
export { FileMediaStore, MemoryMediaStore, MediaExistsError } from './server/file-store.js';
|
||||
export type { MediaStore, MediaRecord, MediaUpload } from './server/file-store.js';
|
||||
export {
|
||||
FileMediaStore,
|
||||
MemoryMediaStore,
|
||||
MediaExistsError,
|
||||
UploadOffsetError,
|
||||
BadPieceError,
|
||||
UploadConflictError,
|
||||
NoUploadError,
|
||||
checkPiece,
|
||||
} from './server/file-store.js';
|
||||
export type {
|
||||
MediaStore,
|
||||
MediaRecord,
|
||||
MediaUpload,
|
||||
PendingUpload,
|
||||
PendingStart,
|
||||
ReadBack,
|
||||
FileMediaStoreOptions,
|
||||
} from './server/file-store.js';
|
||||
export { ObjectMediaStore, MemoryMediaIndex } from './server/object-store.js';
|
||||
export { S3Bucket, S3Error, signV4 } from './server/s3.js';
|
||||
export type { S3BucketOptions, S3Credentials, S3Object } from './server/s3.js';
|
||||
export type { MediaIndex, IndexedMedia, ObjectMediaStoreOptions } from './server/object-store.js';
|
||||
export type { MediaIndex, IndexedMedia, PendingObject, ObjectMediaStoreOptions } from './server/object-store.js';
|
||||
export { createLiveRelay, FileLivePinStore, MemoryLivePinStore, LivePinTakenError, MemoryLivePublisherLocator } from './server/live-relay.js';
|
||||
export type { LiveRelay, LiveRelayOptions, LivePin, LivePinStore, LivePublisherLocator } from './server/live-relay.js';
|
||||
export { createWatchRoutes } from './server/watch-routes.js';
|
||||
export type { WatchRoutesOptions } from './server/watch-routes.js';
|
||||
export { createMediaService, parseOwners, mediaMaxRequestBody, MEDIA_BODY_ROUTE } from './server/service.js';
|
||||
export { createMediaService, parseOwners, mediaMaxRequestBody } from './server/service.js';
|
||||
export type { MediaService, MediaServiceOptions } from './server/service.js';
|
||||
|
||||
@@ -7,12 +7,19 @@
|
||||
* JSON sidecar (owner, size, read-token hash); the in-memory index is
|
||||
* rebuilt from the sidecars on open, so the directory is the only truth and
|
||||
* a restart loses nothing.
|
||||
*
|
||||
* A resumable upload is `uploads/<id>.part` (pieces written at their
|
||||
* offsets), `uploads/<id>.json` (its terms) and `uploads/<id>.log` (the
|
||||
* index of each piece, appended once the piece is on disk). The log is what
|
||||
* landed: a crash mid-piece leaves bytes the log does not name, and that
|
||||
* piece is sent again. All of it survives a restart.
|
||||
*/
|
||||
|
||||
import { mkdir, link, readdir, readFile, rename, rm, stat, unlink, writeFile, open } from 'node:fs/promises';
|
||||
import type { FileHandle } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { randomBytes, toHex } from '../bytes.js';
|
||||
import { pieceProblem, receivedOf } from '../upload.js';
|
||||
|
||||
export interface MediaRecord {
|
||||
/** Lowercase hex of the 16-byte mediaId. */
|
||||
@@ -40,25 +47,110 @@ export class MediaExistsError extends Error {
|
||||
override readonly name = 'MediaExistsError';
|
||||
}
|
||||
|
||||
/** A resumable upload (see `upload.ts`): what was promised and how much has arrived. */
|
||||
export interface PendingUpload {
|
||||
id: string;
|
||||
owner: string;
|
||||
size: number;
|
||||
readTokenHash: string | null;
|
||||
/** Bytes per piece; the last may be shorter. */
|
||||
chunk: number;
|
||||
/** How much of the file, from the start, has landed. */
|
||||
received: number;
|
||||
/** Pieces (by index) past `received` that landed already. */
|
||||
landed: number[];
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export type PendingStart = Omit<PendingUpload, 'received' | 'landed'>;
|
||||
|
||||
/** The piece is too far ahead of the upload; `received` is where it stands. */
|
||||
export class UploadOffsetError extends Error {
|
||||
override readonly name = 'UploadOffsetError';
|
||||
constructor(readonly received: number) {
|
||||
super(`upload is at offset ${received}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** A piece of the wrong size, or past the end. */
|
||||
export class BadPieceError extends Error {
|
||||
override readonly name = 'BadPieceError';
|
||||
}
|
||||
|
||||
/** An upload of this id is under way on other terms (owner, size, read token). */
|
||||
export class UploadConflictError extends Error {
|
||||
override readonly name = 'UploadConflictError';
|
||||
}
|
||||
|
||||
export class NoUploadError extends Error {
|
||||
override readonly name = 'NoUploadError';
|
||||
}
|
||||
|
||||
/** Reads bytes of a fully received upload — for the footer check before it is stored. */
|
||||
export type ReadBack = (offset: number, length: number) => Promise<Uint8Array>;
|
||||
|
||||
export interface MediaStore {
|
||||
get(id: string): Promise<MediaRecord | null>;
|
||||
/** Total bytes stored for an owner — for quotas. */
|
||||
/** Total bytes stored for an owner, counting uploads under way — for quotas. */
|
||||
usage(owner: string): Promise<number>;
|
||||
/** Likewise across owners. */
|
||||
totalBytes(): Promise<number>;
|
||||
/** A whole file in one request. */
|
||||
begin(id: string): Promise<MediaUpload>;
|
||||
/** Start a resumable upload, or return the one under way on the same terms. Throws `MediaExistsError`, `UploadConflictError`. */
|
||||
openUpload(start: PendingStart): Promise<PendingUpload>;
|
||||
getUpload(id: string): Promise<PendingUpload | null>;
|
||||
/**
|
||||
* Store the piece at `offset` (a piece already landed is a no-op);
|
||||
* returns the new `received`. Pieces of one upload may arrive at once.
|
||||
* Throws `NoUploadError`, `UploadOffsetError`, `BadPieceError`.
|
||||
*/
|
||||
appendUpload(id: string, offset: number, bytes: Uint8Array): Promise<number>;
|
||||
/**
|
||||
* Every byte is in: `verify` them, then store the file. A failed check
|
||||
* (it throws) discards the upload. Throws `MediaExistsError` if the id was
|
||||
* taken meanwhile.
|
||||
*/
|
||||
completeUpload(id: string, verify: (read: ReadBack) => Promise<void>): Promise<MediaRecord>;
|
||||
abortUpload(id: string): Promise<boolean>;
|
||||
/** Body for `[start, end)`, streamed — a film is never loaded into memory. */
|
||||
body(id: string, start: number, end: number): Promise<ReadableStream<Uint8Array>>;
|
||||
delete(id: string): Promise<boolean>;
|
||||
list(owner: string): Promise<MediaRecord[]>;
|
||||
/** Reclaim what abandoned uploads left behind, past the store's grace period. Safe to run often. */
|
||||
sweep(): Promise<{ objects: number; uploads: number }>;
|
||||
}
|
||||
|
||||
/** The check every store runs before taking a piece. */
|
||||
export function checkPiece(up: { size: number; chunk: number; received: number }, offset: number, length: number): void {
|
||||
const problem = pieceProblem(up, offset, length);
|
||||
if (problem === null) return;
|
||||
if (problem.ahead) throw new UploadOffsetError(up.received);
|
||||
throw new BadPieceError(problem.message);
|
||||
}
|
||||
|
||||
export interface FileMediaStoreOptions {
|
||||
/** An upload with no new piece for this long is abandoned. Default 24 h. */
|
||||
uploadGraceMs?: number;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
const ID_RE = /^[0-9a-f]{32}$/;
|
||||
|
||||
export class FileMediaStore implements MediaStore {
|
||||
private readonly index = new Map<string, MediaRecord>();
|
||||
private readonly pending = new Map<string, { terms: PendingStart; landed: Set<number> }>();
|
||||
private readonly locks = new Map<string, Promise<unknown>>();
|
||||
private readonly graceMs: number;
|
||||
private readonly now: () => number;
|
||||
private ready: Promise<void>;
|
||||
|
||||
constructor(private readonly dir: string) {
|
||||
constructor(
|
||||
private readonly dir: string,
|
||||
opts: FileMediaStoreOptions = {},
|
||||
) {
|
||||
this.graceMs = opts.uploadGraceMs ?? 24 * 3600 * 1000;
|
||||
this.now = opts.now ?? Date.now;
|
||||
this.ready = this.load();
|
||||
// A directory it cannot use fails every call that awaits `ready`, with
|
||||
// the reason — not the process, as an unhandled rejection at start.
|
||||
@@ -73,9 +165,60 @@ export class FileMediaStore implements MediaStore {
|
||||
return join(this.dir, 'objects', id.slice(0, 2), `${id}.json`);
|
||||
}
|
||||
|
||||
private partPath(id: string): string {
|
||||
return join(this.dir, 'uploads', `${id}.part`);
|
||||
}
|
||||
|
||||
private termsPath(id: string): string {
|
||||
return join(this.dir, 'uploads', `${id}.json`);
|
||||
}
|
||||
|
||||
private logPath(id: string): string {
|
||||
return join(this.dir, 'uploads', `${id}.log`);
|
||||
}
|
||||
|
||||
/** Bookkeeping of one upload (its log, completion) one step at a time; different uploads run side by side. */
|
||||
private locked<T>(id: string, fn: () => Promise<T>): Promise<T> {
|
||||
const run = (this.locks.get(id) ?? Promise.resolve()).then(fn, fn);
|
||||
const settled = run.then(
|
||||
() => {},
|
||||
() => {},
|
||||
);
|
||||
this.locks.set(id, settled);
|
||||
void settled.then(() => {
|
||||
if (this.locks.get(id) === settled) this.locks.delete(id);
|
||||
});
|
||||
return run;
|
||||
}
|
||||
|
||||
private view(p: { terms: PendingStart; landed: Set<number> }): PendingUpload {
|
||||
const received = receivedOf(p.terms.size, p.terms.chunk, (n) => p.landed.has(n));
|
||||
const past = received / p.terms.chunk;
|
||||
return { ...p.terms, received, landed: [...p.landed].filter((n) => n > past).sort((x, y) => x - y) };
|
||||
}
|
||||
|
||||
private async load(): Promise<void> {
|
||||
await mkdir(join(this.dir, 'objects'), { recursive: true });
|
||||
await mkdir(join(this.dir, 'tmp'), { recursive: true });
|
||||
await mkdir(join(this.dir, 'uploads'), { recursive: true });
|
||||
for (const f of await readdir(join(this.dir, 'uploads'))) {
|
||||
if (!f.endsWith('.json')) continue;
|
||||
const id = f.slice(0, -5);
|
||||
if (!ID_RE.test(id)) continue;
|
||||
try {
|
||||
const terms = JSON.parse(await readFile(this.termsPath(id), 'utf8')) as PendingStart;
|
||||
await stat(this.partPath(id));
|
||||
const log = new Uint8Array(await readFile(this.logPath(id)));
|
||||
const landed = new Set<number>();
|
||||
const v = new DataView(log.buffer, log.byteOffset, log.byteLength);
|
||||
// A torn last entry (a crash while appending) is not a landed piece.
|
||||
for (let o = 0; o + 4 <= log.length; o += 4) landed.add(v.getUint32(o));
|
||||
this.pending.set(id, { terms, landed });
|
||||
} catch {
|
||||
// Terms without a part file or log (a crash while starting) is nothing to resume.
|
||||
await rm(this.termsPath(id), { force: true });
|
||||
}
|
||||
}
|
||||
// Uploads that never committed (a crash, a dropped connection) are garbage.
|
||||
for (const f of await readdir(join(this.dir, 'tmp'))) {
|
||||
await rm(join(this.dir, 'tmp', f), { force: true });
|
||||
@@ -108,6 +251,7 @@ export class FileMediaStore implements MediaStore {
|
||||
await this.ready;
|
||||
let n = 0;
|
||||
for (const r of this.index.values()) if (r.owner === owner) n += r.size;
|
||||
for (const p of this.pending.values()) if (p.terms.owner === owner) n += p.terms.size;
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -115,6 +259,7 @@ export class FileMediaStore implements MediaStore {
|
||||
await this.ready;
|
||||
let n = 0;
|
||||
for (const r of this.index.values()) n += r.size;
|
||||
for (const p of this.pending.values()) n += p.terms.size;
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -182,6 +327,165 @@ export class FileMediaStore implements MediaStore {
|
||||
};
|
||||
}
|
||||
|
||||
async openUpload(start: PendingStart): Promise<PendingUpload> {
|
||||
await this.ready;
|
||||
if (!ID_RE.test(start.id)) throw new Error('bad media id');
|
||||
return this.locked(start.id, async () => {
|
||||
if (this.index.has(start.id)) throw new MediaExistsError(start.id);
|
||||
const had = this.pending.get(start.id);
|
||||
if (had !== undefined) {
|
||||
const t = had.terms;
|
||||
if (t.owner !== start.owner || t.size !== start.size || t.readTokenHash !== start.readTokenHash) {
|
||||
throw new UploadConflictError(start.id);
|
||||
}
|
||||
return this.view(had);
|
||||
}
|
||||
await writeFile(this.partPath(start.id), new Uint8Array(0), { flag: 'wx' });
|
||||
await writeFile(this.logPath(start.id), new Uint8Array(0));
|
||||
// Terms last, atomically: they are what makes the upload exist on load.
|
||||
const tmp = `${this.termsPath(start.id)}.${toHex(randomBytes(4))}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(start));
|
||||
await rename(tmp, this.termsPath(start.id));
|
||||
const p = { terms: start, landed: new Set<number>() };
|
||||
this.pending.set(start.id, p);
|
||||
return this.view(p);
|
||||
});
|
||||
}
|
||||
|
||||
async getUpload(id: string): Promise<PendingUpload | null> {
|
||||
await this.ready;
|
||||
const p = this.pending.get(id);
|
||||
return p === undefined ? null : this.view(p);
|
||||
}
|
||||
|
||||
async appendUpload(id: string, offset: number, bytes: Uint8Array): Promise<number> {
|
||||
await this.ready;
|
||||
const p = this.pending.get(id);
|
||||
if (p === undefined) throw new NoUploadError(id);
|
||||
checkPiece(this.view(p), offset, bytes.length);
|
||||
const n = offset / p.terms.chunk;
|
||||
if (p.landed.has(n)) return this.view(p).received;
|
||||
// Pieces write side by side, each at its own offset; only the log is in turn.
|
||||
try {
|
||||
const fh = await open(this.partPath(id), 'r+');
|
||||
try {
|
||||
let off = 0;
|
||||
while (off < bytes.length) {
|
||||
const { bytesWritten } = await fh.write(bytes, off, bytes.length - off, offset + off);
|
||||
off += bytesWritten;
|
||||
}
|
||||
// On disk before the log says so: the client will not send it again.
|
||||
await fh.sync();
|
||||
} finally {
|
||||
await fh.close();
|
||||
}
|
||||
} catch (e) {
|
||||
if (this.pending.get(id) !== p) throw new NoUploadError(id); // aborted meanwhile
|
||||
throw e;
|
||||
}
|
||||
await this.locked(id, async () => {
|
||||
if (this.pending.get(id) !== p) throw new NoUploadError(id);
|
||||
if (p.landed.has(n)) return;
|
||||
const entry = new Uint8Array(4);
|
||||
new DataView(entry.buffer).setUint32(0, n);
|
||||
const log = await open(this.logPath(id), 'a');
|
||||
try {
|
||||
await log.write(entry);
|
||||
await log.sync();
|
||||
} finally {
|
||||
await log.close();
|
||||
}
|
||||
p.landed.add(n);
|
||||
});
|
||||
return this.view(p).received;
|
||||
}
|
||||
|
||||
async completeUpload(id: string, verify: (read: ReadBack) => Promise<void>): Promise<MediaRecord> {
|
||||
await this.ready;
|
||||
return this.locked(id, async () => {
|
||||
const pending = this.pending.get(id);
|
||||
if (pending === undefined) throw new NoUploadError(id);
|
||||
const { received } = this.view(pending);
|
||||
const p = pending.terms;
|
||||
if (received !== p.size) throw new UploadOffsetError(received);
|
||||
const part = this.partPath(id);
|
||||
const fh = await open(part, 'r');
|
||||
try {
|
||||
await verify(async (offset, length) => {
|
||||
const out = new Uint8Array(length);
|
||||
const { bytesRead } = await fh.read(out, 0, length, offset);
|
||||
return out.subarray(0, bytesRead);
|
||||
});
|
||||
} catch (e) {
|
||||
await fh.close();
|
||||
await this.dropUpload(id);
|
||||
throw e;
|
||||
}
|
||||
await fh.close();
|
||||
const finalPath = this.objectPath(id);
|
||||
await mkdir(join(finalPath, '..'), { recursive: true });
|
||||
try {
|
||||
await link(part, finalPath);
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code === 'EEXIST') {
|
||||
await this.dropUpload(id);
|
||||
throw new MediaExistsError(id);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
const record: MediaRecord = {
|
||||
id,
|
||||
owner: p.owner,
|
||||
size: p.size,
|
||||
readTokenHash: p.readTokenHash,
|
||||
createdAt: this.now(),
|
||||
};
|
||||
const sidecar = this.sidecarPath(id);
|
||||
const sidecarTmp = `${sidecar}.${toHex(randomBytes(4))}.tmp`;
|
||||
await writeFile(sidecarTmp, JSON.stringify(record));
|
||||
await rename(sidecarTmp, sidecar);
|
||||
this.index.set(id, record);
|
||||
await this.dropUpload(id);
|
||||
return record;
|
||||
});
|
||||
}
|
||||
|
||||
async abortUpload(id: string): Promise<boolean> {
|
||||
await this.ready;
|
||||
return this.locked(id, async () => {
|
||||
if (!this.pending.has(id)) return false;
|
||||
await this.dropUpload(id);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private async dropUpload(id: string): Promise<void> {
|
||||
this.pending.delete(id);
|
||||
// Terms first: a part file without terms is not resumed on load.
|
||||
await rm(this.termsPath(id), { force: true });
|
||||
await rm(this.logPath(id), { force: true });
|
||||
await rm(this.partPath(id), { force: true });
|
||||
}
|
||||
|
||||
/** Drop uploads with no new piece within the grace period. */
|
||||
async sweep(): Promise<{ objects: number; uploads: number }> {
|
||||
await this.ready;
|
||||
const cutoff = this.now() - this.graceMs;
|
||||
let uploads = 0;
|
||||
for (const id of [...this.pending.keys()]) {
|
||||
const dropped = await this.locked(id, async () => {
|
||||
if (!this.pending.has(id)) return false;
|
||||
// The log changes with every piece that lands, and is created with the upload.
|
||||
const s = await stat(this.logPath(id)).catch(() => null);
|
||||
if (s !== null && s.mtimeMs >= cutoff) return false;
|
||||
await this.dropUpload(id);
|
||||
return true;
|
||||
});
|
||||
if (dropped) uploads++;
|
||||
}
|
||||
return { objects: 0, uploads };
|
||||
}
|
||||
|
||||
async body(id: string, start: number, end: number): Promise<ReadableStream<Uint8Array>> {
|
||||
await this.ready;
|
||||
// Read the range ourselves rather than handing `Bun.file().slice()` to a
|
||||
@@ -228,6 +532,13 @@ export class FileMediaStore implements MediaStore {
|
||||
/** For tests only — loses everything on restart, which a media library must not. */
|
||||
export class MemoryMediaStore implements MediaStore {
|
||||
private readonly objects = new Map<string, { rec: MediaRecord; bytes: Uint8Array }>();
|
||||
private readonly uploads = new Map<string, { start: PendingStart; pieces: Map<number, Uint8Array> }>();
|
||||
private viewOf(u: { start: PendingStart; pieces: Map<number, Uint8Array> }): PendingUpload {
|
||||
const received = receivedOf(u.start.size, u.start.chunk, (n) => u.pieces.has(n));
|
||||
const past = received / u.start.chunk;
|
||||
return { ...u.start, received, landed: [...u.pieces.keys()].filter((n) => n > past).sort((x, y) => x - y) };
|
||||
}
|
||||
constructor(private readonly now: () => number = Date.now) {}
|
||||
|
||||
async get(id: string): Promise<MediaRecord | null> {
|
||||
return this.objects.get(id)?.rec ?? null;
|
||||
@@ -235,11 +546,13 @@ export class MemoryMediaStore implements MediaStore {
|
||||
async usage(owner: string): Promise<number> {
|
||||
let n = 0;
|
||||
for (const o of this.objects.values()) if (o.rec.owner === owner) n += o.rec.size;
|
||||
for (const u of this.uploads.values()) if (u.start.owner === owner) n += u.start.size;
|
||||
return n;
|
||||
}
|
||||
async totalBytes(): Promise<number> {
|
||||
let n = 0;
|
||||
for (const o of this.objects.values()) n += o.rec.size;
|
||||
for (const u of this.uploads.values()) n += u.start.size;
|
||||
return n;
|
||||
}
|
||||
async list(owner: string): Promise<MediaRecord[]> {
|
||||
@@ -276,6 +589,53 @@ export class MemoryMediaStore implements MediaStore {
|
||||
async abort() {},
|
||||
};
|
||||
}
|
||||
async openUpload(start: PendingStart): Promise<PendingUpload> {
|
||||
if (this.objects.has(start.id)) throw new MediaExistsError(start.id);
|
||||
const had = this.uploads.get(start.id);
|
||||
if (had !== undefined) {
|
||||
const t = had.start;
|
||||
if (t.owner !== start.owner || t.size !== start.size || t.readTokenHash !== start.readTokenHash) {
|
||||
throw new UploadConflictError(start.id);
|
||||
}
|
||||
return this.viewOf(had);
|
||||
}
|
||||
const u = { start, pieces: new Map<number, Uint8Array>() };
|
||||
this.uploads.set(start.id, u);
|
||||
return this.viewOf(u);
|
||||
}
|
||||
async getUpload(id: string): Promise<PendingUpload | null> {
|
||||
const u = this.uploads.get(id);
|
||||
return u === undefined ? null : this.viewOf(u);
|
||||
}
|
||||
async appendUpload(id: string, offset: number, bytes: Uint8Array): Promise<number> {
|
||||
const u = this.uploads.get(id);
|
||||
if (u === undefined) throw new NoUploadError(id);
|
||||
checkPiece(this.viewOf(u), offset, bytes.length);
|
||||
const n = offset / u.start.chunk;
|
||||
if (!u.pieces.has(n)) u.pieces.set(n, bytes.slice());
|
||||
return this.viewOf(u).received;
|
||||
}
|
||||
async completeUpload(id: string, verify: (read: ReadBack) => Promise<void>): Promise<MediaRecord> {
|
||||
const u = this.uploads.get(id);
|
||||
if (u === undefined) throw new NoUploadError(id);
|
||||
const { received } = this.viewOf(u);
|
||||
if (received !== u.start.size) throw new UploadOffsetError(received);
|
||||
const bytes = new Uint8Array(u.start.size);
|
||||
for (const [n, piece] of u.pieces) bytes.set(piece, n * u.start.chunk);
|
||||
this.uploads.delete(id);
|
||||
await verify(async (offset, length) => bytes.slice(offset, offset + length));
|
||||
if (this.objects.has(id)) throw new MediaExistsError(id);
|
||||
const { chunk: _chunk, createdAt: _at, ...terms } = u.start;
|
||||
const rec: MediaRecord = { ...terms, createdAt: this.now() };
|
||||
this.objects.set(id, { rec, bytes });
|
||||
return rec;
|
||||
}
|
||||
async abortUpload(id: string): Promise<boolean> {
|
||||
return this.uploads.delete(id);
|
||||
}
|
||||
async sweep(): Promise<{ objects: number; uploads: number }> {
|
||||
return { objects: 0, uploads: 0 };
|
||||
}
|
||||
async body(id: string, start: number, end: number): Promise<ReadableStream<Uint8Array>> {
|
||||
const o = this.objects.get(id);
|
||||
if (o === undefined) throw new Error('not found');
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
/**
|
||||
* HTTP routes for sealed media.
|
||||
*
|
||||
* PUT /v1/media/:id signed by the owner; body = the sealed SMF1 file
|
||||
* PUT /v1/media/:id signed by the owner; body = a sealed SMF1 file of at most one piece
|
||||
* POST /v1/media/:id/upload signed; start a resumable upload, or ask how far it got
|
||||
* PATCH /v1/media/:id/upload signed; one piece of it (see `upload.ts`)
|
||||
* DELETE /v1/media/:id/upload signed; give up on it
|
||||
* HEAD /v1/media/:id size (read token if the upload set one)
|
||||
* GET /v1/media/:id Range-capable read of the sealed bytes
|
||||
* DELETE /v1/media/:id signed by the owner
|
||||
@@ -13,13 +16,15 @@
|
||||
*/
|
||||
|
||||
import { Hono } from 'hono';
|
||||
import type { Context } from 'hono';
|
||||
import { fromB64u, sha256, toHex } from '../bytes.js';
|
||||
import { decodeFooter, FOOTER_BYTES, sealedSizeFor } from '../sealed.js';
|
||||
import { READ_HASH_HEADER, READ_TOKEN_HEADER, verifyOwner } from '../owner.js';
|
||||
import { MediaExistsError } from './file-store.js';
|
||||
import { BadPieceError, MediaExistsError, NoUploadError, UploadConflictError, UploadOffsetError } from './file-store.js';
|
||||
import { parseRange } from '../browser/range.js';
|
||||
export { parseRange };
|
||||
import type { MediaStore } from './file-store.js';
|
||||
import type { MediaStore, ReadBack } from './file-store.js';
|
||||
import { MAX_PIECE_BYTES, OFFSET_HEADER, UPLOAD_WINDOW, chunkFor, pieceProblem } from '../upload.js';
|
||||
|
||||
export interface MediaRoutesOptions {
|
||||
/** Owner keys (base64url) allowed to upload. Unset = any key, within quota. */
|
||||
@@ -36,6 +41,10 @@ export interface MediaRoutesOptions {
|
||||
const ID_RE = /^[0-9a-f]{32}$/;
|
||||
const GiB = 1024 * 1024 * 1024;
|
||||
|
||||
class NotSealedError extends Error {
|
||||
override readonly name = 'NotSealedError';
|
||||
}
|
||||
|
||||
async function tokenMatches(hash: string | null, token: string | null | undefined): Promise<boolean> {
|
||||
if (hash === null) return true;
|
||||
if (token === null || token === undefined) return false;
|
||||
@@ -53,6 +62,40 @@ export function createMediaRoutes(store: MediaStore, opts: MediaRoutesOptions =
|
||||
const maxOwner = opts.maxOwnerBytes ?? 256 * GiB;
|
||||
const allowed = opts.allowedOwners !== undefined ? new Set(opts.allowedOwners) : null;
|
||||
|
||||
/** Why `owner` may not store `size` more bytes under `id`, as a response — or null. */
|
||||
const refuse = async (c: Context, owner: string, id: string, size: number) => {
|
||||
if (allowed !== null && !allowed.has(owner)) {
|
||||
return c.json({ error: 'FORBIDDEN', message: 'this key may not upload here' }, 403);
|
||||
}
|
||||
if (size > maxObject) return c.json({ error: 'TOO_LARGE', limit: maxObject }, 413);
|
||||
if ((await store.usage(owner)) + size > maxOwner) {
|
||||
return c.json({ error: 'QUOTA', message: 'owner quota exceeded', limit: maxOwner }, 413);
|
||||
}
|
||||
if (opts.maxTotalBytes !== undefined && (await store.totalBytes()) + size > opts.maxTotalBytes) {
|
||||
return c.json({ error: 'STORE_FULL' }, 507);
|
||||
}
|
||||
if ((await store.get(id)) !== null) return c.json({ error: 'EXISTS', message: 'sealed media is immutable' }, 409);
|
||||
return null;
|
||||
};
|
||||
|
||||
/** The footer parses, names this id and implies exactly this size. Throws `NotSealedError` why not. */
|
||||
const checkSealed = async (id: string, size: number, read: ReadBack) => {
|
||||
const tail = await read(size - FOOTER_BYTES, FOOTER_BYTES);
|
||||
let footer: ReturnType<typeof decodeFooter>;
|
||||
try {
|
||||
footer = decodeFooter(tail);
|
||||
} catch (e) {
|
||||
throw new NotSealedError((e as Error).message);
|
||||
}
|
||||
if (toHex(footer.mediaId) !== id) throw new NotSealedError('footer names a different media id');
|
||||
if (sealedSizeFor(footer) !== size) throw new NotSealedError('footer does not match the file size');
|
||||
};
|
||||
|
||||
const readHashOf = (c: Context): string | null => {
|
||||
const h = c.req.header(READ_HASH_HEADER) ?? '';
|
||||
return h === '' || /^[0-9a-f]{64}$/.test(h) ? h : null;
|
||||
};
|
||||
|
||||
app.put('/v1/media/:id', async (c) => {
|
||||
const id = c.req.param('id');
|
||||
if (!ID_RE.test(id)) return c.json({ error: 'BAD_ID' }, 400);
|
||||
@@ -60,23 +103,18 @@ export function createMediaRoutes(store: MediaStore, opts: MediaRoutesOptions =
|
||||
if (!Number.isSafeInteger(size) || size < FOOTER_BYTES) {
|
||||
return c.json({ error: 'LENGTH_REQUIRED', message: 'Content-Length of the sealed file is required' }, 411);
|
||||
}
|
||||
const readTokenHash = c.req.header(READ_HASH_HEADER) ?? '';
|
||||
if (readTokenHash !== '' && !/^[0-9a-f]{64}$/.test(readTokenHash)) {
|
||||
return c.json({ error: 'BAD_READ_HASH' }, 400);
|
||||
}
|
||||
const readTokenHash = readHashOf(c);
|
||||
if (readTokenHash === null) return c.json({ error: 'BAD_READ_HASH' }, 400);
|
||||
const auth = verifyOwner(c.req.raw.headers, { op: 'put', id, size, readTokenHash }, now());
|
||||
if (!auth.ok) return c.json({ error: 'UNAUTHORIZED', message: auth.reason }, 401);
|
||||
if (allowed !== null && !allowed.has(auth.owner)) {
|
||||
return c.json({ error: 'FORBIDDEN', message: 'this key may not upload here' }, 403);
|
||||
if (size > MAX_PIECE_BYTES) {
|
||||
return c.json(
|
||||
{ error: 'USE_UPLOAD', message: `files over ${MAX_PIECE_BYTES} bytes go up in pieces: POST /v1/media/${id}/upload` },
|
||||
413,
|
||||
);
|
||||
}
|
||||
if (size > maxObject) return c.json({ error: 'TOO_LARGE', limit: maxObject }, 413);
|
||||
if ((await store.usage(auth.owner)) + size > maxOwner) {
|
||||
return c.json({ error: 'QUOTA', message: 'owner quota exceeded', limit: maxOwner }, 413);
|
||||
}
|
||||
if (opts.maxTotalBytes !== undefined && (await store.totalBytes()) + size > opts.maxTotalBytes) {
|
||||
return c.json({ error: 'STORE_FULL' }, 507);
|
||||
}
|
||||
if ((await store.get(id)) !== null) return c.json({ error: 'EXISTS', message: 'sealed media is immutable' }, 409);
|
||||
const refused = await refuse(c, auth.owner, id, size);
|
||||
if (refused !== null) return refused;
|
||||
const body = c.req.raw.body;
|
||||
if (body === null) return c.json({ error: 'EMPTY_BODY' }, 400);
|
||||
|
||||
@@ -98,12 +136,11 @@ export function createMediaRoutes(store: MediaStore, opts: MediaRoutesOptions =
|
||||
return c.json({ error: 'LENGTH_MISMATCH', message: `got ${up.written} of ${size} bytes` }, 400);
|
||||
}
|
||||
try {
|
||||
const footer = decodeFooter(await up.readBack(size - FOOTER_BYTES, FOOTER_BYTES));
|
||||
if (toHex(footer.mediaId) !== id) throw new Error('footer names a different media id');
|
||||
if (sealedSizeFor(footer) !== size) throw new Error('footer does not match the file size');
|
||||
await checkSealed(id, size, (o, l) => up.readBack(o, l));
|
||||
} catch (e) {
|
||||
await up.abort();
|
||||
return c.json({ error: 'NOT_SMF1', message: (e as Error).message }, 422);
|
||||
if (!(e instanceof NotSealedError)) throw e;
|
||||
return c.json({ error: 'NOT_SMF1', message: e.message }, 422);
|
||||
}
|
||||
await up.commit({
|
||||
id,
|
||||
@@ -120,7 +157,132 @@ export function createMediaRoutes(store: MediaStore, opts: MediaRoutesOptions =
|
||||
return c.json({ id, size }, 201);
|
||||
});
|
||||
|
||||
const read = async (c: import('hono').Context, head: boolean) => {
|
||||
/** The store's refusals of an upload step, as responses; anything else is a 500. */
|
||||
const uploadError = (c: Context, e: unknown) => {
|
||||
if (e instanceof UploadOffsetError) return c.json({ error: 'OFFSET', received: e.received }, 409);
|
||||
if (e instanceof BadPieceError) return c.json({ error: 'BAD_PIECE', message: e.message }, 400);
|
||||
if (e instanceof UploadConflictError) {
|
||||
return c.json({ error: 'UPLOAD_CONFLICT', message: 'an upload of this id is under way on other terms' }, 409);
|
||||
}
|
||||
if (e instanceof NoUploadError) return c.json({ error: 'NO_UPLOAD' }, 404);
|
||||
if (e instanceof MediaExistsError) return c.json({ error: 'EXISTS', message: 'sealed media is immutable' }, 409);
|
||||
throw e;
|
||||
};
|
||||
|
||||
app.post('/v1/media/:id/upload', async (c) => {
|
||||
const id = c.req.param('id');
|
||||
if (!ID_RE.test(id)) return c.json({ error: 'BAD_ID' }, 400);
|
||||
const size = Number(c.req.header('x-shade-size'));
|
||||
if (!Number.isSafeInteger(size) || size < FOOTER_BYTES) {
|
||||
return c.json({ error: 'BAD_SIZE', message: 'x-shade-size: the sealed file size' }, 400);
|
||||
}
|
||||
const readTokenHash = readHashOf(c);
|
||||
if (readTokenHash === null) return c.json({ error: 'BAD_READ_HASH' }, 400);
|
||||
const auth = verifyOwner(c.req.raw.headers, { op: 'upload', id, size, readTokenHash }, now());
|
||||
if (!auth.ok) return c.json({ error: 'UNAUTHORIZED', message: auth.reason }, 401);
|
||||
const terms = {
|
||||
id,
|
||||
owner: auth.owner,
|
||||
size,
|
||||
readTokenHash: readTokenHash === '' ? null : readTokenHash,
|
||||
chunk: chunkFor(size),
|
||||
createdAt: now(),
|
||||
};
|
||||
try {
|
||||
// Done already: the last piece landed but its answer was lost on the way.
|
||||
const done = await store.get(id);
|
||||
if (done !== null && done.owner === auth.owner && done.size === size && done.readTokenHash === terms.readTokenHash) {
|
||||
return c.json({ id, size, chunk: terms.chunk, window: UPLOAD_WINDOW, received: size, landed: [], complete: true });
|
||||
}
|
||||
const had = await store.getUpload(id);
|
||||
// Resuming is not a new reservation: the upload's size is already counted.
|
||||
if (had === null) {
|
||||
const refused = await refuse(c, auth.owner, id, size);
|
||||
if (refused !== null) return refused;
|
||||
}
|
||||
const up = await store.openUpload(had !== null ? { ...terms, chunk: had.chunk, createdAt: had.createdAt } : terms);
|
||||
return c.json(
|
||||
{ id, size: up.size, chunk: up.chunk, window: UPLOAD_WINDOW, received: up.received, landed: up.landed },
|
||||
had === null ? 201 : 200,
|
||||
);
|
||||
} catch (e) {
|
||||
return uploadError(c, e);
|
||||
}
|
||||
});
|
||||
|
||||
app.patch('/v1/media/:id/upload', async (c) => {
|
||||
const id = c.req.param('id');
|
||||
if (!ID_RE.test(id)) return c.json({ error: 'BAD_ID' }, 400);
|
||||
const length = Number(c.req.header('content-length') ?? '0');
|
||||
const offset = Number(c.req.header(OFFSET_HEADER));
|
||||
if (!Number.isSafeInteger(length) || length < 0 || length > MAX_PIECE_BYTES) {
|
||||
return c.json({ error: 'BAD_PIECE', message: `Content-Length of at most ${MAX_PIECE_BYTES}` }, 400);
|
||||
}
|
||||
if (!Number.isSafeInteger(offset) || offset < 0) return c.json({ error: 'BAD_PIECE', message: `${OFFSET_HEADER} required` }, 400);
|
||||
const auth = verifyOwner(c.req.raw.headers, { op: 'piece', id, offset, length }, now());
|
||||
if (!auth.ok) return c.json({ error: 'UNAUTHORIZED', message: auth.reason }, 401);
|
||||
/** Stored already — by a request that landed the last piece alongside this one, or whose answer was lost. */
|
||||
const storedFor = async () => {
|
||||
const rec = await store.get(id);
|
||||
return rec !== null && rec.owner === auth.owner ? c.json({ id, size: rec.size }, 201) : null;
|
||||
};
|
||||
try {
|
||||
const up = await store.getUpload(id);
|
||||
if (up === null || up.owner !== auth.owner) return (await storedFor()) ?? c.json({ error: 'NO_UPLOAD' }, 404);
|
||||
// Everything in already (a completion that was cut off): an empty piece at the end finishes it.
|
||||
const finishing = up.received === up.size && offset === up.size && length === 0;
|
||||
if (!finishing) {
|
||||
// Refuse before reading a body that cannot be used.
|
||||
const problem = pieceProblem(up, offset, length);
|
||||
if (problem !== null) {
|
||||
return problem.ahead
|
||||
? c.json({ error: 'OFFSET', received: up.received }, 409)
|
||||
: c.json({ error: 'BAD_PIECE', message: problem.message }, 400);
|
||||
}
|
||||
let received = up.received;
|
||||
// A piece that landed already is not read again.
|
||||
if (offset >= up.received && !up.landed.includes(offset / up.chunk)) {
|
||||
const bytes = new Uint8Array(await c.req.arrayBuffer());
|
||||
if (bytes.length !== length) {
|
||||
return c.json({ error: 'LENGTH_MISMATCH', message: `got ${bytes.length} of ${length} bytes` }, 400);
|
||||
}
|
||||
received = await store.appendUpload(id, offset, bytes);
|
||||
}
|
||||
if (received < up.size) return c.json({ id, received });
|
||||
}
|
||||
try {
|
||||
await store.completeUpload(id, (read) => checkSealed(id, up.size, read));
|
||||
} catch (e) {
|
||||
// The store discarded it; anything else (the bucket hiccuped) leaves it to retry.
|
||||
if (e instanceof NotSealedError) return c.json({ error: 'NOT_SMF1', message: e.message }, 422);
|
||||
if (e instanceof NoUploadError || e instanceof MediaExistsError) {
|
||||
const stored = await storedFor();
|
||||
if (stored !== null) return stored;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return c.json({ id, size: up.size }, 201);
|
||||
} catch (e) {
|
||||
if (e instanceof NoUploadError) {
|
||||
const stored = await storedFor();
|
||||
if (stored !== null) return stored;
|
||||
}
|
||||
return uploadError(c, e);
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/v1/media/:id/upload', async (c) => {
|
||||
const id = c.req.param('id');
|
||||
if (!ID_RE.test(id)) return c.json({ error: 'BAD_ID' }, 400);
|
||||
const auth = verifyOwner(c.req.raw.headers, { op: 'abort', id }, now());
|
||||
if (!auth.ok) return c.json({ error: 'UNAUTHORIZED', message: auth.reason }, 401);
|
||||
const up = await store.getUpload(id);
|
||||
if (up === null || up.owner !== auth.owner) return c.json({ error: 'NO_UPLOAD' }, 404);
|
||||
await store.abortUpload(id);
|
||||
return c.json({ id, aborted: true });
|
||||
});
|
||||
|
||||
const read = async (c: Context, head: boolean) => {
|
||||
const id = c.req.param('id') ?? '';
|
||||
if (!ID_RE.test(id)) return c.json({ error: 'BAD_ID' }, 400);
|
||||
const rec = await store.get(id);
|
||||
|
||||
@@ -21,13 +21,20 @@
|
||||
* failed) are removed by `sweep()`, which spares anything younger than the
|
||||
* grace period: it may be an upload still running on another instance.
|
||||
*
|
||||
* A resumable upload (see `upload.ts`) is a multipart upload whose state —
|
||||
* key, upload id, the parts' ETags, how far it got — lives in the index, so
|
||||
* the next piece may land on any instance. Piece n is part n+1, so pieces
|
||||
* land in any order and a retried piece rewrites its own part with the same
|
||||
* bytes; the index records a part's ETag only where none is recorded yet.
|
||||
*
|
||||
* The bucket only ever holds sealed SMF1 bytes. Nothing in it, or in the
|
||||
* index, is a key.
|
||||
*/
|
||||
|
||||
import { randomBytes, toHex } from '../bytes.js';
|
||||
import { MediaExistsError } from './file-store.js';
|
||||
import type { MediaRecord, MediaStore, MediaUpload } from './file-store.js';
|
||||
import { MediaExistsError, NoUploadError, UploadConflictError, UploadOffsetError, checkPiece } from './file-store.js';
|
||||
import type { MediaRecord, MediaStore, MediaUpload, PendingStart, PendingUpload, ReadBack } from './file-store.js';
|
||||
import { receivedOf } from '../upload.js';
|
||||
import type { S3Bucket } from './s3.js';
|
||||
/** A record and the object holding its bytes. */
|
||||
export interface IndexedMedia extends MediaRecord {
|
||||
@@ -42,15 +49,59 @@ export interface MediaIndex {
|
||||
insert(rec: IndexedMedia): Promise<void>;
|
||||
/** Remove and return the record, or null if there was none. */
|
||||
remove(id: string): Promise<IndexedMedia | null>;
|
||||
/** Bytes of an owner's records plus the promised size of its uploads under way. */
|
||||
usage(owner: string): Promise<number>;
|
||||
/** Likewise across owners. */
|
||||
totalBytes(): Promise<number>;
|
||||
getPending(id: string): Promise<PendingObject | null>;
|
||||
/** Insert, or return the upload already recorded for the id (whoever got there first). */
|
||||
insertPending(p: PendingObject): Promise<PendingObject>;
|
||||
/** Record that piece `n` landed as part n+1, unless it is recorded already. */
|
||||
landPiece(id: string, n: number, etag: string, at: number): Promise<void>;
|
||||
removePending(id: string): Promise<PendingObject | null>;
|
||||
/** Uploads with no new piece since `before`. */
|
||||
stalePending(before: number): Promise<PendingObject[]>;
|
||||
/** Newest first. */
|
||||
list(owner: string): Promise<MediaRecord[]>;
|
||||
}
|
||||
|
||||
/** A resumable upload in the bucket. */
|
||||
export interface PendingObject extends PendingStart {
|
||||
key: string;
|
||||
uploadId: string;
|
||||
/** ETag of piece n's part at index n; null (or past the end) where it has not landed. */
|
||||
etags: (string | null)[];
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
/** For tests and single-process use — a relay with more than one instance needs a shared index. */
|
||||
export class MemoryMediaIndex implements MediaIndex {
|
||||
private readonly recs = new Map<string, IndexedMedia>();
|
||||
private readonly pending = new Map<string, PendingObject>();
|
||||
async getPending(id: string): Promise<PendingObject | null> {
|
||||
const p = this.pending.get(id);
|
||||
return p === undefined ? null : { ...p, etags: [...p.etags] };
|
||||
}
|
||||
async insertPending(p: PendingObject): Promise<PendingObject> {
|
||||
if (!this.pending.has(p.id)) this.pending.set(p.id, { ...p, etags: [...p.etags] });
|
||||
return (await this.getPending(p.id))!;
|
||||
}
|
||||
async landPiece(id: string, n: number, etag: string, at: number): Promise<void> {
|
||||
const p = this.pending.get(id);
|
||||
if (p === undefined) return;
|
||||
while (p.etags.length <= n) p.etags.push(null);
|
||||
if (p.etags[n] != null) return;
|
||||
p.etags[n] = etag;
|
||||
p.updatedAt = at;
|
||||
}
|
||||
async removePending(id: string): Promise<PendingObject | null> {
|
||||
const p = this.pending.get(id) ?? null;
|
||||
this.pending.delete(id);
|
||||
return p;
|
||||
}
|
||||
async stalePending(before: number): Promise<PendingObject[]> {
|
||||
return [...this.pending.values()].filter((p) => p.updatedAt < before);
|
||||
}
|
||||
async get(id: string): Promise<IndexedMedia | null> {
|
||||
return this.recs.get(id) ?? null;
|
||||
}
|
||||
@@ -66,11 +117,13 @@ export class MemoryMediaIndex implements MediaIndex {
|
||||
async usage(owner: string): Promise<number> {
|
||||
let n = 0;
|
||||
for (const r of this.recs.values()) if (r.owner === owner) n += r.size;
|
||||
for (const p of this.pending.values()) if (p.owner === owner) n += p.size;
|
||||
return n;
|
||||
}
|
||||
async totalBytes(): Promise<number> {
|
||||
let n = 0;
|
||||
for (const r of this.recs.values()) n += r.size;
|
||||
for (const p of this.pending.values()) n += p.size;
|
||||
return n;
|
||||
}
|
||||
async list(owner: string): Promise<MediaRecord[]> {
|
||||
@@ -94,6 +147,8 @@ export interface ObjectMediaStoreOptions {
|
||||
}
|
||||
|
||||
const ID_RE = /^[0-9a-f]{32}$/;
|
||||
const KEY_RE = /^objects\/([0-9a-f]{32})\/[0-9a-f]{32}\.smf$/;
|
||||
const CONTENT_TYPE = 'application/vnd.shade.smf1';
|
||||
const MiB = 1024 * 1024;
|
||||
/** What an upload keeps of its own tail, for `readBack` of the footer. */
|
||||
const TAIL_BYTES = 64 * 1024;
|
||||
@@ -147,11 +202,16 @@ export class ObjectMediaStore implements MediaStore {
|
||||
return this.index.list(owner);
|
||||
}
|
||||
|
||||
/** Every upload gets a key of its own: two uploads never write the same object. */
|
||||
private freshKey(id: string): string {
|
||||
return `${this.prefix}objects/${id}/${toHex(randomBytes(16))}.smf`;
|
||||
}
|
||||
|
||||
async begin(id: string): Promise<MediaUpload> {
|
||||
if (!ID_RE.test(id)) throw new Error('bad media id');
|
||||
const key = `${this.prefix}objects/${id}/${toHex(randomBytes(16))}.smf`;
|
||||
const key = this.freshKey(id);
|
||||
const { index, s3, partSize } = this;
|
||||
const contentType = 'application/vnd.shade.smf1';
|
||||
const contentType = CONTENT_TYPE;
|
||||
let written = 0;
|
||||
let buffered: Uint8Array[] = [];
|
||||
let bufferedBytes = 0;
|
||||
@@ -260,6 +320,104 @@ export class ObjectMediaStore implements MediaStore {
|
||||
};
|
||||
}
|
||||
|
||||
async openUpload(start: PendingStart): Promise<PendingUpload> {
|
||||
if (!ID_RE.test(start.id)) throw new Error('bad media id');
|
||||
if ((await this.index.get(start.id)) !== null) throw new MediaExistsError(start.id);
|
||||
let p = await this.index.getPending(start.id);
|
||||
if (p === null) {
|
||||
const key = this.freshKey(start.id);
|
||||
const uploadId = await this.s3.createMultipart(key, CONTENT_TYPE);
|
||||
p = await this.index.insertPending({ ...start, key, uploadId, etags: [], updatedAt: this.now() });
|
||||
// Another instance started the same upload first: use theirs.
|
||||
if (p.uploadId !== uploadId) await this.s3.abortMultipart(key, uploadId).catch(() => {});
|
||||
}
|
||||
if (p.owner !== start.owner || p.size !== start.size || p.readTokenHash !== start.readTokenHash) {
|
||||
throw new UploadConflictError(start.id);
|
||||
}
|
||||
return pendingView(p);
|
||||
}
|
||||
|
||||
async getUpload(id: string): Promise<PendingUpload | null> {
|
||||
const p = await this.index.getPending(id);
|
||||
return p === null ? null : pendingView(p);
|
||||
}
|
||||
|
||||
async appendUpload(id: string, offset: number, bytes: Uint8Array): Promise<number> {
|
||||
const p = await this.index.getPending(id);
|
||||
if (p === null) throw new NoUploadError(id);
|
||||
checkPiece(pendingView(p), offset, bytes.length);
|
||||
const n = offset / p.chunk;
|
||||
if (p.etags[n] == null) {
|
||||
const etag = await this.s3.uploadPart(p.key, p.uploadId, n + 1, bytes);
|
||||
await this.index.landPiece(id, n, etag, this.now());
|
||||
}
|
||||
const now = await this.index.getPending(id);
|
||||
if (now === null) throw new NoUploadError(id); // aborted, or completed by a request that saw every piece
|
||||
return pendingView(now).received;
|
||||
}
|
||||
|
||||
async completeUpload(id: string, verify: (read: ReadBack) => Promise<void>): Promise<MediaRecord> {
|
||||
const p = await this.index.getPending(id);
|
||||
if (p === null) throw new NoUploadError(id);
|
||||
const { received } = pendingView(p);
|
||||
if (received !== p.size) throw new UploadOffsetError(received);
|
||||
const { s3 } = this;
|
||||
// A completion retried after a crash (or racing one on another instance)
|
||||
// finds the multipart upload already completed: the object is there.
|
||||
if ((await s3.head(p.key)) !== p.size) {
|
||||
try {
|
||||
await s3.completeMultipart(p.key, p.uploadId, p.etags as string[]);
|
||||
} catch (e) {
|
||||
if ((await s3.head(p.key)) !== p.size) throw e;
|
||||
}
|
||||
}
|
||||
const stored = await s3.head(p.key);
|
||||
if (stored !== p.size) {
|
||||
await this.dropPending(p);
|
||||
throw new Error(`object storage holds ${stored ?? 'nothing'} of ${p.size} bytes`);
|
||||
}
|
||||
try {
|
||||
await verify((offset, length) => s3.getRange(p.key, offset, offset + length));
|
||||
} catch (e) {
|
||||
await this.dropPending(p);
|
||||
throw e;
|
||||
}
|
||||
const record: MediaRecord = {
|
||||
id,
|
||||
owner: p.owner,
|
||||
size: p.size,
|
||||
readTokenHash: p.readTokenHash,
|
||||
createdAt: this.now(),
|
||||
};
|
||||
try {
|
||||
await this.index.insert({ ...record, key: p.key });
|
||||
} catch (e) {
|
||||
if (!(e instanceof MediaExistsError)) throw e;
|
||||
const won = await this.index.get(id);
|
||||
await this.index.removePending(id);
|
||||
// The same upload, completed by another instance: done, not lost.
|
||||
if (won !== null && won.key === p.key) return strip(won);
|
||||
await s3.delete(p.key).catch(() => {});
|
||||
throw e;
|
||||
}
|
||||
await this.index.removePending(id);
|
||||
return record;
|
||||
}
|
||||
|
||||
async abortUpload(id: string): Promise<boolean> {
|
||||
const p = await this.index.getPending(id);
|
||||
if (p === null) return false;
|
||||
await this.dropPending(p);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async dropPending(p: PendingObject): Promise<void> {
|
||||
await this.index.removePending(p.id);
|
||||
// Left for sweep() if these fail: nothing points at them any more.
|
||||
await this.s3.abortMultipart(p.key, p.uploadId).catch(() => {});
|
||||
await this.s3.delete(p.key).catch(() => {});
|
||||
}
|
||||
|
||||
async body(id: string, start: number, end: number): Promise<ReadableStream<Uint8Array>> {
|
||||
const rec = await this.index.get(id);
|
||||
if (rec === null) throw new Error('not found');
|
||||
@@ -307,7 +465,7 @@ export class ObjectMediaStore implements MediaStore {
|
||||
do {
|
||||
const page = await this.s3.list(prefix, next);
|
||||
for (const obj of page.objects) {
|
||||
const m = /^objects\/([0-9a-f]{32})\/[0-9a-f]{32}\.smf$/.exec(obj.key.slice(this.prefix.length));
|
||||
const m = KEY_RE.exec(obj.key.slice(this.prefix.length));
|
||||
if (m === null) continue; // not ours: leave it
|
||||
if (!(obj.lastModified < cutoff)) continue;
|
||||
const rec = await this.index.get(m[1]!);
|
||||
@@ -318,8 +476,17 @@ export class ObjectMediaStore implements MediaStore {
|
||||
next = page.next;
|
||||
} while (next !== undefined);
|
||||
let uploads = 0;
|
||||
// Resumable uploads nobody has sent a piece to within the grace period.
|
||||
for (const p of await this.index.stalePending(cutoff)) {
|
||||
await this.dropPending(p);
|
||||
uploads++;
|
||||
}
|
||||
for (const u of await this.s3.listMultipart(prefix)) {
|
||||
if (!(u.initiated < cutoff)) continue;
|
||||
// A resumable upload still being sent is older than the grace period
|
||||
// when the film is big; the index says whether it is alive.
|
||||
const m = KEY_RE.exec(u.key.slice(this.prefix.length));
|
||||
if (m !== null && (await this.index.getPending(m[1]!))?.uploadId === u.uploadId) continue;
|
||||
await this.s3.abortMultipart(u.key, u.uploadId);
|
||||
uploads++;
|
||||
}
|
||||
@@ -327,6 +494,17 @@ export class ObjectMediaStore implements MediaStore {
|
||||
}
|
||||
}
|
||||
|
||||
function pendingView(p: PendingObject): PendingUpload {
|
||||
const { key: _key, uploadId: _u, etags, updatedAt: _at, ...terms } = p;
|
||||
const received = receivedOf(p.size, p.chunk, (n) => etags[n] != null);
|
||||
const past = received / p.chunk;
|
||||
const landed: number[] = [];
|
||||
etags.forEach((e, n) => {
|
||||
if (e != null && n > past) landed.push(n);
|
||||
});
|
||||
return { ...terms, received, landed };
|
||||
}
|
||||
|
||||
function strip(r: IndexedMedia): MediaRecord {
|
||||
const { key: _key, ...rec } = r;
|
||||
return rec;
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { MediaStore } from './file-store.js';
|
||||
import { createLiveRelay, FileLivePinStore } from './live-relay.js';
|
||||
import type { LivePinStore, LiveRelay, LiveRelayOptions } from './live-relay.js';
|
||||
import { createWatchRoutes } from './watch-routes.js';
|
||||
import { MAX_PIECE_BYTES } from '../upload.js';
|
||||
|
||||
export interface MediaServiceOptions {
|
||||
/**
|
||||
@@ -37,6 +38,12 @@ export interface MediaServiceOptions {
|
||||
live?: Omit<LiveRelayOptions, 'pins' | 'allowedOwners'>;
|
||||
/** Re-bundle the watch page per request. */
|
||||
dev?: boolean;
|
||||
/**
|
||||
* Told what each `store.sweep()` (abandoned uploads, orphaned objects)
|
||||
* reclaimed, or why it failed. The sweep runs a minute after start, then
|
||||
* hourly; every instance may run it.
|
||||
*/
|
||||
onSweep?: (result: { objects: number; uploads: number } | Error) => void;
|
||||
}
|
||||
|
||||
export interface MediaService {
|
||||
@@ -47,19 +54,15 @@ export interface MediaService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Largest request body a server mounting media must accept: the largest
|
||||
* sealed file plus headroom. Bun.serve refuses anything over 128 MiB by
|
||||
* default, which would turn every film into a 413 — pass this as
|
||||
* `maxRequestBodySize`, and keep the default cap on every other route
|
||||
* (see `MEDIA_BODY_ROUTE`).
|
||||
* Largest request body a server mounting media must accept: one piece of an
|
||||
* upload (`MAX_PIECE_BYTES`), with headroom — never a whole film, which goes
|
||||
* up in pieces. Bun.serve's default (128 MiB) already covers it; this keeps
|
||||
* it so if either changes.
|
||||
*/
|
||||
export function mediaMaxRequestBody(opts: { media?: { maxObjectBytes?: number } } = {}): number {
|
||||
return (opts.media?.maxObjectBytes ?? 64 * 1024 ** 3) + 1024 * 1024;
|
||||
export function mediaMaxRequestBody(): number {
|
||||
return Math.max(128 * 1024 * 1024, MAX_PIECE_BYTES + 1024 * 1024);
|
||||
}
|
||||
|
||||
/** Path prefix whose bodies the media routes bound themselves (PUT of a sealed file). */
|
||||
export const MEDIA_BODY_ROUTE = '/v1/media/';
|
||||
|
||||
export function createMediaService(opts: MediaServiceOptions): MediaService {
|
||||
const owners = opts.owners === 'any' ? undefined : opts.owners;
|
||||
const dirFor = (what: string) => {
|
||||
@@ -93,7 +96,24 @@ export function createMediaService(opts: MediaServiceOptions): MediaService {
|
||||
});
|
||||
app.route('/', relay.app);
|
||||
app.route('/', createWatchRoutes({ dev: opts.dev === true }));
|
||||
return { app, relay, stop: () => relay.stop() };
|
||||
const sweep = () =>
|
||||
store.sweep().then(
|
||||
(r) => opts.onSweep?.(r),
|
||||
(e: unknown) => opts.onSweep?.(e instanceof Error ? e : new Error(String(e))),
|
||||
);
|
||||
const first = setTimeout(sweep, 60_000);
|
||||
const hourly = setInterval(sweep, 3600_000);
|
||||
first.unref();
|
||||
hourly.unref();
|
||||
return {
|
||||
app,
|
||||
relay,
|
||||
stop: () => {
|
||||
clearTimeout(first);
|
||||
clearInterval(hourly);
|
||||
return relay.stop();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Parse `SHADE_MEDIA_OWNERS`-style config: comma-separated keys, or `*` for any. */
|
||||
|
||||
78
packages/shade-media/src/upload.ts
Normal file
78
packages/shade-media/src/upload.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Upload in pieces: what the relay and its clients agree on.
|
||||
*
|
||||
* A film does not go up as one request. Bun.serve does not hold a slow
|
||||
* request body back — it reads the socket as fast as the client sends and
|
||||
* queues what the handler has not taken yet — so a fast uplink to a relay
|
||||
* whose store is slower (object storage, a busy disk) would put the whole
|
||||
* film in the relay's memory. Bounded requests bound that, and make an
|
||||
* upload survive a dropped connection or a relay restart:
|
||||
*
|
||||
* POST /v1/media/:id/upload start, or ask how far an upload got
|
||||
* → `{ size, chunk, window, received, landed }`, plus
|
||||
* `complete: true` if it was stored (its last answer was lost)
|
||||
* PATCH /v1/media/:id/upload one piece at `x-shade-offset`
|
||||
* → 200 `{ received }`, or 201 once the file is stored
|
||||
* DELETE /v1/media/:id/upload give up
|
||||
*
|
||||
* Every piece but the last is exactly `chunk` bytes, so a piece's place is
|
||||
* its offset and a piece sent twice is the same bytes twice: the second is
|
||||
* a no-op. `received` is how much of the file, from the start, has landed;
|
||||
* up to `window` pieces past it may be in flight at once and land in any
|
||||
* order (`landed` lists those that did), so an upload is not one round trip
|
||||
* per piece. A file no larger than one piece may still go up as a single
|
||||
* `PUT /v1/media/:id`.
|
||||
*/
|
||||
|
||||
const MiB = 1024 * 1024;
|
||||
|
||||
/** Largest request body the media routes take — a whole small file or one piece. */
|
||||
export const MAX_PIECE_BYTES = 64 * MiB;
|
||||
|
||||
/** Piece size a relay picks unless a file is too big for it. */
|
||||
export const DEFAULT_CHUNK_BYTES = 16 * MiB;
|
||||
|
||||
/** S3 caps a multipart upload at 10 000 parts; a piece is one part. */
|
||||
const MAX_PIECES = 10_000;
|
||||
|
||||
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;
|
||||
|
||||
/** 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;
|
||||
return Math.min(MAX_PIECE_BYTES, Math.max(DEFAULT_CHUNK_BYTES, need));
|
||||
}
|
||||
|
||||
/** Largest file that fits in pieces of at most `MAX_PIECE_BYTES`. */
|
||||
export const MAX_UPLOAD_BYTES = MAX_PIECES * MAX_PIECE_BYTES;
|
||||
|
||||
/**
|
||||
* Why a piece at `offset` of `length` bytes cannot be taken now, or null if
|
||||
* it can. `ahead`: it is fine, but too far past `received` — send it later.
|
||||
*/
|
||||
export function pieceProblem(
|
||||
up: { size: number; chunk: number; received: number },
|
||||
offset: number,
|
||||
length: number,
|
||||
): { ahead: boolean; message: string } | null {
|
||||
if (offset % up.chunk !== 0 || offset >= up.size) {
|
||||
return { ahead: false, message: `a piece starts at a multiple of ${up.chunk} inside the file` };
|
||||
}
|
||||
const want = Math.min(up.chunk, up.size - offset);
|
||||
if (length !== want) return { ahead: false, message: `the piece at ${offset} is ${want} bytes` };
|
||||
if (offset >= up.received + UPLOAD_WINDOW * up.chunk) {
|
||||
return { ahead: true, message: `at most ${UPLOAD_WINDOW} pieces past ${up.received} at once` };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** How much of the file, from the start, the landed pieces cover. */
|
||||
export function receivedOf(size: number, chunk: number, landed: (n: number) => boolean): number {
|
||||
const pieces = Math.ceil(size / chunk);
|
||||
let n = 0;
|
||||
while (n < pieces && landed(n)) n++;
|
||||
return Math.min(size, n * chunk);
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
import { describe, test, expect, beforeAll } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { createMediaRoutes, MemoryMediaIndex, ObjectMediaStore, S3Bucket } from '../src/server.js';
|
||||
import { MediaClient, OwnerKey, openGrant, sealMediaBytes, MIN_SEGMENT_SIZE } from '../src/index.js';
|
||||
import { MediaClient, OwnerKey, openGrant, sealMediaBytes, MIN_SEGMENT_SIZE, DEFAULT_CHUNK_BYTES } from '../src/index.js';
|
||||
import { toHex } from '../src/bytes.js';
|
||||
|
||||
const URL_ = process.env.SHADE_TEST_S3_URL;
|
||||
@@ -134,4 +134,59 @@ describe.skipIf(URL_ === undefined)('ObjectMediaStore (S3)', () => {
|
||||
expect(new Uint8Array(await new Response(body).arrayBuffer())).toEqual(new Uint8Array([299 & 0xff, 300 & 0xff]));
|
||||
expect(await store.delete(id)).toBe(true);
|
||||
}, 180_000);
|
||||
|
||||
test('a film in pieces across two instances: each piece lands where it lands, one multipart upload, one object', async () => {
|
||||
const index = new MemoryMediaIndex();
|
||||
const a = serve(new Hono().route('/', createMediaRoutes(new ObjectMediaStore(s3, index, { prefix }))));
|
||||
const b = serve(new Hono().route('/', createMediaRoutes(new ObjectMediaStore(s3, index, { prefix }))));
|
||||
try {
|
||||
const plain = pattern(2 * DEFAULT_CHUNK_BYTES + 5 * 1024 * 1024 + 99);
|
||||
const { bytes, result } = await sealMediaBytes(plain, { meta: { name: 'Film.mkv' } });
|
||||
// A load balancer that sends every other request to the other instance.
|
||||
let n = 0;
|
||||
const roundRobin: typeof fetch = ((input: RequestInfo | URL, init?: RequestInit) =>
|
||||
fetch(String(input).replace(a.base, n++ % 2 === 0 ? a.base : b.base), init)) as typeof fetch;
|
||||
const grant = await new MediaClient(a.base, OwnerKey.generate(), { fetch: roundRobin }).putSealed(result, new Blob([bytes]));
|
||||
expect(n).toBeGreaterThanOrEqual(4); // start + three pieces
|
||||
const reader = await openGrant(grant, { url: grant.url!.replace(a.base, b.base) });
|
||||
expect(await reader.read(0, reader.size)).toEqual(plain);
|
||||
const id = toHex(result.mediaId);
|
||||
expect((await keys()).filter((k) => k.includes(id)).length).toBe(1);
|
||||
expect(await index.getPending(id)).toBeNull();
|
||||
expect(await s3.listMultipart(prefix)).toEqual([]);
|
||||
await new ObjectMediaStore(s3, index, { prefix }).delete(id);
|
||||
} finally {
|
||||
a.server.stop(true);
|
||||
b.server.stop(true);
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
test('pieces out of order and twice at once on two instances; sweep spares an old upload still being sent', async () => {
|
||||
const index = new MemoryMediaIndex();
|
||||
const grace = 2000;
|
||||
const a = new ObjectMediaStore(s3, index, { prefix, sweepGraceMs: grace });
|
||||
const b = new ObjectMediaStore(s3, index, { prefix, sweepGraceMs: grace });
|
||||
const { bytes, result } = await sealMediaBytes(pattern(DEFAULT_CHUNK_BYTES + 1024 * 1024));
|
||||
const id = toHex(result.mediaId);
|
||||
const terms = { id, owner: 'o', size: bytes.length, readTokenHash: null, chunk: DEFAULT_CHUNK_BYTES, createdAt: Date.now() };
|
||||
await a.openUpload(terms);
|
||||
// B starting the same upload finds A's, rather than a second multipart upload.
|
||||
await b.openUpload(terms);
|
||||
expect((await s3.listMultipart(prefix)).filter((u) => u.key.includes(id)).length).toBe(1);
|
||||
|
||||
// The last piece first; then, past the grace period, the first one on both instances at once.
|
||||
expect(await b.appendUpload(id, DEFAULT_CHUNK_BYTES, bytes.slice(DEFAULT_CHUNK_BYTES))).toBe(0);
|
||||
await Bun.sleep(grace + 1200);
|
||||
const first = bytes.slice(0, DEFAULT_CHUNK_BYTES);
|
||||
expect(await Promise.all([a.appendUpload(id, 0, first), b.appendUpload(id, 0, first)])).toEqual([bytes.length, bytes.length]);
|
||||
expect((await index.getPending(id))!.etags.map((e) => e !== null)).toEqual([true, true]);
|
||||
// Its multipart upload is older than the grace period, but a piece landed just now: alive.
|
||||
expect(await a.sweep()).toEqual({ objects: 0, uploads: 0 });
|
||||
expect(await index.getPending(id)).not.toBeNull();
|
||||
// Then nothing more for longer than the grace period: abandoned.
|
||||
await Bun.sleep(grace + 1200);
|
||||
expect(await b.sweep()).toEqual({ objects: 0, uploads: 1 });
|
||||
expect(await index.getPending(id)).toBeNull();
|
||||
expect((await s3.listMultipart(prefix)).filter((u) => u.key.includes(id))).toEqual([]);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
287
packages/shade-media/tests/upload.test.ts
Normal file
287
packages/shade-media/tests/upload.test.ts
Normal file
@@ -0,0 +1,287 @@
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user