/** * 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); // 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 () => { // Each size in a process of its own: RSS is process-wide, and other test // files in this one leave garbage the collector has not returned yet. const grew = async (mib: number) => { const proc = Bun.spawn(['bun', `${import.meta.dir}/fixtures/object-upload-rss.ts`, URL_!, prefix, String(mib)], { stdout: 'pipe', stderr: 'inherit' }); const out = await new Response(proc.stdout).text(); expect(await proc.exited).toBe(0); const r = JSON.parse(out) as { retainedMiB: number; peakMiB: number; readBack: boolean }; expect(r.readBack).toBe(true); return r; }; const small = await grew(128); const large = await grew(512); const f = (n: number) => n.toFixed(0); console.log( `object upload: RSS held ${f(small.retainedMiB)} MiB for 128 MiB, ${f(large.retainedMiB)} MiB for 512 MiB ` + `(peaks before collection ${f(small.peakMiB)} / ${f(large.peakMiB)})`, ); // Three parts (one filling, two uploading) and the HTTP machinery: four // times the film is not four times the memory, nor anywhere near the film. expect(large.retainedMiB).toBeLessThan(small.retainedMiB + 48); expect(large.retainedMiB).toBeLessThan(128); }, 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; // A prefix of its own: with a grace period this short, a sweep over the // shared one would take other tests' objects for orphans. const own = `${prefix}sweep/`; const a = new ObjectMediaStore(s3, index, { prefix: own, sweepGraceMs: grace }); const b = new ObjectMediaStore(s3, index, { prefix: own, 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(own)).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(own)).filter((u) => u.key.includes(id))).toEqual([]); }, 60_000); });