Files
Shade/packages/shade-media/tests/object-store.test.ts

195 lines
11 KiB
TypeScript
Raw Normal View History

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
/**
* 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';
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
import { MediaClient, OwnerKey, openGrant, sealMediaBytes, MIN_SEGMENT_SIZE, DEFAULT_CHUNK_BYTES } from '../src/index.js';
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
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 () => {
feat(media): `shade live record` — a broadcast to files, or to a sealed film with its own link `live record <link> [-o base] [--put --server URL]` writes what a channel carries until the channel ends or Ctrl-C: - text goes to base.txt; - video and sound go to base.webm or base.mp4: the init, then every chunk in the order sent. A chunk that arrives late is left out and counted. A new init continues in base-2.…; - pictures go to base-images/. ffmpeg then rewrites each recording with -c copy, which adds an index for seeking and starts the clock at 0:00. `--put` seals and uploads the recording under the channel's name (several files become an album). LiveRecorder is exported from @shade/media/node. `live video` now sends a sticky meta frame like text and picture channels do. The browser and Android players ignore it. Verified against a real relay: - A 30 s VP8/Opus broadcast was recorded and is 29–32 s long, starting at 0. - It was uploaded as "Kveldssending.webm" and plays in Chromium, with a seek to 22 s (frame 14). - Live playback with the meta frame still plays, with 2.4 s latency. Tests: - object-store's memory test now runs in its own process. RSS is process-wide, and other test files in the same `bun test` made it flaky (192 MiB). It now compares memory held after a collection at 128 MiB and 512 MiB, ~85 vs ~103 MiB, instead of using a magic number. - The sweep test has its own prefix. - tests/live-record.test.ts (4). - media 122 green, 3 runs in a row. All 27 packages type-check. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:01:55 +02:00
// 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);
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
}, 180_000);
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
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;
feat(media): `shade live record` — a broadcast to files, or to a sealed film with its own link `live record <link> [-o base] [--put --server URL]` writes what a channel carries until the channel ends or Ctrl-C: - text goes to base.txt; - video and sound go to base.webm or base.mp4: the init, then every chunk in the order sent. A chunk that arrives late is left out and counted. A new init continues in base-2.…; - pictures go to base-images/. ffmpeg then rewrites each recording with -c copy, which adds an index for seeking and starts the clock at 0:00. `--put` seals and uploads the recording under the channel's name (several files become an album). LiveRecorder is exported from @shade/media/node. `live video` now sends a sticky meta frame like text and picture channels do. The browser and Android players ignore it. Verified against a real relay: - A 30 s VP8/Opus broadcast was recorded and is 29–32 s long, starting at 0. - It was uploaded as "Kveldssending.webm" and plays in Chromium, with a seek to 22 s (frame 14). - Live playback with the meta frame still plays, with 2.4 s latency. Tests: - object-store's memory test now runs in its own process. RSS is process-wide, and other test files in the same `bun test` made it flaky (192 MiB). It now compares memory held after a collection at 128 MiB and 512 MiB, ~85 vs ~103 MiB, instead of using a magic number. - The sweep test has its own prefix. - tests/live-record.test.ts (4). - media 122 green, 3 runs in a row. All 27 packages type-check. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:01:55 +02:00
// 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 });
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
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);
feat(media): `shade live record` — a broadcast to files, or to a sealed film with its own link `live record <link> [-o base] [--put --server URL]` writes what a channel carries until the channel ends or Ctrl-C: - text goes to base.txt; - video and sound go to base.webm or base.mp4: the init, then every chunk in the order sent. A chunk that arrives late is left out and counted. A new init continues in base-2.…; - pictures go to base-images/. ffmpeg then rewrites each recording with -c copy, which adds an index for seeking and starts the clock at 0:00. `--put` seals and uploads the recording under the channel's name (several files become an album). LiveRecorder is exported from @shade/media/node. `live video` now sends a sticky meta frame like text and picture channels do. The browser and Android players ignore it. Verified against a real relay: - A 30 s VP8/Opus broadcast was recorded and is 29–32 s long, starting at 0. - It was uploaded as "Kveldssending.webm" and plays in Chromium, with a seek to 22 s (frame 14). - Live playback with the meta frame still plays, with 2.4 s latency. Tests: - object-store's memory test now runs in its own process. RSS is process-wide, and other test files in the same `bun test` made it flaky (192 MiB). It now compares memory held after a collection at 128 MiB and 512 MiB, ~85 vs ~103 MiB, instead of using a magic number. - The sweep test has its own prefix. - tests/live-record.test.ts (4). - media 122 green, 3 runs in a row. All 27 packages type-check. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:01:55 +02:00
expect((await s3.listMultipart(own)).filter((u) => u.key.includes(id)).length).toBe(1);
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
// 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();
feat(media): `shade live record` — a broadcast to files, or to a sealed film with its own link `live record <link> [-o base] [--put --server URL]` writes what a channel carries until the channel ends or Ctrl-C: - text goes to base.txt; - video and sound go to base.webm or base.mp4: the init, then every chunk in the order sent. A chunk that arrives late is left out and counted. A new init continues in base-2.…; - pictures go to base-images/. ffmpeg then rewrites each recording with -c copy, which adds an index for seeking and starts the clock at 0:00. `--put` seals and uploads the recording under the channel's name (several files become an album). LiveRecorder is exported from @shade/media/node. `live video` now sends a sticky meta frame like text and picture channels do. The browser and Android players ignore it. Verified against a real relay: - A 30 s VP8/Opus broadcast was recorded and is 29–32 s long, starting at 0. - It was uploaded as "Kveldssending.webm" and plays in Chromium, with a seek to 22 s (frame 14). - Live playback with the meta frame still plays, with 2.4 s latency. Tests: - object-store's memory test now runs in its own process. RSS is process-wide, and other test files in the same `bun test` made it flaky (192 MiB). It now compares memory held after a collection at 128 MiB and 512 MiB, ~85 vs ~103 MiB, instead of using a magic number. - The sweep test has its own prefix. - tests/live-record.test.ts (4). - media 122 green, 3 runs in a row. All 27 packages type-check. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:01:55 +02:00
expect((await s3.listMultipart(own)).filter((u) => u.key.includes(id))).toEqual([]);
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
}, 60_000);
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
});