fix(media,server): films over 128 MiB were refused; docs/media.md

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) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 21:15:13 +02:00
parent df3ca685c5
commit e9ae5bd28e
7 changed files with 565 additions and 2 deletions

View File

@@ -104,7 +104,7 @@ const err = (s: string) => process.stderr.write(`${s}\n`);
async function mediaServe(flags: Flags): Promise<number> {
const { websocket } = await import('hono/bun');
const { createMediaService, parseOwners } = await import('./server.js');
const { createMediaService, parseOwners, mediaMaxRequestBody } = await import('./server.js');
const dir = str(flags, 'dir') ?? process.env.SHADE_MEDIA_DIR ?? './shade-media-data';
const port = Number(str(flags, 'port') ?? process.env.PORT ?? 3910);
// Closed by default: this machine's own owner key, plus any listed. `--open`
@@ -120,6 +120,8 @@ async function mediaServe(flags: Flags): 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.
maxRequestBodySize: mediaMaxRequestBody(),
});
err(`shade media: serving on http://localhost:${server.port} (data in ${dir})`);
err(owners === 'any' ? 'open relay: any key may upload and publish' : `owners: ${owners.join(', ')}`);

View File

@@ -6,5 +6,5 @@ export { createLiveRelay, FileLivePinStore, MemoryLivePinStore } from './server/
export type { LiveRelay, LiveRelayOptions, LivePin, LivePinStore } from './server/live-relay.js';
export { createWatchRoutes } from './server/watch-routes.js';
export type { WatchRoutesOptions } from './server/watch-routes.js';
export { createMediaService, parseOwners } from './server/service.js';
export { createMediaService, parseOwners, mediaMaxRequestBody, MEDIA_BODY_ROUTE } from './server/service.js';
export type { MediaService, MediaServiceOptions } from './server/service.js';

View File

@@ -34,6 +34,20 @@ export interface MediaService {
stop(): void;
}
/**
* 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`).
*/
export function mediaMaxRequestBody(opts: { media?: { maxObjectBytes?: number } } = {}): number {
return (opts.media?.maxObjectBytes ?? 64 * 1024 ** 3) + 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 app = new Hono();

View File

@@ -1,4 +1,6 @@
import { Hono } from 'hono';
import { bodyLimit } from 'hono/body-limit';
import { mediaMaxRequestBody } from '@shade/media/server';
import { SubtleCryptoProvider } from '@shade/crypto-web';
import {
createInboxRoutes,
@@ -233,6 +235,18 @@ if (disableRateLimit) {
// Compose the full app: metrics middleware + health + metrics + prekey routes
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.
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.route('/', createHealthRoutes(store, VERSION));
app.route('/', createMetricsRoutes());
app.route('/', createOpenApiRoutes());
@@ -379,6 +393,7 @@ const server = Bun.serve({
port,
fetch: (req, srv) => app.fetch(req, srv),
websocket: bridgeRoutes.websocket as any,
...(mediaService !== null ? { maxRequestBodySize: mediaMaxRequestBody() } : {}),
});
// ─── Graceful shutdown ───────────────────────────────────────