Files
Shade/packages/shade-storage-postgres/tests/postgres-media.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

272 lines
13 KiB
TypeScript

/**
* Shared media backend: the Postgres index and pins, and two relays over one
* bucket. Needs PostgreSQL (SHADE_TEST_PG_URL); the relay test also an S3
* API (SHADE_TEST_S3_URL, a bucket that may be written to):
*
* docker run -d --rm -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=test postgres:16-alpine
* docker run -d --rm -p 127.0.0.1:58333:8333 chrislusf/seaweedfs server -s3 -dir=/data
* SHADE_TEST_PG_URL=postgres://postgres:test@127.0.0.1:55432/postgres \
* SHADE_TEST_S3_URL=http://key:secret@127.0.0.1:58333/shade-media-test bun test postgres-media
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import postgres, { type Sql } from 'postgres';
import { Hono } from 'hono';
import { createMediaService, LivePinTakenError, MediaExistsError, MemoryMediaStore, S3Bucket } from '@shade/media/server';
import type { IndexedMedia, PendingObject } from '@shade/media/server';
import { MediaClient, OwnerKey, openGrant, sealMediaBytes, MIN_SEGMENT_SIZE, LivePublisher, LivePublishClient, LiveWatchClient, encodeGrant, parseGrant } from '@shade/media';
import type { LiveGrant, ReceivedFrame } from '@shade/media';
import { websocket } from 'hono/bun';
import { createSharedMediaBackend, PostgresLivePinStore, PostgresLivePublisherLocator, PostgresMediaIndex } from '../src/index.js';
const PG_URL = process.env.SHADE_TEST_PG_URL;
const S3_URL = process.env.SHADE_TEST_S3_URL;
const rec = (id: string, owner: string, size: number, createdAt = 1): IndexedMedia => ({
id,
owner,
size,
readTokenHash: null,
key: `objects/${id}/${'00'.repeat(16)}.smf`,
createdAt,
});
const hexId = (n: number) => n.toString(16).padStart(32, '0');
describe.skipIf(PG_URL === undefined)('Postgres media index and live pins', () => {
let sql: Sql;
beforeAll(async () => {
sql = postgres(PG_URL!);
await sql`DROP TABLE IF EXISTS shade_media_objects`;
await sql`DROP TABLE IF EXISTS shade_media_uploads`;
await sql`DROP TABLE IF EXISTS shade_live_pins`;
await sql`DROP TABLE IF EXISTS shade_live_publishers`;
});
afterAll(async () => {
await sql.end();
});
test('records: insert once, sizes past 2^31, owner sums, newest first, remove returns the key', async () => {
const index = await PostgresMediaIndex.fromClient(sql);
const big = 40 * 1024 ** 3; // a 40 GiB film
await index.insert(rec(hexId(1), 'alice', big, 10));
await index.insert(rec(hexId(2), 'alice', 5, 20));
await index.insert(rec(hexId(3), 'bob', 7, 30));
await expect(index.insert(rec(hexId(1), 'mallory', 1))).rejects.toBeInstanceOf(MediaExistsError);
expect((await index.get(hexId(1)))!.owner).toBe('alice');
expect(await index.usage('alice')).toBe(big + 5);
expect(await index.totalBytes()).toBe(big + 12);
expect((await index.list('alice')).map((r) => r.id)).toEqual([hexId(2), hexId(1)]);
expect('key' in (await index.list('alice'))[0]!).toBe(false);
expect((await index.remove(hexId(1)))!.key).toBe(rec(hexId(1), 'alice', 1).key);
expect(await index.remove(hexId(1))).toBeNull();
expect(await index.usage('alice')).toBe(5);
});
test('racing inserts of one id over separate connections: exactly one wins', async () => {
const pools = Array.from({ length: 8 }, () => postgres(PG_URL!, { max: 2 }));
try {
const indexes = await Promise.all(pools.map((p) => PostgresMediaIndex.fromClient(p)));
const results = await Promise.allSettled(indexes.flatMap((ix, i) => [0, 1, 2].map((j) => ix.insert(rec(hexId(99), `o${i}-${j}`, 1)))));
expect(results.filter((r) => r.status === 'fulfilled').length).toBe(1);
expect(results.filter((r) => r.status === 'rejected' && r.reason instanceof MediaExistsError).length).toBe(23);
} finally {
await Promise.all(pools.map((p) => p.end()));
}
});
test('uploads under way: one per id, each piece recorded once in any order, counted against the owner', async () => {
const chunk = 16 * 1024 * 1024;
const pending = (owner: string, uploadId: string): PendingObject => ({
id: hexId(500),
owner,
size: 50 * 1024 ** 3, // a 50 GiB film, promised
readTokenHash: null,
chunk,
key: `objects/${hexId(500)}/${'11'.repeat(16)}.smf`,
uploadId,
etags: [],
createdAt: 5,
updatedAt: 5,
});
const index = await PostgresMediaIndex.fromClient(sql);
const before = await index.usage('carol');
expect((await index.insertPending(pending('carol', 'up-1'))).uploadId).toBe('up-1');
// A second instance starting the same upload gets the first one's.
expect((await index.insertPending(pending('carol', 'up-2'))).uploadId).toBe('up-1');
expect(await index.usage('carol')).toBe(before + 50 * 1024 ** 3);
const fresh = (await index.getPending(hexId(500)))!;
expect(fresh.etags.length).toBe(3200);
expect(fresh.etags.every((e) => e === null)).toBe(true);
// Piece 2 lands before piece 0, on six connections at once: recorded once, at its own place.
const pools = Array.from({ length: 6 }, () => postgres(PG_URL!, { max: 1 }));
try {
const indexes = await Promise.all(pools.map((p) => PostgresMediaIndex.fromClient(p)));
await Promise.all(indexes.map((ix, i) => ix.landPiece(hexId(500), 2, `"etag-${i}"`, 9)));
} finally {
await Promise.all(pools.map((p) => p.end()));
}
let now = (await index.getPending(hexId(500)))!;
expect(now.etags.slice(0, 4).map((e) => e !== null)).toEqual([false, false, true, false]);
const first = now.etags[2];
await index.landPiece(hexId(500), 2, '"later"', 10);
await index.landPiece(hexId(500), 0, '"e0"', 11);
now = (await index.getPending(hexId(500)))!;
expect(now.etags[2]).toBe(first!);
expect(now.etags.slice(0, 3)).toEqual(['"e0"', null, first!]);
expect(now.updatedAt).toBe(11);
expect((await index.stalePending(11)).map((p) => p.id)).toEqual([]);
expect((await index.stalePending(12)).map((p) => p.id)).toEqual([hexId(500)]);
expect((await index.removePending(hexId(500)))!.uploadId).toBe('up-1');
expect(await index.getPending(hexId(500))).toBeNull();
expect(await index.usage('carol')).toBe(before);
});
test('pins: refreshed by their own key, refused to another, even when two relays race to create one', async () => {
const pins = await PostgresLivePinStore.fromClient(sql, 1000);
const pin = { channelId: 'ch1', signingKey: 'K1', readTokenHash: 'h', pinnedAt: 100, lastSeen: 100 };
await pins.put(pin);
await pins.put({ ...pin, lastSeen: 150 });
expect((await pins.get('ch1'))!.lastSeen).toBe(150);
await expect(pins.put({ ...pin, signingKey: 'K2' })).rejects.toBeInstanceOf(LivePinTakenError);
expect((await pins.get('ch1'))!.signingKey).toBe('K1');
const pools = [postgres(PG_URL!), postgres(PG_URL!)];
try {
const [a, b] = await Promise.all(pools.map((p) => PostgresLivePinStore.fromClient(p)));
for (let i = 0; i < 20; i++) {
const id = `race-${i}`;
const r = await Promise.allSettled([
a!.put({ ...pin, channelId: id, signingKey: 'A', lastSeen: 160 }),
b!.put({ ...pin, channelId: id, signingKey: 'B', lastSeen: 160 }),
]);
expect(r.filter((x) => x.status === 'fulfilled').length).toBe(1);
}
} finally {
await Promise.all(pools.map((p) => p.end()));
}
// Idle past the TTL: released, and the channel may be pinned anew.
await pins.put({ ...pin, channelId: 'other', lastSeen: 5000 });
expect(await pins.get('ch1')).toBeNull();
await pins.put({ ...pin, signingKey: 'K2', lastSeen: 5000 });
expect((await pins.get('ch1'))!.signingKey).toBe('K2');
});
});
describe.skipIf(PG_URL === undefined)('Postgres live publisher locator', () => {
test('newest claim wins, release only removes its own, stale claims are not found', async () => {
const sql = postgres(PG_URL!, { onnotice: () => {} });
try {
const loc = await PostgresLivePublisherLocator.fromClient(sql);
await loc.claim('c', 'http://a', 1000);
expect(await loc.find('c', 0)).toBe('http://a');
await loc.claim('c', 'http://b', 2000);
await loc.release('c', 'http://a'); // a late release from the old relay
expect(await loc.find('c', 0)).toBe('http://b');
expect(await loc.find('c', 2000)).toBeNull(); // not refreshed since: a dead relay
await loc.release('c', 'http://b');
expect(await loc.find('c', 0)).toBeNull();
} finally {
await sql.end();
}
});
test('two media services over Postgres: publish on one, watch on the other', async () => {
const pools = [postgres(PG_URL!, { onnotice: () => {} }), postgres(PG_URL!, { onnotice: () => {} })];
const relays = await Promise.all(
pools.map(async (p) => {
let app: Hono | null = null;
const server = Bun.serve({ port: 0, fetch: (req, srv) => app!.fetch(req, { server: srv }), websocket });
const self = `http://localhost:${server.port}`;
const svc = createMediaService({
owners: 'any',
store: new MemoryMediaStore(),
pins: await PostgresLivePinStore.fromClient(p),
live: { mesh: { self, locator: await PostgresLivePublisherLocator.fromClient(p), pollMs: 100 } },
});
app = new Hono().route('/', svc.app);
return { server, svc, self };
}),
);
const [a, b] = relays as [(typeof relays)[0], (typeof relays)[0]];
try {
const pub = new LivePublisher({ meta: { name: 'logg' } });
const c = new LivePublishClient({ relay: a.self, publisher: pub, readToken: new Uint8Array(32).fill(5) });
await c.whenReady();
const grant = parseGrant(encodeGrant(c.grant('oldest'))) as LiveGrant;
const got: ReceivedFrame[] = [];
const v = new LiveWatchClient(grant, { url: grant.url!.replace(a.self.replace('http', 'ws'), b.self.replace('http', 'ws')), onFrame: (f) => void got.push(f) });
const deadline = Date.now() + 10_000;
while (b.svc.relay.stats().viewers < 1 || a.svc.relay.stats().viewers < 1) {
if (Date.now() > deadline) throw new Error('B never followed A');
await Bun.sleep(20);
}
for (let i = 0; i < 5; i++) await c.send({ type: 'text', text: `linje ${i}` }, { keyframe: true });
while (got.length < 5) {
if (Date.now() > deadline) throw new Error(`got ${got.length} of 5`);
await Bun.sleep(20);
}
expect(got.map((f) => (f.content as { text: string }).text)).toEqual([0, 1, 2, 3, 4].map((i) => `linje ${i}`));
v.close();
c.close();
} finally {
for (const r of relays) {
r.svc.stop();
r.server.stop(true);
}
await Promise.all(pools.map((p) => p.end()));
}
}, 30_000);
});
describe.skipIf(PG_URL === undefined || S3_URL === undefined)('two relays, one shared backend', () => {
test('upload on one relay, play, list and delete on the other; a race for one id is decided once', async () => {
const prefix = `relay-test-${Date.now().toString(36)}`;
const s3Url = `${S3_URL!.replace(/\/$/, '')}/${prefix}`;
// Separate backends, separate pools: as two containers would be.
const backends = await Promise.all([0, 1].map(() => createSharedMediaBackend({ s3Url, pgUrl: PG_URL! })));
const servers = backends.map((be) => {
const svc = createMediaService({ owners: 'any', store: be.store, pins: be.pins });
const app = new Hono().route('/', svc.app);
const server = Bun.serve({ port: 0, fetch: (req) => app.fetch(req), maxRequestBodySize: 1024 ** 3 });
return { server, svc, base: `http://localhost:${server.port}` };
});
const [a, b] = servers as [(typeof servers)[0], (typeof servers)[0]];
try {
const owner = OwnerKey.generate();
const plain = new Uint8Array(20 * 1024 * 1024 + 99).map((_, i) => (i * 7) & 0xff);
const grant = await new MediaClient(a.base, owner).uploadBytes(plain, { meta: { name: 'Delt.mkv' } });
const r = await openGrant(grant, { url: grant.url!.replace(a.base, b.base) });
expect(r.meta.name).toBe('Delt.mkv');
expect(await r.read(17 * 1024 * 1024, 3 * 1024 * 1024 + 99)).toEqual(plain.subarray(17 * 1024 * 1024));
const { bytes, result } = await sealMediaBytes(new Uint8Array(2 * MIN_SEGMENT_SIZE).fill(3));
const race = await Promise.allSettled([a, b].map((s) => new MediaClient(s.base, owner).putSealed(result, bytes)));
expect(race.filter((x) => x.status === 'fulfilled').length).toBe(1);
const listed = await new MediaClient(b.base, owner).list();
expect(listed.items.length).toBe(2);
expect(listed.usage).toBe(listed.items.reduce((n, i) => n + i.size, 0));
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 new MediaClient(a.base, owner).list().then((l) => l.items.length)).toBe(0);
// Nothing left in the bucket, and nothing for the sweeper.
const { bucket, prefix: p } = S3Bucket.fromUrl(s3Url);
expect((await bucket.list(`${p}objects/`)).objects).toEqual([]);
expect(await backends[0]!.sweep()).toEqual({ objects: 0, uploads: 0 });
} finally {
for (const s of servers) {
s.server.stop(true);
s.svc.stop();
}
await Promise.all(backends.map((be) => be.close()));
}
}, 120_000);
test('a bucket it cannot use is refused at start, not at the first upload', async () => {
const u = new URL(S3_URL!);
u.password = 'wrong-secret';
await expect(createSharedMediaBackend({ s3Url: u.toString(), pgUrl: PG_URL! })).rejects.toThrow(/403|Access|Signature/);
});
});