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:
2026-10-18 23:39:25 +02:00
parent 5f7c6ff4b4
commit bd4882e1b8
22 changed files with 2076 additions and 101 deletions

View File

@@ -66,6 +66,15 @@ New package **`@shade/media`** — see `docs/media.md`.
`PostgresLivePinStore`, `createSharedMediaBackend` in
`@shade/storage-postgres`. A live pin can no longer change key, even between
instances (`LivePinTakenError`).
- **Uploads in pieces, resumable.** A sealed file over 16 MiB goes up as
`POST /v1/media/:id/upload` + 16 MiB `PATCH` pieces (each signed over its
offset), up to 4 in flight and landing in any order. 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 under way survive restarts (`uploads/` on disk, `shade_media_uploads`
beside the S3 multipart upload), count against quota and are swept after
24 h without a piece. `media put` shows progress. Above all, a relay's
memory no longer grows with the film (see Fixed).
- **`shade live video --input`** a film, `/dev/video0` or `rtsp://…`: ffmpeg is
run for you, H.264/AAC copied (a camera's own encoder) and anything else
encoded to H.264 (keyframe every 2 s) and AAC, as low-latency fMP4.
@@ -116,8 +125,17 @@ New package **`@shade/media`** — see `docs/media.md`.
handler (an unhandled rejection). Now every call fails with the reason.
- The container refused every request body over 128 MiB (Bun's default),
which would have made every film a 413. The cap is raised only when media
is mounted, and every other route now has an explicit 128 MiB body limit.
which would have made every film a 413. Films now go up in pieces of at
most 64 MiB, so the cap stays, and every route has an explicit 128 MiB
body limit.
- An upload put the whole film in the relay's memory whenever the store was
slower than the client: Bun.serve reads a request body as fast as it
arrives, whether the handler takes it or not. One `PUT` of a 512 MiB film
peaked at 762 MiB (disk) and 1011 MiB (S3). In pieces it stays the same at
512 MiB and 1.5 GiB (`bench/media-store.ts`).
- The media sweep ran only for the S3 store, from two copies of the timer
(container and `media serve`). It is now part of every store and of
`createMediaService` (`onSweep` reports it), hourly.
## [4.14.1] — 2026-10-16 — Vault: `edit` for vaults two devices write

View File

@@ -0,0 +1,26 @@
/**
* Media routes over one store, in their own process, for bench/media-store.ts
* (so the relay's memory is measured alone). Prints its port.
*
* bun bench/media-store-relay.ts file <dir>
* bun bench/media-store-relay.ts s3 <s3 url> [<postgres url>]
*/
import { createMediaRoutes, FileMediaStore, MemoryMediaIndex, ObjectMediaStore, S3Bucket, mediaMaxRequestBody } from '../packages/shade-media/src/server.js';
import type { MediaIndex, MediaStore } from '../packages/shade-media/src/server.js';
const [kind, where, pg] = process.argv.slice(2);
let store: MediaStore;
if (kind === 'file') {
store = new FileMediaStore(where!);
} else {
const { bucket, prefix } = S3Bucket.fromUrl(where!);
let index: MediaIndex = new MemoryMediaIndex();
if (pg !== undefined) {
const { PostgresMediaIndex } = await import('../packages/shade-storage-postgres/src/index.js');
index = await PostgresMediaIndex.create(pg);
}
store = new ObjectMediaStore(bucket, index, { prefix });
}
const app = createMediaRoutes(store);
const server = Bun.serve({ port: 0, fetch: (req) => app.fetch(req), idleTimeout: 0, maxRequestBodySize: mediaMaxRequestBody() });
console.log(server.port);

View File

@@ -0,0 +1,42 @@
{
"sizesMiB": [
512,
1536
],
"runs": 3,
"bun": "1.3.5",
"results": {
"512": {
"disk (FileMediaStore)": {
"uploadMiBs": 171,
"readMiBs": 239.5,
"seekP50": 3.78,
"seekP95": 7.03,
"peakRssMiB": 330
},
"S3 + Postgres (ObjectMediaStore)": {
"uploadMiBs": 179.9,
"readMiBs": 146.3,
"seekP50": 15.96,
"seekP95": 28.66,
"peakRssMiB": 360
}
},
"1536": {
"disk (FileMediaStore)": {
"uploadMiBs": 286.6,
"readMiBs": 199.6,
"seekP50": 9.05,
"seekP95": 19.37,
"peakRssMiB": 369
},
"S3 + Postgres (ObjectMediaStore)": {
"uploadMiBs": 79.3,
"readMiBs": 107.4,
"seekP50": 20.37,
"seekP95": 31.89,
"peakRssMiB": 358
}
}
}
}

View File

@@ -0,0 +1,125 @@
[
{
"type": "bar",
"title": "Sealed film store: disk vs S3 (MiB/s)",
"subtitle": "1536 MiB film through the real media routes, median of 3 runs; relay in its own process; S3 = local SeaweedFS",
"y": {
"label": "MiB/s",
"min": 0
},
"note": "Bun 1.3.5. Uploads go up in 16 MiB pieces, up to 4 in flight. Disk: each piece fsynced before it is acknowledged. S3: each piece is one SHA-256-signed multipart part.",
"source": {
"path": "media-store-results.json"
},
"series": [
{
"name": "disk (FileMediaStore)",
"data": [
[
"upload (pieces)",
286.6
],
[
"read + verify (Range)",
199.6
]
]
},
{
"name": "S3 + Postgres (ObjectMediaStore)",
"data": [
[
"upload (pieces)",
79.3
],
[
"read + verify (Range)",
107.4
]
]
}
]
},
{
"type": "bar",
"title": "Relay memory does not grow with the film",
"subtitle": "Peak relay RSS growth during one upload (VmHWM − RSS before), worst of 3 runs, per film size",
"y": {
"label": "MiB",
"min": 0
},
"note": "Bounded by the upload window (4 pieces of 16 MiB) and garbage not yet collected. Before pieces, one PUT of a 512 MiB film put 762 MiB (disk) and 1011 MiB (S3) in the relay: Bun.serve reads a request body as fast as the client sends.",
"source": {
"path": "media-store-results.json"
},
"series": [
{
"name": "disk (FileMediaStore)",
"data": [
[
"512 MiB film",
330
],
[
"1536 MiB film",
369
]
]
},
{
"name": "S3 + Postgres (ObjectMediaStore)",
"data": [
[
"512 MiB film",
360
],
[
"1536 MiB film",
358
]
]
}
]
},
{
"type": "bar",
"title": "Seek latency, disk vs S3 (ms)",
"subtitle": "64 KiB at a random offset of the 1536 MiB film, fresh reader each (n = 50 per run, median of 3 runs)",
"y": {
"label": "ms",
"min": 0
},
"note": "Includes opening: footer + trailer + root check, then the range.",
"source": {
"path": "media-store-results.json"
},
"series": [
{
"name": "disk (FileMediaStore)",
"data": [
[
"p50",
9.05
],
[
"p95",
19.37
]
]
},
{
"name": "S3 + Postgres (ObjectMediaStore)",
"data": [
[
"p50",
20.37
],
[
"p95",
31.89
]
]
}
]
}
]

174
bench/media-store.ts Normal file
View File

@@ -0,0 +1,174 @@
/**
* Where sealed films live: the disk store against the S3 store
* (ObjectMediaStore), through the real media routes, each relay in its own
* process.
*
* Run: SHADE_BENCH_S3_URL=http://key:secret@127.0.0.1:58333/bench \
* [SHADE_BENCH_PG_URL=postgres://…] bun bench/media-store.ts [--mib 512,1536]
*
* Per store: upload (a sealed file in pieces, as `media put` sends it), full read + verify over
* Range, seek latency (64 KiB at random offsets, fresh reader each), and the
* relay's own peak memory during the upload (VmHWM − VmRSS before) — at
* each film size, to show it does not grow with the film.
* Writes bench/media-store-results.json and bench/media-store.chart.json.
*/
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { sealFile } from '../packages/shade-media/src/node.js';
import { MediaClient, openGrant } from '../packages/shade-media/src/client.js';
import { OwnerKey } from '../packages/shade-media/src/owner.js';
const args = process.argv.slice(2);
const SIZES = (args.includes('--mib') ? args[args.indexOf('--mib') + 1]! : '512,1536').split(',').map(Number);
if (SIZES.some((n) => !Number.isInteger(n) || n < 1)) throw new Error('--mib takes sizes in MiB, comma-separated');
// Disk and bucket speed swing with whatever else the machine does: median of several runs.
const RUNS = args.includes('--runs') ? Number(args[args.indexOf('--runs') + 1]) : 3;
const S3 = process.env.SHADE_BENCH_S3_URL;
const PG = process.env.SHADE_BENCH_PG_URL;
if (S3 === undefined) throw new Error('set SHADE_BENCH_S3_URL (a bucket that may be written to)');
const MiB = 1024 * 1024;
const pct = (xs: number[], p: number) => {
const s = [...xs].sort((a, b) => a - b);
return Math.round(s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]! * 100) / 100;
};
const kib = async (pid: number, field: 'VmRSS' | 'VmHWM') =>
Number(new RegExp(`${field}:\\s+(\\d+) kB`).exec(await readFile(`/proc/${pid}/status`, 'utf8'))![1]);
async function relay(argv: string[]) {
const proc = Bun.spawn(['bun', join(import.meta.dir, 'media-store-relay.ts'), ...argv], { stdout: 'pipe', stderr: 'inherit' });
const reader = proc.stdout.getReader();
const { value } = await reader.read();
const port = Number(new TextDecoder().decode(value).trim());
return { proc, base: `http://localhost:${port}` };
}
type Result = { uploadMiBs: number; readMiBs: number; seekP50: number; seekP95: number; peakRssMiB: number };
const S3_NAME = PG !== undefined ? 'S3 + Postgres (ObjectMediaStore)' : 'S3 (ObjectMediaStore)';
const DISK_NAME = 'disk (FileMediaStore)';
/** One film of `mib` MiB through each store. */
async function run(mib: number, work: string): Promise<Record<string, Result>> {
const plain = join(work, 'film.bin');
const sealed = join(work, 'film.smf');
{
const f = Bun.file(plain).writer();
const chunk = new Uint8Array(MiB);
for (let i = 0; i < mib; i++) {
crypto.getRandomValues(chunk.subarray(0, 65536));
for (let o = 65536; o < MiB; o += 65536) chunk.copyWithin(o, 0, 65536);
chunk[0] = i & 0xff;
f.write(chunk);
}
await f.end();
}
const sealResult = await sealFile(plain, sealed, { meta: { name: 'bench.bin' } });
await rm(plain);
const sealedSize = Bun.file(sealed).size;
const stores: [string, string[]][] = [
[DISK_NAME, ['file', join(work, `store-${mib}`)]],
[S3_NAME, ['s3', `${S3!.replace(/\/$/, '')}/bench-${Date.now().toString(36)}`, ...(PG !== undefined ? [PG] : [])]],
];
const results: Record<string, Result> = {};
for (const [name, argv] of stores) {
const runs: Result[] = [];
for (let i = 0; i < RUNS; i++) {
// A fresh relay per run: its high-water mark is this upload's alone.
const { proc, base } = await relay(argv);
try {
const client = new MediaClient(base, OwnerKey.generate());
await Bun.sleep(300);
const rssBefore = await kib(proc.pid, 'VmRSS');
let t = performance.now();
const grant = await client.putSealed(sealResult, Bun.file(sealed));
const upSec = (performance.now() - t) / 1000;
const peak = (await kib(proc.pid, 'VmHWM')) - rssBefore;
const reader = await openGrant(grant);
t = performance.now();
for (let off = 0; off < reader.size; off += 8 * MiB) await reader.read(off, Math.min(8 * MiB, reader.size - off));
const readSec = (performance.now() - t) / 1000;
const seeks: number[] = [];
for (let j = 0; j < 50; j++) {
const r = await openGrant(grant);
const at = Math.floor(Math.random() * (r.size - 65536));
const s = performance.now();
await r.read(at, 65536);
seeks.push(performance.now() - s);
}
runs.push({
uploadMiBs: sealedSize / MiB / upSec,
readMiBs: mib / readSec,
seekP50: pct(seeks, 50),
seekP95: pct(seeks, 95),
peakRssMiB: peak / 1024,
});
await client.delete(grant.mediaId);
} finally {
proc.kill();
await proc.exited;
}
}
const median = (k: keyof Result) => pct(runs.map((r) => r[k]), 50);
results[name] = {
uploadMiBs: Math.round(median('uploadMiBs') * 10) / 10,
readMiBs: Math.round(median('readMiBs') * 10) / 10,
seekP50: median('seekP50'),
seekP95: median('seekP95'),
// Memory is a bound, not a typical value: the worst run.
peakRssMiB: Math.round(Math.max(...runs.map((r) => r.peakRssMiB))),
};
console.log(`${mib} MiB`, name, results[name], `(${RUNS} runs; upload ${runs.map((r) => r.uploadMiBs.toFixed(0)).join('/')} MiB/s)`);
}
await rm(sealed);
await rm(join(work, `store-${mib}`), { recursive: true, force: true });
return results;
}
const work = await mkdtemp(join(tmpdir(), 'shade-bench-store-'));
try {
const bySize: Record<string, Record<string, Result>> = {};
for (const mib of SIZES) bySize[mib] = await run(mib, work);
await writeFile(
join(import.meta.dir, 'media-store-results.json'),
`${JSON.stringify({ sizesMiB: SIZES, runs: RUNS, bun: Bun.version, results: bySize }, null, 2)}\n`,
);
const largest = Math.max(...SIZES);
const results = bySize[largest]!;
const names = [DISK_NAME, S3_NAME];
const charts = [
{
type: 'bar',
title: 'Sealed film store: disk vs S3 (MiB/s)',
subtitle: `${largest} MiB film through the real media routes, median of ${RUNS} runs; relay in its own process; S3 = local SeaweedFS`,
y: { label: 'MiB/s', min: 0 },
note: `Bun ${Bun.version}. Uploads go up in 16 MiB pieces, up to 4 in flight. Disk: each piece fsynced before it is acknowledged. S3: each piece is one SHA-256-signed multipart part.`,
source: { path: 'media-store-results.json' },
series: names.map((n) => ({ name: n, data: [['upload (pieces)', results[n]!.uploadMiBs], ['read + verify (Range)', results[n]!.readMiBs]] })),
},
{
type: 'bar',
title: 'Relay memory does not grow with the film',
subtitle: `Peak relay RSS growth during one upload (VmHWM − RSS before), worst of ${RUNS} runs, per film size`,
y: { label: 'MiB', min: 0 },
note: 'Bounded by the upload window (4 pieces of 16 MiB) and garbage not yet collected. Before pieces, one PUT of a 512 MiB film put 762 MiB (disk) and 1011 MiB (S3) in the relay: Bun.serve reads a request body as fast as the client sends.',
source: { path: 'media-store-results.json' },
series: names.map((n) => ({ name: n, data: SIZES.map((mib) => [`${mib} MiB film`, bySize[mib]![n]!.peakRssMiB]) })),
},
{
type: 'bar',
title: 'Seek latency, disk vs S3 (ms)',
subtitle: `64 KiB at a random offset of the ${largest} MiB film, fresh reader each (n = 50 per run, median of ${RUNS} runs)`,
y: { label: 'ms', min: 0 },
note: 'Includes opening: footer + trailer + root check, then the range.',
source: { path: 'media-store-results.json' },
series: names.map((n) => ({ name: n, data: [['p50', results[n]!.seekP50], ['p95', results[n]!.seekP95]] })),
},
];
await writeFile(join(import.meta.dir, 'media-store.chart.json'), `${JSON.stringify(charts, null, 2)}\n`);
console.log('wrote bench/media-store-results.json and bench/media-store.chart.json');
} finally {
await rm(work, { recursive: true, force: true });
}

View File

@@ -98,7 +98,35 @@ SHADE_MEDIA_OWNERS=<key>,<key> # who may upload / open channels (`sh
SHADE_DISABLE_MEDIA=1 # optional: off entirely
```
Routes: `/v1/media/:id`, `/v1/live/:channelId` (WebSocket), `/watch/`.
Routes: `/v1/media/:id`, `/v1/media/:id/upload`, `/v1/live/:channelId` (WebSocket), `/watch/`.
### Uploads go up in pieces
A sealed file larger than 16 MiB is not one request. `shade media put` (and
`MediaClient.putSealed`) starts an upload (`POST /v1/media/:id/upload`, signed over
id, size and read-token hash) and sends it in pieces of 16 MiB (`PATCH`, each signed
over its offset and length), up to 4 at once. The relay keeps what landed on disk or
in the bucket, so:
- **A dropped connection costs the pieces in flight, not the film.** After a failure
the client asks the relay how far the upload got and sends only what is missing,
with backoff, for up to 8 tries in a row. A piece sent twice is the same bytes twice,
and the second is a no-op.
- **A relay restart, or the next piece landing on another instance, changes nothing.**
The upload is `uploads/<id>.part` + `.json` + `.log` on disk, or a row in
`shade_media_uploads` beside its S3 multipart upload. The log (or the row) names
only pieces already on stable storage, so a piece cut off by a crash is sent again.
- **The relay's memory is bounded by the window, not the film.** This is the reason
the protocol exists. Bun.serve does not hold back a request body the handler reads
slowly: one `PUT` of a 512 MiB film put 762 MiB (disk) and 1011 MiB (S3) into the
relay. In pieces, it stays around 350 MiB at 512 MiB and at 1.5 GiB alike
(`bench/media-store.ts`). Every route now takes at most 64 MiB per
request, so Bun's own 128 MiB cap stays in place.
- An upload counts against the owner's quota from its start. One with no new piece
for 24 hours is dropped by the sweep.
A file of at most one piece still goes up as one `PUT /v1/media/:id`. The full exchange
is described in `packages/shade-media/src/upload.ts`.
**There is no in-memory fallback**, for the vault's reason: a library that lives in
RAM accepts every upload and loses all of it on the next redeploy, without anything
@@ -122,15 +150,18 @@ SeaweedFS, Garage, B2); credentials left out of the URL come from
or `?region=`. A bucket the credentials cannot use is reported at start; media stays
off and the rest of the server runs.
- **Uploads stream.** A film goes up as an S3 multipart upload, part by part, with at
most three 16 MiB parts in memory (512 MiB through: 11 MiB of RSS). Every part's
payload is hashed into its signature, so a part damaged in transit is refused.
- **Uploads stream.** Each piece of an upload is one part of an S3 multipart upload,
and any instance may take the next one. Every part's payload is hashed into its
signature, so a part damaged in transit is refused. A file sent in one `PUT` goes up
part by part as it arrives, with at most three 16 MiB parts in memory.
- **Racing uploads of one id** (on any instances) each go to their own object key;
the primary key in Postgres admits one record, and the loser deletes its object.
Delete removes the record first, so a crash never brings a film back.
- **Sweeping.** Objects no record points at and multipart uploads never completed
(a crash mid-upload) are reclaimed after 24 hours, a minute after start and every
6 hours. Every instance may sweep at once.
- **Sweeping.** Three kinds of leftovers are reclaimed after 24 hours: objects no
record points at, uploads with no new piece in that time, and multipart uploads no
upload owns (a crash mid-`PUT`). An upload still receiving pieces is spared, however
old its multipart upload is. The sweep runs a minute after start and then hourly,
for the disk store too, and every instance may sweep at once.
- **Live channels** are pinned in Postgres, so a channel cannot be pinned to two keys
by two instances. Each instance records which channels' publishers are connected to
it (`shade_live_publishers`, refreshed every 10 s). An instance whose viewers want a
@@ -450,6 +481,15 @@ done in v1. A deployment that needs it can pad above this layer.
byte for byte (`MediaVectorTest`).
- `bench/media.ts`: throughput, seek latency and live fan-out, written as
`bench/media.chart.json`.
- `bench/media-store.ts`: disk store against S3 (+ Postgres) through the real routes,
each relay in its own process. Upload and read speed, seek latency, and the relay's
peak memory at two film sizes, median or worst of 3 runs
(`bench/media-store.chart.json`).
- `tests/upload.test.ts`: uploads in pieces on the memory and disk stores. Covers
dropped connections before and after the relay stored a piece, a restart with a
piece cut off mid-write, pieces out of order and twice at once, the window, signatures
per offset, a bad footer at the last piece, quota and sweep. `object-store.test.ts`
covers the same over S3 across two instances.
## Design notes
@@ -477,14 +517,19 @@ done in v1. A deployment that needs it can pad above this layer.
the encoder wrote. CENC-encrypted tracks (`encv`/`enca`) are refused; Shade already
encrypts, and a second DRM layer would leave the viewer without keys.
- **Bun 1.3.5.** `new Response(Bun.file(p).slice(a, b))` sent the whole file in
answer to a Range request when the file was large. The store therefore reads the
range itself.
answer to a Range request when the file was large, so the store reads the range
itself. `fetch(url, { body: Bun.file(p).slice(a, b) })` never finishes sending, so
the client reads each piece itself. And Bun.serve buffers a request body without
limit when the handler reads it slower than the client sends, which is why uploads
go up in pieces.
## Limits (defaults)
| | |
|---|---|
| sealed file | 64 GiB per object, 256 GiB per owner (`MediaRoutesOptions`) |
| sealed file | 64 GiB per object, 256 GiB per owner, uploads under way included (`MediaRoutesOptions`) |
| one request | 64 MiB (`MAX_PIECE_BYTES`): a file larger than that goes up in pieces of 16 MiB (more for files over 156 GiB), 4 in flight |
| abandoned upload | dropped after 24 h without a new piece |
| metadata | 64 KiB |
| live frame payload | 16 MiB |
| live backlog | 3 keyframes, at most 32 MiB / 5000 frames per channel |

View File

@@ -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 {

View File

@@ -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);

View File

@@ -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';

View File

@@ -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':

View File

@@ -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';

View File

@@ -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');

View File

@@ -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);

View File

@@ -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;

View File

@@ -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. */

View 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);
}

View File

@@ -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);
});

View 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);
}
});
});

View File

@@ -236,17 +236,17 @@ if (disableRateLimit) {
const app = new Hono();
app.use('*', metricsMiddleware());
// Bun.serve's own 128 MiB request cap is raised when media is mounted (a film
// is gigabytes), so it can no longer be what protects every other route —
// several read the whole body before checking its size. Keep that cap here,
// explicitly, for everything but the media upload route, which counts its
// bytes against Content-Length itself.
// Several routes read the whole body before checking its size: cap every
// request here. Media fits under it — films go up in pieces of at most
// MAX_PIECE_BYTES, never as one body.
const DEFAULT_MAX_BODY = 128 * 1024 * 1024;
const generalBodyLimit = bodyLimit({
maxSize: DEFAULT_MAX_BODY,
onError: (c) => c.json({ error: 'PAYLOAD_TOO_LARGE', limit: DEFAULT_MAX_BODY }, 413),
});
app.use('*', (c, next) => (c.req.path.startsWith('/v1/media/') ? next() : generalBodyLimit(c, next)));
app.use(
'*',
bodyLimit({
maxSize: DEFAULT_MAX_BODY,
onError: (c) => c.json({ error: 'PAYLOAD_TOO_LARGE', limit: DEFAULT_MAX_BODY }, 413),
}),
);
app.route('/', createHealthRoutes(store, VERSION));
app.route('/', createMetricsRoutes());
app.route('/', createOpenApiRoutes());
@@ -370,31 +370,29 @@ if (process.env.SHADE_DISABLE_MEDIA === '1') {
owners,
store: backend.store,
pins: backend.pins,
onSweep: reportMediaSweep,
...(self !== undefined ? { live: { mesh: { self, locator: backend.locator } } } : {}),
});
where = backend.describe;
// Reclaim what crashed uploads left in the bucket. Every instance may
// run it; the grace period spares uploads still in flight anywhere.
const sweep = () =>
backend.sweep().then(
(n) => (n.objects + n.uploads > 0 ? logger.info('Media sweep', n) : undefined),
(e: unknown) => logger.warn('Media sweep failed', { error: String(e) }),
);
setTimeout(sweep, 60_000).unref();
setInterval(sweep, 6 * 3600_000).unref();
} else if (mediaS3 === undefined) {
mediaService = createMediaService({ dir: process.env.SHADE_MEDIA_DIR!, owners });
mediaService = createMediaService({ dir: process.env.SHADE_MEDIA_DIR!, owners, onSweep: reportMediaSweep });
}
if (mediaService !== null) {
app.route('/', mediaService.app);
logger.info('Media enabled', {
routes: ['/v1/media/:id', '/v1/live/:channelId', '/watch/'],
routes: ['/v1/media/:id', '/v1/media/:id/upload', '/v1/live/:channelId', '/watch/'],
store: where,
owners: owners === 'any' ? 'any' : owners.length,
});
}
}
/** What the media store's sweep reclaimed (abandoned uploads, orphaned objects), or why it failed. */
function reportMediaSweep(r: { objects: number; uploads: number } | Error): void {
if (r instanceof Error) logger.warn('Media sweep failed', { error: r.message });
else if (r.objects + r.uploads > 0) logger.info('Media sweep', r);
}
// ─── Optional: Observer + Dashboard ──────────────────────────
const observerToken = process.env.SHADE_OBSERVER_TOKEN;

View File

@@ -282,7 +282,7 @@ export async function ensureInboxServerTables(sql: Sql): Promise<void> {
}
/**
* Sealed-media records (`PostgresMediaIndex`) and live-channel pins
* Sealed-media records and uploads under way (`PostgresMediaIndex`) and live-channel pins
* (`PostgresLivePinStore`) for relays that share one bucket. Sizes are
* BIGINT: one film can pass 2 GiB, an owner's library 2^31 bytes easily.
*/
@@ -301,6 +301,31 @@ export async function ensureMediaServerTables(sql: Sql): Promise<void> {
CREATE INDEX IF NOT EXISTS shade_media_owner_idx
ON shade_media_objects(owner_pubkey, created_at DESC)
`;
// Resumable uploads under way: the multipart upload and which pieces
// landed, so the next piece may land on any instance.
await sql`
CREATE TABLE IF NOT EXISTS shade_media_uploads (
media_id TEXT PRIMARY KEY,
owner_pubkey TEXT NOT NULL,
size BIGINT NOT NULL,
read_token_hash TEXT,
chunk BIGINT NOT NULL,
object_key TEXT NOT NULL,
upload_id TEXT NOT NULL,
-- etags[n + 1]: piece n's part; NULL until it lands. Pieces land in any order.
etags TEXT[] NOT NULL DEFAULT '{}',
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL
)
`;
await sql`
CREATE INDEX IF NOT EXISTS shade_media_uploads_owner_idx
ON shade_media_uploads(owner_pubkey)
`;
await sql`
CREATE INDEX IF NOT EXISTS shade_media_uploads_updated_idx
ON shade_media_uploads(updated_at)
`;
await sql`
CREATE TABLE IF NOT EXISTS shade_live_pins (
channel_id TEXT PRIMARY KEY,

View File

@@ -1,6 +1,14 @@
import postgres, { type Sql } from 'postgres';
import { LivePinTakenError, MediaExistsError } from '@shade/media/server';
import type { IndexedMedia, LivePin, LivePinStore, LivePublisherLocator, MediaIndex, MediaRecord } from '@shade/media/server';
import type {
IndexedMedia,
LivePin,
LivePinStore,
LivePublisherLocator,
MediaIndex,
MediaRecord,
PendingObject,
} from '@shade/media/server';
import { ensureMediaServerTables } from './ensure-tables.js';
// "relation already exists, skipping" on every start is not news.
@@ -24,10 +32,40 @@ const toRecord = (r: MediaRow): IndexedMedia => ({
createdAt: Number(r.created_at),
});
/** `etags` is selected as JSON: postgres.js reads a NULL element of a TEXT[] as the string "NULL". */
interface UploadRow {
media_id: string;
owner_pubkey: string;
size: string;
read_token_hash: string | null;
chunk: string;
object_key: string;
upload_id: string;
etags: (string | null)[];
created_at: string;
updated_at: string;
}
const toPending = (r: UploadRow): PendingObject => ({
id: r.media_id,
owner: r.owner_pubkey,
size: Number(r.size),
readTokenHash: r.read_token_hash,
chunk: Number(r.chunk),
key: r.object_key,
uploadId: r.upload_id,
etags: r.etags,
createdAt: Number(r.created_at),
updatedAt: Number(r.updated_at),
});
/**
* The shared record of a media bucket (`ObjectMediaStore`), so any number of
* relay instances serve one library. The primary key on `media_id` is what
* decides racing uploads of one id: exactly one INSERT wins, on any instance.
* Uploads under way are rows of `shade_media_uploads`; a piece's ETag is
* set only where none is, so of two instances landing one piece the first
* is recorded and the second changes nothing.
*/
export class PostgresMediaIndex implements MediaIndex {
private constructor(
@@ -78,16 +116,75 @@ export class PostgresMediaIndex implements MediaIndex {
async usage(owner: string): Promise<number> {
const rows = await this.sql<{ n: string }[]>`
SELECT COALESCE(SUM(size), 0)::text AS n FROM shade_media_objects WHERE owner_pubkey = ${owner}
SELECT (
(SELECT COALESCE(SUM(size), 0) FROM shade_media_objects WHERE owner_pubkey = ${owner}) +
(SELECT COALESCE(SUM(size), 0) FROM shade_media_uploads WHERE owner_pubkey = ${owner})
)::text AS n
`;
return Number(rows[0]!.n);
}
async totalBytes(): Promise<number> {
const rows = await this.sql<{ n: string }[]>`SELECT COALESCE(SUM(size), 0)::text AS n FROM shade_media_objects`;
const rows = await this.sql<{ n: string }[]>`
SELECT (
(SELECT COALESCE(SUM(size), 0) FROM shade_media_objects) +
(SELECT COALESCE(SUM(size), 0) FROM shade_media_uploads)
)::text AS n
`;
return Number(rows[0]!.n);
}
async getPending(id: string): Promise<PendingObject | null> {
const rows = await this.sql<UploadRow[]>`
SELECT media_id, owner_pubkey, size::text, read_token_hash, chunk::text,
object_key, upload_id, array_to_json(etags) AS etags, created_at::text, updated_at::text
FROM shade_media_uploads WHERE media_id = ${id}
`;
return rows.length === 0 ? null : toPending(rows[0]!);
}
async insertPending(p: PendingObject): Promise<PendingObject> {
await this.sql`
INSERT INTO shade_media_uploads
(media_id, owner_pubkey, size, read_token_hash, chunk, object_key, upload_id, etags, created_at, updated_at)
VALUES (${p.id}, ${p.owner}, ${p.size}, ${p.readTokenHash}, ${p.chunk},
${p.key}, ${p.uploadId}, array_fill(NULL::text, ARRAY[${Math.ceil(p.size / p.chunk)}::int]),
${p.createdAt}, ${p.updatedAt})
ON CONFLICT (media_id) DO NOTHING
`;
const won = await this.getPending(p.id);
if (won === null) throw new Error(`upload ${p.id} vanished as it was recorded`);
return won;
}
async landPiece(id: string, n: number, etag: string, at: number): Promise<void> {
// 1-based, and filled with NULLs at insert: an element set in an empty
// array would start the array at that subscript instead.
await this.sql`
UPDATE shade_media_uploads
SET etags[${n + 1}::int] = ${etag}::text, updated_at = ${at}
WHERE media_id = ${id} AND etags[${n + 1}::int] IS NULL
`;
}
async removePending(id: string): Promise<PendingObject | null> {
const rows = await this.sql<UploadRow[]>`
DELETE FROM shade_media_uploads WHERE media_id = ${id}
RETURNING media_id, owner_pubkey, size::text, read_token_hash, chunk::text,
object_key, upload_id, array_to_json(etags) AS etags, created_at::text, updated_at::text
`;
return rows.length === 0 ? null : toPending(rows[0]!);
}
async stalePending(before: number): Promise<PendingObject[]> {
const rows = await this.sql<UploadRow[]>`
SELECT media_id, owner_pubkey, size::text, read_token_hash, chunk::text,
object_key, upload_id, array_to_json(etags) AS etags, created_at::text, updated_at::text
FROM shade_media_uploads WHERE updated_at < ${before}
`;
return rows.map(toPending);
}
async list(owner: string): Promise<MediaRecord[]> {
const rows = await this.sql<MediaRow[]>`
SELECT media_id, owner_pubkey, size::text, read_token_hash, object_key, created_at::text

View File

@@ -12,7 +12,7 @@ import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import postgres, { type Sql } from 'postgres';
import { Hono } from 'hono';
import { createMediaService, LivePinTakenError, MediaExistsError, MemoryMediaStore, S3Bucket } from '@shade/media/server';
import type { IndexedMedia } from '@shade/media/server';
import type { IndexedMedia, PendingObject } from '@shade/media/server';
import { MediaClient, OwnerKey, openGrant, sealMediaBytes, MIN_SEGMENT_SIZE, LivePublisher, LivePublishClient, LiveWatchClient, encodeGrant, parseGrant } from '@shade/media';
import type { LiveGrant, ReceivedFrame } from '@shade/media';
import { websocket } from 'hono/bun';
@@ -36,6 +36,7 @@ describe.skipIf(PG_URL === undefined)('Postgres media index and live pins', () =
beforeAll(async () => {
sql = postgres(PG_URL!);
await sql`DROP TABLE IF EXISTS shade_media_objects`;
await sql`DROP TABLE IF EXISTS shade_media_uploads`;
await sql`DROP TABLE IF EXISTS shade_live_pins`;
await sql`DROP TABLE IF EXISTS shade_live_publishers`;
});
@@ -72,6 +73,54 @@ describe.skipIf(PG_URL === undefined)('Postgres media index and live pins', () =
}
});
test('uploads under way: one per id, each piece recorded once in any order, counted against the owner', async () => {
const chunk = 16 * 1024 * 1024;
const pending = (owner: string, uploadId: string): PendingObject => ({
id: hexId(500),
owner,
size: 50 * 1024 ** 3, // a 50 GiB film, promised
readTokenHash: null,
chunk,
key: `objects/${hexId(500)}/${'11'.repeat(16)}.smf`,
uploadId,
etags: [],
createdAt: 5,
updatedAt: 5,
});
const index = await PostgresMediaIndex.fromClient(sql);
const before = await index.usage('carol');
expect((await index.insertPending(pending('carol', 'up-1'))).uploadId).toBe('up-1');
// A second instance starting the same upload gets the first one's.
expect((await index.insertPending(pending('carol', 'up-2'))).uploadId).toBe('up-1');
expect(await index.usage('carol')).toBe(before + 50 * 1024 ** 3);
const fresh = (await index.getPending(hexId(500)))!;
expect(fresh.etags.length).toBe(3200);
expect(fresh.etags.every((e) => e === null)).toBe(true);
// Piece 2 lands before piece 0, on six connections at once: recorded once, at its own place.
const pools = Array.from({ length: 6 }, () => postgres(PG_URL!, { max: 1 }));
try {
const indexes = await Promise.all(pools.map((p) => PostgresMediaIndex.fromClient(p)));
await Promise.all(indexes.map((ix, i) => ix.landPiece(hexId(500), 2, `"etag-${i}"`, 9)));
} finally {
await Promise.all(pools.map((p) => p.end()));
}
let now = (await index.getPending(hexId(500)))!;
expect(now.etags.slice(0, 4).map((e) => e !== null)).toEqual([false, false, true, false]);
const first = now.etags[2];
await index.landPiece(hexId(500), 2, '"later"', 10);
await index.landPiece(hexId(500), 0, '"e0"', 11);
now = (await index.getPending(hexId(500)))!;
expect(now.etags[2]).toBe(first!);
expect(now.etags.slice(0, 3)).toEqual(['"e0"', null, first!]);
expect(now.updatedAt).toBe(11);
expect((await index.stalePending(11)).map((p) => p.id)).toEqual([]);
expect((await index.stalePending(12)).map((p) => p.id)).toEqual([hexId(500)]);
expect((await index.removePending(hexId(500)))!.uploadId).toBe('up-1');
expect(await index.getPending(hexId(500))).toBeNull();
expect(await index.usage('carol')).toBe(before);
});
test('pins: refreshed by their own key, refused to another, even when two relays race to create one', async () => {
const pins = await PostgresLivePinStore.fromClient(sql, 1000);
const pin = { channelId: 'ch1', signingKey: 'K1', readTokenHash: 'h', pinnedAt: 100, lastSeen: 100 };