45 lines
1.8 KiB
TypeScript
45 lines
1.8 KiB
TypeScript
|
|
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;
|
||
|
|
}
|
||
|
|
}
|