Files
Shade/packages/shade-media/tests/object-store.test.ts
Sterister aaec92429d feat(media): one library for several relays — films in S3, records and live pins in Postgres
FileMediaStore ties a library to one disk on one machine. SHADE_MEDIA_S3_URL
+ SHADE_MEDIA_PG_URL (or `media serve --s3 --pg`) put sealed bytes in any
S3 bucket and the records every instance must agree on in Postgres.

- ObjectMediaStore: each upload streams as multipart to its own object
  key; the commit is an INSERT whose primary key admits one record per id,
  so racing uploads on any instances are decided once and the loser
  deletes its object. Delete drops the record first. sweep() reclaims
  unreferenced objects and dead multipart uploads past a 24 h grace.
- S3Bucket: Shade's own SigV4 client. Bun 1.3.5's S3Client buffers a
  whole upload (512 MiB in, 543 MiB RSS), end(error) does not abort, and
  slice(0, n).stream() returned the whole object. Here: at most three parts
  in memory (512 MiB through, 11 MiB RSS), payload-hashed signatures,
  AbortMultipartUpload, ranged reads checked for length.
- PostgresMediaIndex, PostgresLivePinStore, createSharedMediaBackend in
  @shade/storage-postgres. LivePinStore.put now refuses a key change
  (LivePinTakenError) in every store, atomically in Postgres.
- The container logs a backend it cannot use and runs on without media.

Verified: SigV4 reproduces AWS's published example signature; SeaweedFS
with signature checking accepts it and refuses a wrong secret (403);
Postgres 16: racing inserts over 8 pools (1 of 24 wins), racing pins,
BIGINT sizes; two relays over one backend; CLI relays behind a
round-robin proxy: upload, bit-identical download, Chromium playback
seeked to 24 s with ranges served by both; the bucket holds no
plaintext, name or MP4 marker. Suites: media 87, storage-postgres 18,
server 55, cli 15, all green.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:28:58 +02:00

138 lines
7.3 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 } 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);
});