db.ts70 lines · main
| 1 | /** |
| 2 | * Doltgres connection pool for database `briven_engine`. |
| 3 | * HARD RULE: only Doltgres. Refuses stock postgres host. |
| 4 | */ |
| 5 | |
| 6 | import pg from 'pg'; |
| 7 | |
| 8 | import { env } from '../../env.js'; |
| 9 | import { log } from '../../lib/logger.js'; |
| 10 | |
| 11 | let pool: pg.Pool | null = null; |
| 12 | |
| 13 | function engineDatabaseUrl(): string { |
| 14 | // Prefer dedicated URL; else rewrite control URL database name to briven_engine. |
| 15 | if (env.BRIVEN_ENGINE_DATABASE_URL) { |
| 16 | return env.BRIVEN_ENGINE_DATABASE_URL; |
| 17 | } |
| 18 | const base = env.BRIVEN_DATABASE_URL ?? env.BRIVEN_DATA_PLANE_URL; |
| 19 | if (!base) { |
| 20 | throw new Error( |
| 21 | 'BRIVEN_ENGINE_DATABASE_URL or BRIVEN_DATABASE_URL required for briven-engine (Doltgres)', |
| 22 | ); |
| 23 | } |
| 24 | const u = new URL(base); |
| 25 | if (u.hostname === 'postgres') { |
| 26 | throw new Error( |
| 27 | 'DOLTGRES-FIRST: briven-engine refuses stock postgres host — use doltgres', |
| 28 | ); |
| 29 | } |
| 30 | u.pathname = '/briven_engine'; |
| 31 | return u.toString(); |
| 32 | } |
| 33 | |
| 34 | export function openEnginePool(): pg.Pool { |
| 35 | if (pool) return pool; |
| 36 | const connectionString = engineDatabaseUrl(); |
| 37 | const host = new URL(connectionString).hostname; |
| 38 | if (host === 'postgres') { |
| 39 | throw new Error('DOLTGRES-FIRST: refusing stock postgres for briven-engine'); |
| 40 | } |
| 41 | pool = new pg.Pool({ |
| 42 | connectionString, |
| 43 | max: 10, |
| 44 | // Doltgres-friendly |
| 45 | idleTimeoutMillis: 30_000, |
| 46 | }); |
| 47 | pool.on('error', (err) => { |
| 48 | log.warn('briven_engine_pool_error', { |
| 49 | message: err instanceof Error ? err.message : String(err), |
| 50 | }); |
| 51 | }); |
| 52 | log.info('briven_engine_pool_open', { host, database: 'briven_engine' }); |
| 53 | return pool; |
| 54 | } |
| 55 | |
| 56 | export function getEnginePool(): pg.Pool { |
| 57 | if (!pool) return openEnginePool(); |
| 58 | return pool; |
| 59 | } |
| 60 | |
| 61 | export function isEnginePoolReady(): boolean { |
| 62 | return pool != null; |
| 63 | } |
| 64 | |
| 65 | export async function closeEnginePool(): Promise<void> { |
| 66 | if (pool) { |
| 67 | await pool.end(); |
| 68 | pool = null; |
| 69 | } |
| 70 | } |