Files
Shade/packages/shade-media/tests/object-store.test.ts
Sterister bd4882e1b8 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>
2026-10-18 23:39:25 +02:00

193 lines
11 KiB
TypeScript

/**
* ObjectMediaStore against a real S3 API. Skipped unless SHADE_TEST_S3_URL
* names a bucket that may be emptied, e.g. with SeaweedFS:
*
* docker run -d --rm -p 127.0.0.1:58333:8333 chrislusf/seaweedfs server -s3 -dir=/data
* SHADE_TEST_S3_URL=http://key:secret@127.0.0.1:58333/shade-media-test bun test object-store
*/
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, DEFAULT_CHUNK_BYTES } from '../src/index.js';
import { toHex } from '../src/bytes.js';
const URL_ = process.env.SHADE_TEST_S3_URL;
function pattern(n: number): Uint8Array {
const out = new Uint8Array(n);
for (let i = 0; i < n; i++) out[i] = (i * 31 + (i >> 8)) & 0xff;
return out;
}
function serve(app: Hono) {
const server = Bun.serve({ port: 0, fetch: (req) => app.fetch(req), maxRequestBodySize: 1024 ** 3 });
return { server, base: `http://localhost:${server.port}` };
}
describe.skipIf(URL_ === undefined)('ObjectMediaStore (S3)', () => {
const { bucket: s3, prefix: basePrefix } = URL_ !== undefined ? S3Bucket.fromUrl(URL_) : ({} as ReturnType<typeof S3Bucket.fromUrl>);
// A fresh prefix per run: runs never see each other's objects.
const prefix = `${basePrefix}run-${Date.now().toString(36)}/`;
const keys = async () => (await s3.list(prefix)).objects.map((o) => o.key);
beforeAll(async () => {
// SeaweedFS and MinIO create a bucket on PUT; real S3 answers 409 for one that exists.
const u = new URL(URL_!);
await fetch(`${u.protocol}//${u.host}${u.pathname.split('/').slice(0, 2).join('/')}`, { method: 'PUT' }).catch(() => {});
});
test('two relay instances over one bucket and one index: upload on A, play on B, race decided once', async () => {
const index = new MemoryMediaIndex();
const a = serve(new Hono().route('/', createMediaRoutes(new ObjectMediaStore(s3, index, { prefix, partSize: 5 * 1024 * 1024 }))));
const b = serve(new Hono().route('/', createMediaRoutes(new ObjectMediaStore(s3, index, { prefix }))));
try {
const owner = OwnerKey.generate();
// Bigger than two parts, not a multiple of one: the multipart path and its last short part.
const plain = pattern(12 * 1024 * 1024 + 4321);
const grant = await new MediaClient(a.base, owner).uploadBytes(plain, { meta: { name: 'Film.mkv' } });
const onB = await openGrant(grant, { url: grant.url!.replace(a.base, b.base) });
expect(onB.meta.name).toBe('Film.mkv');
expect(await onB.read(7 * 1024 * 1024 - 11, 3 * 1024 * 1024)).toEqual(plain.subarray(7 * 1024 * 1024 - 11, 10 * 1024 * 1024 - 11));
expect(await onB.read(0, plain.length)).toEqual(plain);
const res = await fetch(grant.url!.replace(a.base, b.base), { headers: { Range: 'bytes=100-1048675', 'x-shade-read': '' } });
expect(res.status).toBe(404); // the read token still guards the bytes
// The same sealed file sent to both instances at once: one wins, one gets 409, one object stays.
const { bytes, result } = await sealMediaBytes(pattern(3 * MIN_SEGMENT_SIZE));
const settled = await Promise.allSettled([
new MediaClient(a.base, owner).putSealed(result, bytes),
new MediaClient(b.base, owner).putSealed(result, bytes),
]);
expect(settled.filter((s) => s.status === 'fulfilled').length).toBe(1);
expect(String((settled.find((s) => s.status === 'rejected') as PromiseRejectedResult).reason)).toMatch(/409/);
const id = toHex(result.mediaId);
expect((await keys()).filter((k) => k.includes(id)).length).toBe(1);
expect((await new MediaClient(b.base, owner).list()).items.length).toBe(2);
expect(await new MediaClient(b.base, owner).delete(grant.mediaId)).toBe(true);
expect(await new MediaClient(a.base, owner).delete(result.mediaId)).toBe(true);
expect(await keys()).toEqual([]);
} finally {
a.server.stop(true);
b.server.stop(true);
}
}, 60_000);
test('a refused upload leaves nothing behind; sweep reclaims orphans past the grace period only', async () => {
let clock = Date.now();
const index = new MemoryMediaIndex();
const store = new ObjectMediaStore(s3, index, { prefix, now: () => clock, sweepGraceMs: 60_000 });
const srv = serve(new Hono().route('/', createMediaRoutes(store)));
try {
const { bytes, result } = await sealMediaBytes(pattern(2 * MIN_SEGMENT_SIZE));
const damaged = bytes.slice();
damaged[damaged.length - 1]! ^= 0xff; // the footer no longer parses
await expect(new MediaClient(srv.base, OwnerKey.generate()).putSealed(result, damaged)).rejects.toThrow(/422/);
expect(await keys()).toEqual([]);
// An orphan: bytes that reached the bucket, a record that never did (a crash between the two).
const orphan = `${prefix}objects/${'ab'.repeat(16)}/${'cd'.repeat(16)}.smf`;
await s3.put(orphan, new Uint8Array(100));
const kept = await new MediaClient(srv.base, OwnerKey.generate()).putSealed(result, bytes);
const foreign = `${prefix}objects/notes.txt`;
await s3.put(foreign, new TextEncoder().encode('not ours'));
// And an upload that died mid-way: parts in the bucket, never completed.
const dead = await s3.createMultipart(`${prefix}objects/${'ef'.repeat(16)}/${'01'.repeat(16)}.smf`);
await s3.uploadPart(`${prefix}objects/${'ef'.repeat(16)}/${'01'.repeat(16)}.smf`, dead, 1, new Uint8Array(10));
expect(await store.sweep()).toEqual({ objects: 0, uploads: 0 }); // everything is younger than the grace period
clock += 120_000;
expect(await store.sweep()).toEqual({ objects: 1, uploads: 1 });
expect(await s3.listMultipart(prefix)).toEqual([]);
expect((await keys()).sort()).toEqual([foreign, (await index.get(toHex(kept.mediaId)))!.key].sort());
expect(await (await openGrant(kept)).read(0, 10)).toEqual(pattern(10));
await s3.delete(foreign);
await store.delete(toHex(kept.mediaId));
} finally {
srv.server.stop(true);
}
}, 60_000);
test('a film streams through: memory is bounded by the parts in flight, not the film', async () => {
const partSize = 8 * 1024 * 1024;
const store = new ObjectMediaStore(s3, new MemoryMediaIndex(), { prefix, partSize });
const chunk = new Uint8Array(1024 * 1024);
const total = 512 * 1024 * 1024;
Bun.gc(true);
const before = process.memoryUsage().rss;
let peak = before;
const id = toHex(new Uint8Array(16).fill(0x5a));
const up = await store.begin(id);
for (let off = 0; off < total; off += chunk.length) {
chunk.fill((off / chunk.length) & 0xff);
await up.write(chunk);
peak = Math.max(peak, process.memoryUsage().rss);
}
await up.commit({ id, owner: 'o', size: total, readTokenHash: null, createdAt: Date.now() });
// Three parts (one filling, two uploading) and the HTTP machinery — not 512 MiB.
const grewMiB = (peak - before) / 1024 / 1024;
console.log(`object upload of 512 MiB: RSS grew ${grewMiB.toFixed(0)} MiB`);
expect(grewMiB).toBeLessThan(120);
const body = await store.body(id, 300 * 1024 * 1024 - 1, 300 * 1024 * 1024 + 1);
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);
});