games_app/backend/dist/db/connection.js

204 lines
8.4 KiB
JavaScript

"use strict";
/**
* PostgreSQL connection pool and query helpers.
* Loads environment from backend or repo root, runs parameterized queries, and applies schema migrations.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.markAuthorizedDbChange = markAuthorizedDbChange;
exports.beginAuthorizedTransaction = beginAuthorizedTransaction;
exports.query = query;
exports.getClient = getClient;
exports.runMigrations = runMigrations;
const dotenv_1 = __importDefault(require("dotenv"));
const pg_1 = require("pg");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
// Load .env from backend root first, then repo root (docker-compose .env lives at repo root)
const backendRoot = path.resolve(__dirname, '..', '..');
const repoRoot = path.resolve(__dirname, '..', '..', '..');
[path.join(backendRoot, '.env'), path.join(repoRoot, '.env')].forEach((envPath) => {
dotenv_1.default.config({ path: envPath });
});
/** Inside Docker, localhost is the container — rewrite to reach Postgres on the host. */
function resolveDatabaseUrl(raw) {
const trimmed = raw.trim();
try {
const parsed = new URL(trimmed);
const isLocalHost = parsed.hostname === 'localhost' ||
parsed.hostname === '127.0.0.1' ||
parsed.hostname === '::1' ||
parsed.hostname === '[::1]';
if (isLocalHost && fs.existsSync('/.dockerenv')) {
const dockerHost = process.env.DATABASE_DOCKER_HOST || 'host.docker.internal';
console.warn(`[db] DATABASE_URL host "${parsed.hostname}" does not work inside Docker; using "${dockerHost}". ` +
'Set DATABASE_URL with host.docker.internal in .env to silence this.');
parsed.hostname = dockerHost;
return parsed.toString();
}
}
catch {
// keep raw URL for connectionString fallback
}
return trimmed;
}
/** Resolves DB password: explicit env vars beat URL (avoids encoding issues in DATABASE_URL). */
function resolveDatabasePassword(parsed) {
const fromUrl = parsed.password ? decodeURIComponent(parsed.password) : '';
for (const candidate of [
process.env.DATABASE_PASSWORD,
process.env.POSTGRES_PASSWORD,
fromUrl,
]) {
if (typeof candidate === 'string' && candidate !== '') {
return candidate;
}
}
return '';
}
/**
* Builds pg Pool configuration from DATABASE_URL, preferring DATABASE_PASSWORD when set.
* @returns Parsed host/port config or a raw connectionString fallback
* @throws When DATABASE_URL is missing or empty
*/
function getPoolConfig() {
const url = resolveDatabaseUrl(process.env.DATABASE_URL ?? '');
if (!url || url.trim() === '') {
throw new Error('DATABASE_URL is not set. Create a .env file with DATABASE_URL=postgresql://user:password@localhost:5432/crypto_wallet');
}
try {
const parsed = new URL(url);
const password = resolveDatabasePassword(parsed);
return {
host: parsed.hostname,
port: parsed.port ? parseInt(parsed.port, 10) : 5432,
database: parsed.pathname?.slice(1) || 'crypto_wallet',
user: decodeURIComponent(parsed.username || '') || process.env.POSTGRES_USER || 'postgres',
password,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 10000,
};
}
catch {
return {
connectionString: url,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 10000,
};
}
}
const poolConfig = getPoolConfig();
const pool = new pg_1.Pool('connectionString' in poolConfig
? { ...poolConfig, max: 20, idleTimeoutMillis: 30000, connectionTimeoutMillis: 10000 }
: poolConfig);
const DEFAULT_STATEMENT_TIMEOUT_MS = Math.max(0, parseInt(process.env.DB_STATEMENT_TIMEOUT_MS ?? '180000', 10));
const AUTHORIZED_CHANGE_SQL = `SET app.authorized_change = '1'`;
const RESET_AUTHORIZED_CHANGE_SQL = `RESET app.authorized_change`;
/** Marks the current transaction as an authorized application write (bypasses DB tamper triggers). */
async function markAuthorizedDbChange(client) {
await client.query(`SET LOCAL app.authorized_change = '1'`);
}
/** Starts a transaction and marks subsequent writes as application-authorized. */
async function beginAuthorizedTransaction(client) {
await client.query('BEGIN');
await markAuthorizedDbChange(client);
}
/**
* Runs a parameterized SQL query and returns result rows.
* Application queries are marked authorized so PostgreSQL tamper triggers ignore them.
*/
async function query(text, params, options) {
const client = await pool.connect();
const timeoutMs = options?.statementTimeoutMs ?? DEFAULT_STATEMENT_TIMEOUT_MS;
try {
if (timeoutMs > 0) {
await client.query(`SET statement_timeout = ${Math.floor(timeoutMs)}`);
}
// Session-level flag: SET LOCAL does not persist across autocommit statements on the same client.
await client.query(AUTHORIZED_CHANGE_SQL);
const res = await client.query(text, params);
return res.rows;
}
finally {
await client.query(RESET_AUTHORIZED_CHANGE_SQL).catch(() => undefined);
if (timeoutMs > 0) {
await client.query('RESET statement_timeout').catch(() => undefined);
}
client.release();
}
}
/** Acquires a dedicated client from the connection pool. */
async function getClient() {
return pool.connect();
}
/**
* Applies schema.sql to the database (idempotent DDL).
* Resolves schema path from cwd or compiled __dirname for dev and production.
* @throws When schema.sql cannot be found on disk
*/
async function runMigrations() {
// In dev (ts-node) __dirname points to src/db; in production it points to dist/db.
// We prefer reading from source path (repo stable) and fall back to dist-local.
const candidates = [
path.resolve(process.cwd(), 'src', 'db', 'schema.sql'),
path.resolve(process.cwd(), 'backend', 'src', 'db', 'schema.sql'),
path.join(__dirname, 'schema.sql'),
];
const schemaPath = candidates.find((p) => fs.existsSync(p));
if (!schemaPath) {
throw new Error(`schema.sql not found. Tried: ${candidates.join(', ')}`);
}
const sql = fs.readFileSync(schemaPath, 'utf8');
const client = await pool.connect();
try {
await client.query(`SET app.authorized_change = '1'`);
await client.query(sql);
const { syncPermissionCatalog } = await Promise.resolve().then(() => __importStar(require('../rbac/syncPermissions')));
await syncPermissionCatalog();
const { ensureDefaultPoliciesSeeded } = await Promise.resolve().then(() => __importStar(require('../repositories/approvalPolicyRepository')));
await ensureDefaultPoliciesSeeded();
}
finally {
client.release();
}
}
/** Shared PostgreSQL connection pool for the application. */
exports.default = pool;
//# sourceMappingURL=connection.js.map