From e9ae5bd28e4c8da055d26a4c802e65332823b183 Mon Sep 17 00:00:00 2001 From: Sterister Date: Sun, 18 Oct 2026 21:15:13 +0200 Subject: [PATCH] fix(media,server): films over 128 MiB were refused; docs/media.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bun.serve refuses request bodies over 128 MiB by default, so every film larger than that got a 413 from both `shade media serve` and the container. The cap is now raised to the media object limit only when media is mounted, and every other route gets an explicit 128 MiB bodyLimit — several read the whole body before checking its size, so Bun's default was their only guard. Verified on the standalone process: 300 MiB sealed film round trip identical; a 200 MiB POST to a prekey route still 413. docs/media.md: formats (SMF1, SLF1, grants) as the cross-language contract, key schedule, what the relay learns, design notes, limits. bench/media.ts: throughput, seek latency, live fan-out → media.chart.json. Co-Authored-By: Claude Opus 5.5 (1M context) --- bench/media-relay.ts | 7 + bench/media.ts | 236 +++++++++++++++++ docs/media.md | 289 +++++++++++++++++++++ packages/shade-media/src/cli.ts | 4 +- packages/shade-media/src/server.ts | 2 +- packages/shade-media/src/server/service.ts | 14 + packages/shade-server/src/standalone.ts | 15 ++ 7 files changed, 565 insertions(+), 2 deletions(-) create mode 100644 bench/media-relay.ts create mode 100644 bench/media.ts create mode 100644 docs/media.md diff --git a/bench/media-relay.ts b/bench/media-relay.ts new file mode 100644 index 0000000..cde7e20 --- /dev/null +++ b/bench/media-relay.ts @@ -0,0 +1,7 @@ +/** A live relay in its own process for bench/media.ts; prints its port. */ +import { websocket } from 'hono/bun'; +import { createLiveRelay, MemoryLivePinStore } from '../packages/shade-media/src/server.js'; + +const relay = createLiveRelay({ pins: new MemoryLivePinStore(), viewerHighWater: 32 * 1024 * 1024 }); +const server = Bun.serve({ port: 0, fetch: (req, srv) => relay.app.fetch(req, { server: srv }), websocket, idleTimeout: 0 }); +console.log(server.port); diff --git a/bench/media.ts b/bench/media.ts new file mode 100644 index 0000000..e0ac923 --- /dev/null +++ b/bench/media.ts @@ -0,0 +1,236 @@ +/** + * @shade/media benchmarks — what streaming under Shade costs. + * + * Run: bun bench/media.ts [--big-mib 1024] [--viewers 1,10,50,200] + * + * 1. Seal and read throughput, sealed file on disk (1 MiB segments). + * 2. The same read over HTTP Range from the real media routes. + * 3. Seek: time to the first decrypted byte at a random offset over HTTP. + * 4. Live fan-out: one publisher, N viewers, relay in its own process — + * delivered fraction and end-to-end latency (publish → decrypted). + * + * Writes bench/media-results.json (raw numbers) and bench/media.chart.json + * (charts for the log post, `scaffold-agent chart block`). + */ +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { createWriteStream } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Hono } from 'hono'; +import { websocket } from 'hono/bun'; +import { sealFile, FileSource } from '../packages/shade-media/src/node.js'; +import { MediaReader } from '../packages/shade-media/src/sealed.js'; +import { createMediaRoutes, FileMediaStore, mediaMaxRequestBody } from '../packages/shade-media/src/server.js'; +import { MediaClient, openGrant } from '../packages/shade-media/src/client.js'; +import { OwnerKey } from '../packages/shade-media/src/owner.js'; +import { LivePublisher } from '../packages/shade-media/src/live/channel.js'; +import { LivePublishClient, LiveWatchClient } from '../packages/shade-media/src/live/client.js'; + +const args = process.argv.slice(2); +const flag = (k: string, d: string) => { + const i = args.indexOf(`--${k}`); + return i >= 0 ? args[i + 1]! : d; +}; +const BIG_MIB = Number(flag('big-mib', '1024')); +const VIEWERS = flag('viewers', '1,10,50,200').split(',').map(Number); +const MiB = 1024 * 1024; +const now = () => performance.now(); +const pct = (xs: number[], p: number) => { + const s = [...xs].sort((a, b) => a - b); + return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]!; +}; +const round = (x: number, d = 1) => Math.round(x * 10 ** d) / 10 ** d; + +async function writeRandomFile(path: string, mib: number): Promise { + // Random bytes (incompressible, like video). One 1 MiB block reused with a + // counter stamped in, so generation is not the thing being measured. + const block = new Uint8Array(MiB); + globalThis.crypto.getRandomValues(block.subarray(0, 65536)); + for (let i = 65536; i < MiB; i += 65536) block.copyWithin(i, 0, 65536); + const ws = createWriteStream(path); + for (let i = 0; i < mib; i++) { + new DataView(block.buffer).setUint32(0, i); + if (!ws.write(Buffer.from(block))) await new Promise((r) => ws.once('drain', () => r())); + } + await new Promise((r) => ws.end(() => r())); +} + +async function main() { + const dir = await mkdtemp(join(tmpdir(), 'shade-media-bench-')); + const results: Record = { at: new Date().toISOString(), bun: Bun.version, bigMiB: BIG_MIB }; + try { + // ─── 1. Seal + local read ────────────────────────────────── + const plain = join(dir, 'film.bin'); + const sealedPath = join(dir, 'film.smf'); + await writeRandomFile(plain, BIG_MIB); + let t = now(); + const res = await sealFile(plain, sealedPath, { meta: { mime: 'video/mp4', name: 'film.bin' } }); + const sealMs = now() - t; + const keys = { mediaId: res.mediaId, mediaKey: res.mediaKey, rootDigest: res.rootDigest }; + t = now(); + const reader = await MediaReader.open(new FileSource(sealedPath), keys, { cacheSegments: 0, maxSegmentsPerFetch: 8 }); + let n = 0; + for await (const c of reader.stream()) n += c.length; + const readMs = now() - t; + if (n !== BIG_MIB * MiB) throw new Error(`read ${n} bytes`); + const overhead = (res.sealedSize - res.plaintextSize) / res.plaintextSize; + results.seal = { mibPerSec: round((BIG_MIB / sealMs) * 1000), ms: round(sealMs), overheadPct: round(overhead * 100, 4) }; + results.readDisk = { mibPerSec: round((BIG_MIB / readMs) * 1000), ms: round(readMs) }; + console.log(`seal ${BIG_MIB} MiB: ${round((BIG_MIB / sealMs) * 1000)} MiB/s size overhead ${round(overhead * 100, 4)} %`); + console.log(`read ${BIG_MIB} MiB (disk): ${round((BIG_MIB / readMs) * 1000)} MiB/s`); + + // ─── 2 + 3. Over HTTP ────────────────────────────────────── + const app = new Hono(); + app.route('/', createMediaRoutes(new FileMediaStore(join(dir, 'store')))); + const server = Bun.serve({ port: 0, fetch: (req, srv) => app.fetch(req, { server: srv }), websocket, idleTimeout: 0, maxRequestBodySize: mediaMaxRequestBody() }); + const base = `http://localhost:${server.port}`; + try { + const client = new MediaClient(base, OwnerKey.generate()); + t = now(); + const grant = await client.putSealed(res, Bun.file(sealedPath)); + const uploadMs = now() - t; + t = now(); + const hr = await openGrant(grant, { cacheSegments: 0, maxSegmentsPerFetch: 8 }); + n = 0; + for await (const c of hr.stream()) n += c.length; + const httpMs = now() - t; + results.upload = { mibPerSec: round((BIG_MIB / uploadMs) * 1000) }; + results.readHttp = { mibPerSec: round((BIG_MIB / httpMs) * 1000), ms: round(httpMs) }; + console.log(`upload (localhost): ${round((BIG_MIB / uploadMs) * 1000)} MiB/s read over HTTP Range: ${round((BIG_MIB / httpMs) * 1000)} MiB/s`); + + // Seek: a fresh reader per probe would measure open(); one reader with + // no cache measures what a seek in a playing film costs. + const opened: number[] = []; + for (let i = 0; i < 10; i++) { + t = now(); + await openGrant(grant); + opened.push(now() - t); + } + const seeks: number[] = []; + const sr = await openGrant(grant, { cacheSegments: 0 }); + for (let i = 0; i < 100; i++) { + const off = Math.floor(Math.random() * (BIG_MIB * MiB - 65536)); + t = now(); + await sr.read(off, 65536); + seeks.push(now() - t); + } + results.open = { p50: round(pct(opened, 50), 2), p95: round(pct(opened, 95), 2) }; + results.seek = { p50: round(pct(seeks, 50), 2), p95: round(pct(seeks, 95), 2), max: round(Math.max(...seeks), 2) }; + console.log(`open (footer+trailer): p50 ${round(pct(opened, 50), 2)} ms seek→first byte: p50 ${round(pct(seeks, 50), 2)} ms, p95 ${round(pct(seeks, 95), 2)} ms`); + } finally { + server.stop(true); + } + + // ─── 4. Live fan-out ─────────────────────────────────────── + const relayProc = Bun.spawn(['bun', join(import.meta.dir, 'media-relay.ts')], { stdout: 'pipe', stderr: 'inherit' }); + const portLine = await new Response(relayProc.stdout).body!.getReader().read(); + const relayBase = `http://localhost:${new TextDecoder().decode(portLine.value).trim()}`; + const live: Array<{ viewers: number; delivered: number; p50: number; p95: number; max: number }> = []; + try { + for (const v of VIEWERS) { + const fps = 10; + const frameBytes = 32 * 1024; // ≈ 2.6 Mbit/s, a 720p stream + const seconds = 6; + const pub = new LivePublisher(); + const pc = new LivePublishClient({ relay: relayBase, publisher: pub, readToken: new Uint8Array(32).fill(1) }); + await pc.whenReady(); + const grant = pc.grant('now'); + const lat: number[] = []; + let got = 0; + const viewers: LiveWatchClient[] = []; + let ready = 0; + for (let i = 0; i < v; i++) { + viewers.push( + new LiveWatchClient(grant, { + onState: (s) => { + if (s === 'live') ready++; + }, + onFrame: (f) => { + got++; + lat.push(Date.now() - f.timestamp); + }, + }), + ); + } + while (ready < v) await Bun.sleep(20); + const payload = new Uint8Array(frameBytes); + globalThis.crypto.getRandomValues(payload.subarray(0, 65536 > frameBytes ? frameBytes : 65536)); + const total = fps * seconds; + const start = Date.now(); + for (let i = 0; i < total; i++) { + await pc.send({ type: 'chunk', bytes: payload }, { keyframe: i % fps === 0 }); + const due = start + ((i + 1) * 1000) / fps; + const wait = due - Date.now(); + if (wait > 0) await Bun.sleep(wait); + } + await Bun.sleep(1500); + const delivered = got / (total * v); + const row = { viewers: v, delivered: round(delivered * 100, 2), p50: pct(lat, 50), p95: pct(lat, 95), max: Math.max(...lat) }; + live.push(row); + console.log(`live ${v} viewer(s): delivered ${row.delivered} %, latency p50 ${row.p50} ms, p95 ${row.p95} ms, max ${row.max} ms`); + for (const w of viewers) w.close(); + pc.close(); + await Bun.sleep(300); + } + } finally { + relayProc.kill(); + } + results.live = live; + + await writeFile(join(import.meta.dir, 'media-results.json'), `${JSON.stringify(results, null, 2)}\n`); + const r = results as any; + const charts = [ + { + type: 'bar', + title: 'Sealed media throughput (MiB/s)', + subtitle: `${BIG_MIB} MiB of incompressible data, 1 MiB segments, one core`, + y: { label: 'MiB/s', min: 0 }, + note: `Bun ${Bun.version}; HTTP is localhost through the real media routes; size overhead ${r.seal.overheadPct} %`, + source: { path: 'media-results.json' }, + series: [ + { + name: 'MiB/s', + data: [ + ['seal (disk → disk)', r.seal.mibPerSec], + ['read + verify (disk)', r.readDisk.mibPerSec], + ['upload (HTTP PUT)', r.upload.mibPerSec], + ['read + verify (HTTP Range)', r.readHttp.mibPerSec], + ], + }, + ], + }, + { + type: 'bar', + title: 'Seeking in a sealed film over HTTP (ms)', + subtitle: 'open = footer + trailer + root check; seek = first 64 KiB at a random offset, no cache', + y: { label: 'ms', min: 0 }, + note: 'n = 10 opens, 100 seeks; localhost', + source: { path: 'media-results.json' }, + series: [ + { name: 'p50', data: [['open', r.open.p50], ['seek', r.seek.p50]] }, + { name: 'p95', data: [['open', r.open.p95], ['seek', r.seek.p95]] }, + ], + }, + { + type: 'line', + title: 'Live fan-out: latency publish → decrypted, by viewers', + subtitle: '10 fps × 32 KiB frames (≈ 2.6 Mbit/s) for 6 s; relay in its own process, all viewers in one', + x: { label: 'viewers' }, + y: { label: 'ms', min: 0 }, + note: `delivered: ${live.map((l) => `${l.viewers} → ${l.delivered} %`).join(', ')}. Every viewer verifies every signature and decrypts every frame, in one process, so the curve is mostly the viewers' CPU, not the relay's.`, + source: { path: 'media-results.json' }, + series: [ + { name: 'p50', data: live.map((l) => [l.viewers, l.p50]) }, + { name: 'p95', data: live.map((l) => [l.viewers, l.p95]) }, + ], + }, + ]; + await writeFile(join(import.meta.dir, 'media.chart.json'), `${JSON.stringify(charts, null, 2)}\n`); + console.log('wrote bench/media-results.json and bench/media.chart.json'); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +await main(); +process.exit(0); diff --git a/docs/media.md b/docs/media.md new file mode 100644 index 0000000..76769c0 --- /dev/null +++ b/docs/media.md @@ -0,0 +1,289 @@ +# `@shade/media` — streaming under Shade + +V4.15. Films, videos, songs, images, and live streams of logs, text, video and +audio, all end-to-end encrypted. Whoever stores or relays the bytes cannot read +them, and whoever holds a key cannot forge them for anyone else. + +There are two shapes, because "a film" and "a log" are different problems: + +| | Sealed media (SMF1) | Live channel (SLF1) | +|---|---|---| +| What | a file that exists in full: film, episode, photo, song, document | a stream that is still being made: `tail -f`, a camera, a broadcast | +| Read how | random access over HTTP Range, so you can seek | in order over a WebSocket, joining late from a backlog | +| Stored where | any dumb store: the relay, nginx, S3, a USB disk | the relay holds minutes of ciphertext for late joiners, then lets it go | +| Keys | one random key per file | Sender Keys: a hash chain per epoch, every frame signed | +| Plays in | `