import postgres from 'postgres'; import { ObjectMediaStore, S3Bucket } from '@shade/media/server'; import type { LivePinStore, LivePublisherLocator, MediaStore } from '@shade/media/server'; import { PostgresLivePinStore, PostgresLivePublisherLocator, PostgresMediaIndex } from './postgres-media-store.js'; export interface SharedMediaBackend { store: MediaStore; pins: LivePinStore; /** Where each live channel's publisher is, for relays that follow one another. */ locator: LivePublisherLocator; /** 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; } /** * 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 { 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 locator = await PostgresLivePublisherLocator.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, locator, describe: `s3 ${new URL(opts.s3Url).host}/${bucket.bucket}/${prefix}`, sweep: () => store.sweep(), close: () => sql.end(), }; } catch (e) { await sql.end(); throw e; } }