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>
This commit is contained in:
@@ -282,7 +282,7 @@ export async function ensureInboxServerTables(sql: Sql): Promise<void> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sealed-media records (`PostgresMediaIndex`) and live-channel pins
|
||||
* Sealed-media records and uploads under way (`PostgresMediaIndex`) and live-channel pins
|
||||
* (`PostgresLivePinStore`) for relays that share one bucket. Sizes are
|
||||
* BIGINT: one film can pass 2 GiB, an owner's library 2^31 bytes easily.
|
||||
*/
|
||||
@@ -301,6 +301,31 @@ export async function ensureMediaServerTables(sql: Sql): Promise<void> {
|
||||
CREATE INDEX IF NOT EXISTS shade_media_owner_idx
|
||||
ON shade_media_objects(owner_pubkey, created_at DESC)
|
||||
`;
|
||||
// Resumable uploads under way: the multipart upload and which pieces
|
||||
// landed, so the next piece may land on any instance.
|
||||
await sql`
|
||||
CREATE TABLE IF NOT EXISTS shade_media_uploads (
|
||||
media_id TEXT PRIMARY KEY,
|
||||
owner_pubkey TEXT NOT NULL,
|
||||
size BIGINT NOT NULL,
|
||||
read_token_hash TEXT,
|
||||
chunk BIGINT NOT NULL,
|
||||
object_key TEXT NOT NULL,
|
||||
upload_id TEXT NOT NULL,
|
||||
-- etags[n + 1]: piece n's part; NULL until it lands. Pieces land in any order.
|
||||
etags TEXT[] NOT NULL DEFAULT '{}',
|
||||
created_at BIGINT NOT NULL,
|
||||
updated_at BIGINT NOT NULL
|
||||
)
|
||||
`;
|
||||
await sql`
|
||||
CREATE INDEX IF NOT EXISTS shade_media_uploads_owner_idx
|
||||
ON shade_media_uploads(owner_pubkey)
|
||||
`;
|
||||
await sql`
|
||||
CREATE INDEX IF NOT EXISTS shade_media_uploads_updated_idx
|
||||
ON shade_media_uploads(updated_at)
|
||||
`;
|
||||
await sql`
|
||||
CREATE TABLE IF NOT EXISTS shade_live_pins (
|
||||
channel_id TEXT PRIMARY KEY,
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import postgres, { type Sql } from 'postgres';
|
||||
import { LivePinTakenError, MediaExistsError } from '@shade/media/server';
|
||||
import type { IndexedMedia, LivePin, LivePinStore, LivePublisherLocator, MediaIndex, MediaRecord } from '@shade/media/server';
|
||||
import type {
|
||||
IndexedMedia,
|
||||
LivePin,
|
||||
LivePinStore,
|
||||
LivePublisherLocator,
|
||||
MediaIndex,
|
||||
MediaRecord,
|
||||
PendingObject,
|
||||
} from '@shade/media/server';
|
||||
import { ensureMediaServerTables } from './ensure-tables.js';
|
||||
|
||||
// "relation already exists, skipping" on every start is not news.
|
||||
@@ -24,10 +32,40 @@ const toRecord = (r: MediaRow): IndexedMedia => ({
|
||||
createdAt: Number(r.created_at),
|
||||
});
|
||||
|
||||
/** `etags` is selected as JSON: postgres.js reads a NULL element of a TEXT[] as the string "NULL". */
|
||||
interface UploadRow {
|
||||
media_id: string;
|
||||
owner_pubkey: string;
|
||||
size: string;
|
||||
read_token_hash: string | null;
|
||||
chunk: string;
|
||||
object_key: string;
|
||||
upload_id: string;
|
||||
etags: (string | null)[];
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
const toPending = (r: UploadRow): PendingObject => ({
|
||||
id: r.media_id,
|
||||
owner: r.owner_pubkey,
|
||||
size: Number(r.size),
|
||||
readTokenHash: r.read_token_hash,
|
||||
chunk: Number(r.chunk),
|
||||
key: r.object_key,
|
||||
uploadId: r.upload_id,
|
||||
etags: r.etags,
|
||||
createdAt: Number(r.created_at),
|
||||
updatedAt: Number(r.updated_at),
|
||||
});
|
||||
|
||||
/**
|
||||
* The shared record of a media bucket (`ObjectMediaStore`), so any number of
|
||||
* relay instances serve one library. The primary key on `media_id` is what
|
||||
* decides racing uploads of one id: exactly one INSERT wins, on any instance.
|
||||
* Uploads under way are rows of `shade_media_uploads`; a piece's ETag is
|
||||
* set only where none is, so of two instances landing one piece the first
|
||||
* is recorded and the second changes nothing.
|
||||
*/
|
||||
export class PostgresMediaIndex implements MediaIndex {
|
||||
private constructor(
|
||||
@@ -78,16 +116,75 @@ export class PostgresMediaIndex implements MediaIndex {
|
||||
|
||||
async usage(owner: string): Promise<number> {
|
||||
const rows = await this.sql<{ n: string }[]>`
|
||||
SELECT COALESCE(SUM(size), 0)::text AS n FROM shade_media_objects WHERE owner_pubkey = ${owner}
|
||||
SELECT (
|
||||
(SELECT COALESCE(SUM(size), 0) FROM shade_media_objects WHERE owner_pubkey = ${owner}) +
|
||||
(SELECT COALESCE(SUM(size), 0) FROM shade_media_uploads WHERE owner_pubkey = ${owner})
|
||||
)::text AS n
|
||||
`;
|
||||
return Number(rows[0]!.n);
|
||||
}
|
||||
|
||||
async totalBytes(): Promise<number> {
|
||||
const rows = await this.sql<{ n: string }[]>`SELECT COALESCE(SUM(size), 0)::text AS n FROM shade_media_objects`;
|
||||
const rows = await this.sql<{ n: string }[]>`
|
||||
SELECT (
|
||||
(SELECT COALESCE(SUM(size), 0) FROM shade_media_objects) +
|
||||
(SELECT COALESCE(SUM(size), 0) FROM shade_media_uploads)
|
||||
)::text AS n
|
||||
`;
|
||||
return Number(rows[0]!.n);
|
||||
}
|
||||
|
||||
async getPending(id: string): Promise<PendingObject | null> {
|
||||
const rows = await this.sql<UploadRow[]>`
|
||||
SELECT media_id, owner_pubkey, size::text, read_token_hash, chunk::text,
|
||||
object_key, upload_id, array_to_json(etags) AS etags, created_at::text, updated_at::text
|
||||
FROM shade_media_uploads WHERE media_id = ${id}
|
||||
`;
|
||||
return rows.length === 0 ? null : toPending(rows[0]!);
|
||||
}
|
||||
|
||||
async insertPending(p: PendingObject): Promise<PendingObject> {
|
||||
await this.sql`
|
||||
INSERT INTO shade_media_uploads
|
||||
(media_id, owner_pubkey, size, read_token_hash, chunk, object_key, upload_id, etags, created_at, updated_at)
|
||||
VALUES (${p.id}, ${p.owner}, ${p.size}, ${p.readTokenHash}, ${p.chunk},
|
||||
${p.key}, ${p.uploadId}, array_fill(NULL::text, ARRAY[${Math.ceil(p.size / p.chunk)}::int]),
|
||||
${p.createdAt}, ${p.updatedAt})
|
||||
ON CONFLICT (media_id) DO NOTHING
|
||||
`;
|
||||
const won = await this.getPending(p.id);
|
||||
if (won === null) throw new Error(`upload ${p.id} vanished as it was recorded`);
|
||||
return won;
|
||||
}
|
||||
|
||||
async landPiece(id: string, n: number, etag: string, at: number): Promise<void> {
|
||||
// 1-based, and filled with NULLs at insert: an element set in an empty
|
||||
// array would start the array at that subscript instead.
|
||||
await this.sql`
|
||||
UPDATE shade_media_uploads
|
||||
SET etags[${n + 1}::int] = ${etag}::text, updated_at = ${at}
|
||||
WHERE media_id = ${id} AND etags[${n + 1}::int] IS NULL
|
||||
`;
|
||||
}
|
||||
|
||||
async removePending(id: string): Promise<PendingObject | null> {
|
||||
const rows = await this.sql<UploadRow[]>`
|
||||
DELETE FROM shade_media_uploads WHERE media_id = ${id}
|
||||
RETURNING media_id, owner_pubkey, size::text, read_token_hash, chunk::text,
|
||||
object_key, upload_id, array_to_json(etags) AS etags, created_at::text, updated_at::text
|
||||
`;
|
||||
return rows.length === 0 ? null : toPending(rows[0]!);
|
||||
}
|
||||
|
||||
async stalePending(before: number): Promise<PendingObject[]> {
|
||||
const rows = await this.sql<UploadRow[]>`
|
||||
SELECT media_id, owner_pubkey, size::text, read_token_hash, chunk::text,
|
||||
object_key, upload_id, array_to_json(etags) AS etags, created_at::text, updated_at::text
|
||||
FROM shade_media_uploads WHERE updated_at < ${before}
|
||||
`;
|
||||
return rows.map(toPending);
|
||||
}
|
||||
|
||||
async list(owner: string): Promise<MediaRecord[]> {
|
||||
const rows = await this.sql<MediaRow[]>`
|
||||
SELECT media_id, owner_pubkey, size::text, read_token_hash, object_key, created_at::text
|
||||
|
||||
@@ -12,7 +12,7 @@ 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 } 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';
|
||||
@@ -36,6 +36,7 @@ describe.skipIf(PG_URL === undefined)('Postgres media index and live pins', () =
|
||||
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`;
|
||||
});
|
||||
@@ -72,6 +73,54 @@ describe.skipIf(PG_URL === undefined)('Postgres media index and live pins', () =
|
||||
}
|
||||
});
|
||||
|
||||
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 };
|
||||
|
||||
Reference in New Issue
Block a user