Spaces:
Sleeping
Sleeping
File size: 8,326 Bytes
7f81110 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | import { drizzle } from "drizzle-orm/node-postgres";
import { Pool, type PoolConfig } from "pg";
import * as schema from "../../schema/index";
import { env } from "../../../../config/env";
import { logger } from "../../../common/logger";
// βββ Pool Configuration βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const POOL_CONFIG: PoolConfig = {
connectionString: env.DATABASE_URL,
// connection pool sizing
min: 2, // keep minimum connections alive
max: 10, // max connections per instance
// timeouts
connectionTimeoutMillis: 5_000, // fail fast if cant get connection from pool
idleTimeoutMillis: 10_000, // release idle connections after 10s (proactively)
statement_timeout: 30_000, // kill queries running over 30s
query_timeout: 30_000,
// limit connection lifetime to avoid stale pool issues with Neon
maxUses: 7500,
// keep connections alive through load balancers / firewalls
keepAlive: true,
keepAliveInitialDelayMillis: 10_000,
// ssl - support Neon and require SSL if specified in connection string
ssl: env.DATABASE_URL?.includes("sslmode=require") || env.DATABASE_URL?.includes("neon.tech") || env.NODE_ENV === "production"
? { rejectUnauthorized: false }
: false,
};
// βββ Pool Instance ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
let pool: Pool | null = null;
let db: ReturnType<typeof drizzle<typeof schema>> | null = null;
let isConnected = false;
let connectAttempts = 0;
const MAX_CONNECT_ATTEMPTS = 5;
const RETRY_DELAY_MS = [1_000, 2_000, 4_000, 8_000, 16_000]; // exponential backoff
// βββ Connection βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export async function connectPostgres(): Promise<void> {
if (!env.DATABASE_URL) {
logger.warn("postgres.skipped", {
reason: "DATABASE_URL not set",
});
return;
}
if (isConnected) {
logger.warn("postgres.already_connected");
return;
}
pool = new Pool(POOL_CONFIG);
// ββ pool-level event listeners ββ
pool.on("connect", (client: any) => {
// enforce row-level tenant scoping at connection level
client.query("SET app.current_tenant = ''").catch(() => { });
logger.debug("postgres.client_connected", {
totalCount: pool?.totalCount,
idleCount: pool?.idleCount,
});
});
pool.on("acquire", () => {
logger.debug("postgres.client_acquired", {
totalCount: pool?.totalCount,
idleCount: pool?.idleCount,
waitingCount: pool?.waitingCount,
});
});
pool.on("remove", () => {
logger.debug("postgres.client_removed", {
totalCount: pool?.totalCount,
});
});
pool.on("error", (error: Error) => {
logger.error("postgres.pool_error", {
error: error.message,
stack: error.stack,
totalCount: pool?.totalCount,
idleCount: pool?.idleCount,
waitingCount: pool?.waitingCount,
});
// don't crash β pool will attempt to recover
// but mark as disconnected so health checks fail
isConnected = false;
});
// ββ attempt connection with retry ββ
while (connectAttempts < MAX_CONNECT_ATTEMPTS) {
connectAttempts++;
try {
logger.info("postgres.connect_attempt", {
attempt: connectAttempts,
maxAttempts: MAX_CONNECT_ATTEMPTS,
});
// verify connection is actually reachable
const client = await pool.connect();
const result = await client.query("SELECT version(), current_database()");
client.release();
const { version, current_database } = result.rows[0];
db = drizzle(pool as any, { schema });
isConnected = true;
connectAttempts = 0; // reset for future reconnect attempts
logger.info("postgres.connected", {
database: current_database,
version: version.split(" ").slice(0, 2).join(" "),
poolMin: POOL_CONFIG.min,
poolMax: POOL_CONFIG.max,
});
return;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
const isLastAttempt = connectAttempts >= MAX_CONNECT_ATTEMPTS;
logger.error("postgres.connect_failed", {
attempt: connectAttempts,
maxAttempts: MAX_CONNECT_ATTEMPTS,
error: message,
});
if (isLastAttempt) {
await pool.end().catch(() => { });
pool = null;
db = null;
throw new Error(
`Failed to connect to PostgreSQL after ${MAX_CONNECT_ATTEMPTS} attempts: ${message}`
);
}
const delayMs = RETRY_DELAY_MS[connectAttempts - 1] ?? 16_000;
logger.info("postgres.retry_scheduled", {
delayMs,
nextAttempt: connectAttempts + 1,
});
await delay(delayMs);
}
}
}
// βββ Disconnect βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export async function disconnectPostgres(): Promise<void> {
if (!pool) return;
try {
await pool.end();
pool = null;
db = null;
isConnected = false;
logger.info("postgres.disconnected");
} catch (error) {
logger.error("postgres.disconnect_error", {
error: error instanceof Error ? error.message : String(error),
});
}
}
// βββ Health Check βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export async function checkPostgresHealth(): Promise<{
status: "healthy" | "unhealthy";
latencyMs?: number;
error?: string;
pool?: {
total: number;
idle: number;
waiting: number;
};
}> {
if (!pool || !isConnected) {
return { status: "unhealthy", error: "not_connected" };
}
const start = Date.now();
try {
const client = await pool.connect();
await client.query("SELECT 1");
client.release();
return {
status: "healthy",
latencyMs: Date.now() - start,
pool: {
total: pool.totalCount,
idle: pool.idleCount,
waiting: pool.waitingCount,
},
};
} catch (error) {
return {
status: "unhealthy",
latencyMs: Date.now() - start,
error: error instanceof Error ? error.message : String(error),
};
}
}
// βββ Require DB (safe accessor) βββββββββββββββββββββββββββββββββββββββββββββββ
export function requireDb() {
if (!db || !isConnected) {
throw new Error(
"PostgreSQL is not connected. Ensure connectPostgres() completed successfully."
);
}
return db;
}
export function getPool() {
if (!pool || !isConnected) {
throw new Error(
"PostgreSQL pool is not available."
);
}
return pool;
}
// βββ Utils ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); |