/** * 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> { 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 = {}; 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> = {}; 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 }); }