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

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