Files
stack/packages/db/src/client.ts
Jason Woltje 3b81bc9f3d perf: gateway + DB + frontend optimizations (P8-003)
- DB client: configure connection pool (max=20, idle_timeout=30s, connect_timeout=5s)
- DB schema: add missing indexes for auth sessions, accounts, conversations, agent_logs
- DB schema: promote preferences(user_id,key) to UNIQUE index for ON CONFLICT upsert
- Drizzle migration: 0003_p8003_perf_indexes.sql
- preferences.service: replace 2-query SELECT+INSERT/UPDATE with single-round-trip upsert
- conversations repo: add ORDER BY + LIMIT to findAll (200) and findMessages (500)
- session-gc.service: make onModuleInit fire-and-forget (removes cold-start TTFB block)
- next.config.ts: enable compress, productionBrowserSourceMaps:false, image avif/webp
- docs/PERFORMANCE.md: full profiling report and change impact notes
2026-03-18 21:26:45 -05:00

27 lines
1.1 KiB
TypeScript

import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema.js';
import { DEFAULT_DATABASE_URL } from './defaults.js';
export type Db = PostgresJsDatabase<typeof schema>;
export interface DbHandle {
db: Db;
close: () => Promise<void>;
}
export function createDb(url?: string): DbHandle {
const connectionString = url ?? process.env['DATABASE_URL'] ?? DEFAULT_DATABASE_URL;
const sql = postgres(connectionString, {
// Pool sizing: allow up to 20 concurrent connections per gateway instance.
// Each NestJS module (brain, preferences, memory, coord) shares this pool.
max: Number(process.env['DB_POOL_MAX'] ?? 20),
// Recycle idle connections after 30 s to avoid stale TCP state.
idle_timeout: Number(process.env['DB_IDLE_TIMEOUT'] ?? 30),
// Fail fast (5 s) on connection problems rather than hanging indefinitely.
connect_timeout: Number(process.env['DB_CONNECT_TIMEOUT'] ?? 5),
});
const db = drizzle(sql, { schema });
return { db, close: () => sql.end() };
}