/** * 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); // 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); });