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>
This commit is contained in:
@@ -8,11 +8,13 @@
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/inbox-server": "workspace:*",
|
||||
"@shade/key-transparency": "workspace:*",
|
||||
"@shade/media": "workspace:*",
|
||||
"@shade/server": "workspace:*",
|
||||
"drizzle-orm": "^0.45.2",
|
||||
"postgres": "^3.4.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@shade/crypto-web": "workspace:*"
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
"hono": "^4.12.18"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,3 +280,38 @@ export async function ensureInboxServerTables(sql: Sql): Promise<void> {
|
||||
ON shade_inbox_blobs(expires_at)
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sealed-media records (`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.
|
||||
*/
|
||||
export async function ensureMediaServerTables(sql: Sql): Promise<void> {
|
||||
await sql`
|
||||
CREATE TABLE IF NOT EXISTS shade_media_objects (
|
||||
media_id TEXT PRIMARY KEY,
|
||||
owner_pubkey TEXT NOT NULL,
|
||||
size BIGINT NOT NULL,
|
||||
read_token_hash TEXT,
|
||||
object_key TEXT NOT NULL,
|
||||
created_at BIGINT NOT NULL
|
||||
)
|
||||
`;
|
||||
await sql`
|
||||
CREATE INDEX IF NOT EXISTS shade_media_owner_idx
|
||||
ON shade_media_objects(owner_pubkey, created_at DESC)
|
||||
`;
|
||||
await sql`
|
||||
CREATE TABLE IF NOT EXISTS shade_live_pins (
|
||||
channel_id TEXT PRIMARY KEY,
|
||||
signing_key TEXT NOT NULL,
|
||||
read_token_hash TEXT NOT NULL,
|
||||
pinned_at BIGINT NOT NULL,
|
||||
last_seen BIGINT NOT NULL
|
||||
)
|
||||
`;
|
||||
await sql`
|
||||
CREATE INDEX IF NOT EXISTS shade_live_pins_seen_idx
|
||||
ON shade_live_pins(last_seen)
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -3,10 +3,14 @@ export { PostgresPrekeyStore } from './postgres-prekey-store.js';
|
||||
export { PostgresInboxStore } from './postgres-inbox-store.js';
|
||||
export { PostgresKTLogStore } from './postgres-kt-store.js';
|
||||
export { PostgresBlobStore } from './postgres-blob-store.js';
|
||||
export { PostgresMediaIndex, PostgresLivePinStore } from './postgres-media-store.js';
|
||||
export { createSharedMediaBackend } from './shared-media.js';
|
||||
export type { SharedMediaBackend } from './shared-media.js';
|
||||
export {
|
||||
ensureClientTables,
|
||||
ensurePrekeyServerTables,
|
||||
ensureInboxServerTables,
|
||||
ensureKTLogTables,
|
||||
ensureBlobServerTables,
|
||||
ensureMediaServerTables,
|
||||
} from './ensure-tables.js';
|
||||
|
||||
160
packages/shade-storage-postgres/src/postgres-media-store.ts
Normal file
160
packages/shade-storage-postgres/src/postgres-media-store.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
import postgres, { type Sql } from 'postgres';
|
||||
import { LivePinTakenError, MediaExistsError } from '@shade/media/server';
|
||||
import type { IndexedMedia, LivePin, LivePinStore, MediaIndex, MediaRecord } from '@shade/media/server';
|
||||
import { ensureMediaServerTables } from './ensure-tables.js';
|
||||
|
||||
// "relation already exists, skipping" on every start is not news.
|
||||
const quiet = () => {};
|
||||
|
||||
interface MediaRow {
|
||||
media_id: string;
|
||||
owner_pubkey: string;
|
||||
size: string;
|
||||
read_token_hash: string | null;
|
||||
object_key: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
const toRecord = (r: MediaRow): IndexedMedia => ({
|
||||
id: r.media_id,
|
||||
owner: r.owner_pubkey,
|
||||
size: Number(r.size),
|
||||
readTokenHash: r.read_token_hash,
|
||||
key: r.object_key,
|
||||
createdAt: Number(r.created_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.
|
||||
*/
|
||||
export class PostgresMediaIndex implements MediaIndex {
|
||||
private constructor(
|
||||
private readonly sql: Sql,
|
||||
private readonly ownsConnection: boolean,
|
||||
) {}
|
||||
|
||||
static async create(connectionString: string): Promise<PostgresMediaIndex> {
|
||||
const sql = postgres(connectionString, { onnotice: quiet });
|
||||
await ensureMediaServerTables(sql);
|
||||
return new PostgresMediaIndex(sql, true);
|
||||
}
|
||||
|
||||
static async fromClient(sql: Sql): Promise<PostgresMediaIndex> {
|
||||
await ensureMediaServerTables(sql);
|
||||
return new PostgresMediaIndex(sql, false);
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.ownsConnection) await this.sql.end();
|
||||
}
|
||||
|
||||
async get(id: string): Promise<IndexedMedia | null> {
|
||||
const rows = await this.sql<MediaRow[]>`
|
||||
SELECT media_id, owner_pubkey, size::text, read_token_hash, object_key, created_at::text
|
||||
FROM shade_media_objects WHERE media_id = ${id}
|
||||
`;
|
||||
return rows.length === 0 ? null : toRecord(rows[0]!);
|
||||
}
|
||||
|
||||
async insert(rec: IndexedMedia): Promise<void> {
|
||||
const rows = await this.sql`
|
||||
INSERT INTO shade_media_objects (media_id, owner_pubkey, size, read_token_hash, object_key, created_at)
|
||||
VALUES (${rec.id}, ${rec.owner}, ${rec.size}, ${rec.readTokenHash}, ${rec.key}, ${rec.createdAt})
|
||||
ON CONFLICT (media_id) DO NOTHING
|
||||
RETURNING media_id
|
||||
`;
|
||||
if (rows.length === 0) throw new MediaExistsError(rec.id);
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<IndexedMedia | null> {
|
||||
const rows = await this.sql<MediaRow[]>`
|
||||
DELETE FROM shade_media_objects WHERE media_id = ${id}
|
||||
RETURNING media_id, owner_pubkey, size::text, read_token_hash, object_key, created_at::text
|
||||
`;
|
||||
return rows.length === 0 ? null : toRecord(rows[0]!);
|
||||
}
|
||||
|
||||
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}
|
||||
`;
|
||||
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`;
|
||||
return Number(rows[0]!.n);
|
||||
}
|
||||
|
||||
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
|
||||
FROM shade_media_objects WHERE owner_pubkey = ${owner}
|
||||
ORDER BY created_at DESC
|
||||
`;
|
||||
return rows.map((r) => {
|
||||
const { key: _key, ...rec } = toRecord(r);
|
||||
return rec;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Live-channel pins shared by relay instances. A channel is pinned to the
|
||||
* first signing key that opens it; the upsert only refreshes a pin whose key
|
||||
* matches, so two relays cannot pin one channel to two keys.
|
||||
*/
|
||||
export class PostgresLivePinStore implements LivePinStore {
|
||||
private constructor(
|
||||
private readonly sql: Sql,
|
||||
private readonly ownsConnection: boolean,
|
||||
private readonly ttlMs: number,
|
||||
) {}
|
||||
|
||||
static async create(connectionString: string, ttlMs = 30 * 24 * 3600 * 1000): Promise<PostgresLivePinStore> {
|
||||
const sql = postgres(connectionString, { onnotice: quiet });
|
||||
await ensureMediaServerTables(sql);
|
||||
return new PostgresLivePinStore(sql, true, ttlMs);
|
||||
}
|
||||
|
||||
static async fromClient(sql: Sql, ttlMs = 30 * 24 * 3600 * 1000): Promise<PostgresLivePinStore> {
|
||||
await ensureMediaServerTables(sql);
|
||||
return new PostgresLivePinStore(sql, false, ttlMs);
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.ownsConnection) await this.sql.end();
|
||||
}
|
||||
|
||||
async get(channelId: string): Promise<LivePin | null> {
|
||||
const rows = await this.sql<{ channel_id: string; signing_key: string; read_token_hash: string; pinned_at: string; last_seen: string }[]>`
|
||||
SELECT channel_id, signing_key, read_token_hash, pinned_at::text, last_seen::text
|
||||
FROM shade_live_pins WHERE channel_id = ${channelId}
|
||||
`;
|
||||
if (rows.length === 0) return null;
|
||||
const r = rows[0]!;
|
||||
return {
|
||||
channelId: r.channel_id,
|
||||
signingKey: r.signing_key,
|
||||
readTokenHash: r.read_token_hash,
|
||||
pinnedAt: Number(r.pinned_at),
|
||||
lastSeen: Number(r.last_seen),
|
||||
};
|
||||
}
|
||||
|
||||
async put(pin: LivePin): Promise<void> {
|
||||
// Pins idle past the TTL are released, as in FileLivePinStore.
|
||||
await this.sql`DELETE FROM shade_live_pins WHERE last_seen < ${pin.lastSeen - this.ttlMs}`;
|
||||
const rows = await this.sql`
|
||||
INSERT INTO shade_live_pins (channel_id, signing_key, read_token_hash, pinned_at, last_seen)
|
||||
VALUES (${pin.channelId}, ${pin.signingKey}, ${pin.readTokenHash}, ${pin.pinnedAt}, ${pin.lastSeen})
|
||||
ON CONFLICT (channel_id) DO UPDATE
|
||||
SET read_token_hash = EXCLUDED.read_token_hash, last_seen = EXCLUDED.last_seen
|
||||
WHERE shade_live_pins.signing_key = EXCLUDED.signing_key
|
||||
RETURNING channel_id
|
||||
`;
|
||||
if (rows.length === 0) throw new LivePinTakenError(pin.channelId);
|
||||
}
|
||||
}
|
||||
44
packages/shade-storage-postgres/src/shared-media.ts
Normal file
44
packages/shade-storage-postgres/src/shared-media.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import postgres from 'postgres';
|
||||
import { ObjectMediaStore, S3Bucket } from '@shade/media/server';
|
||||
import type { LivePinStore, MediaStore } from '@shade/media/server';
|
||||
import { PostgresLivePinStore, PostgresMediaIndex } from './postgres-media-store.js';
|
||||
|
||||
export interface SharedMediaBackend {
|
||||
store: MediaStore;
|
||||
pins: LivePinStore;
|
||||
/** Where the bytes go, for logs — no credentials. */
|
||||
describe: string;
|
||||
/** Reclaim unreferenced objects and dead uploads; safe on every instance at once. */
|
||||
sweep(): Promise<{ objects: number; uploads: number }>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A media backend several relay instances can share: sealed bytes in an S3
|
||||
* bucket, records and live pins in Postgres. Both the Shade container
|
||||
* (`SHADE_MEDIA_S3_URL` + `SHADE_MEDIA_PG_URL`) and `shade media serve --s3
|
||||
* --pg` build it here, so they behave alike. Tables are created on first use.
|
||||
*/
|
||||
export async function createSharedMediaBackend(opts: { s3Url: string; pgUrl: string }): Promise<SharedMediaBackend> {
|
||||
const { bucket, prefix } = S3Bucket.fromUrl(opts.s3Url);
|
||||
// "relation already exists, skipping" on every start is not news.
|
||||
const sql = postgres(opts.pgUrl, { onnotice: () => {} });
|
||||
try {
|
||||
const index = await PostgresMediaIndex.fromClient(sql);
|
||||
const pins = await PostgresLivePinStore.fromClient(sql);
|
||||
const store = new ObjectMediaStore(bucket, index, { prefix });
|
||||
// Fail at start, not at the first upload: a bucket that is not there, or
|
||||
// credentials it refuses, show up here.
|
||||
await bucket.list(`${prefix}objects/`);
|
||||
return {
|
||||
store,
|
||||
pins,
|
||||
describe: `s3 ${new URL(opts.s3Url).host}/${bucket.bucket}/${prefix}`,
|
||||
sweep: () => store.sweep(),
|
||||
close: () => sql.end(),
|
||||
};
|
||||
} catch (e) {
|
||||
await sql.end();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
153
packages/shade-storage-postgres/tests/postgres-media.test.ts
Normal file
153
packages/shade-storage-postgres/tests/postgres-media.test.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* 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, S3Bucket } from '@shade/media/server';
|
||||
import type { IndexedMedia } from '@shade/media/server';
|
||||
import { MediaClient, OwnerKey, openGrant, sealMediaBytes, MIN_SEGMENT_SIZE } from '@shade/media';
|
||||
import { createSharedMediaBackend, PostgresLivePinStore, 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_live_pins`;
|
||||
});
|
||||
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('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 || 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/);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user