// postgres's provisioner — the adapter that makes postgres a provider of the mesh // `postgres-database` interface. The watching, sealing and grant-file handling are the sdk // harness's; this writes only the per-service half: how postgres creates and removes a consumer's // database + owning role (novox/hq ADR 0044/0045). // // The `postgres-database` interface: a consumer receives `{ host, port, database, user, password }` // and connects to a database only it owns. // // Identity (the database and role names) is derived from `grant.consumer` alone — never from // `grant.values` — because on removal the harness hands the adapter a grant carrying only the // consumer. Deriving from the consumer keeps create and remove naming the same resource. // // The credential is composed here and returned; the DDL runs through PostgresClient.query(), which // is the module's one pending boundary (see client.ts). Until that boundary is backed, create() // surfaces the TODO honestly rather than sealing a credential for a database that was never made. import { runProvisioner, type Grant, type Credential } from "@novox/mesh-sdk/provisioner"; import { emit } from "@novox/mesh-sdk/events"; import { PostgresClient, generatePassword } from "../client.js"; const postgres = PostgresClient.fromEnv(); /** A stable postgres identifier for a consumer: lowercase [a-z0-9_], never starting with a digit. */ function identity(consumer: string): string { let safe = consumer.toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/^_+|_+$/g, ""); if (safe === "" ) safe = "consumer"; if (/^[0-9]/.test(safe)) safe = "_" + safe; return safe.slice(0, 63); // postgres identifier limit } /** Emit a lifecycle event without letting a broker hiccup fail the provisioning itself. */ async function announce(type: string, body: Record): Promise { try { await emit(type, body); } catch (err) { console.error(`[provisioner:postgres-database] emit ${type} failed: ${err}`); } } runProvisioner("postgres-database", { async create(grant: Grant): Promise { const database = identity(grant.consumer); const user = database; const password = generatePassword(); await postgres.createDatabaseAndRole(database, user, password); await announce("module.postgres.database.provisioned", { consumer: grant.consumer, database, user }); return { fields: { host: postgres.host, port: String(postgres.port), database, user, password, }, }; }, async remove(grant: Grant): Promise { const database = identity(grant.consumer); const user = database; await postgres.dropDatabaseAndRole(database, user); await announce("module.postgres.database.deprovisioned", { consumer: grant.consumer, database }); }, });