Files
MikrotikManager/backend/src/db/index.ts
T

139 lines
5.4 KiB
TypeScript

import { isMainThread } from "node:worker_threads"
import pg from "pg"
import { drizzle } from "drizzle-orm/node-postgres"
import { env } from "../config.js"
import * as schema from "./schema.js"
import { bindSql } from "./sql-bind.js"
import { DatabaseRuntimeSourceRefused, readRuntimeDatabasePoolOptions, type DatabaseArchivePeer } from "./database-runtime-source.js"
const INT8_OID = 20
const DATE_OID = 1082
pg.types.setTypeParser(INT8_OID, (val) => {
const n = Number(val)
return Number.isSafeInteger(n) ? n : val
})
pg.types.setTypeParser(DATE_OID, (val) => val)
class RuntimeCheckedPool extends pg.Pool {
constructor(
options: pg.PoolConfig,
private readonly checkCheckout: (client: pg.PoolClient) => Promise<void>,
readonly checkActivation?: () => void,
readonly archivePeer?: (client: pg.ClientBase) => DatabaseArchivePeer,
readonly readWriterHead?: (client: pg.ClientBase) => Promise<{ epoch: string; sha256: string; issuedAt: number }>,
) { super(options) }
connect(): Promise<pg.PoolClient>
connect(callback: (error: Error | undefined, client: pg.PoolClient | undefined, done: (release?: Error | boolean) => void) => void): void
connect(callback?: (error: Error | undefined, client: pg.PoolClient | undefined, done: (release?: Error | boolean) => void) => void): Promise<pg.PoolClient> | void {
const check = async (client: pg.PoolClient) => {
let connectionFailed = false
const onError = () => { connectionFailed = true }
// pg-pool has removed its idle listener and the caller does not own the client yet.
client.on("error", onError)
try {
await this.checkCheckout(client)
if (connectionFailed) throw new DatabaseRuntimeSourceRefused()
return client
} catch {
client.release(true)
throw new DatabaseRuntimeSourceRefused()
} finally {
client.removeListener("error", onError)
}
}
if (!callback) return super.connect().then(check)
return super.connect((error, client, done) => {
if (error || !client) return callback(error ?? new DatabaseRuntimeSourceRefused(), undefined, done)
void check(client).then(
() => callback(undefined, client, done),
(error: Error) => callback(error, undefined, () => {}),
)
})
}
}
export function createPool(max = 16, allowExitOnIdle = process.env.NODE_ENV === "test"): pg.Pool {
const { archivePeer, checkActivation, checkCheckout, readWriterHead, ...connection } = readRuntimeDatabasePoolOptions({
databaseUrl: env.DATABASE_URL,
requestFile: process.env.DATABASE_RUNTIME_REQUEST_FILE,
requestSha256: process.env.DATABASE_RUNTIME_REQUEST_SHA256,
caFile: process.env.DATABASE_RUNTIME_CA_FILE,
activationDirectory: process.env.DATABASE_RUNTIME_ACTIVATION_DIRECTORY,
activationSha256: process.env.DATABASE_RUNTIME_ACTIVATION_SHA256,
writerApprovalFile: process.env.DATABASE_RUNTIME_WRITER_APPROVAL_FILE,
writerApprovalSha256: process.env.DATABASE_RUNTIME_WRITER_APPROVAL_SHA256,
})
if (connection.onConnect && !process.env.DATABASE_URL) throw new DatabaseRuntimeSourceRefused()
const options = {
...connection,
max,
idleTimeoutMillis: 30_000,
allowExitOnIdle,
connectionTimeoutMillis: 8_000,
statement_timeout: 120_000,
}
const pool = checkCheckout ? new RuntimeCheckedPool(options, checkCheckout, checkActivation, archivePeer, readWriterHead) : new pg.Pool(options)
if (connection.onConnect) pool.on("error", () => console.error("Потеряно проверяемое соединение приложения с PostgreSQL"))
return pool
}
export const pool = createPool(isMainThread ? 16 : 4)
export function assertRuntimeDatabaseActivationCurrent(): void {
if (pool instanceof RuntimeCheckedPool) pool.checkActivation?.()
}
export async function readRuntimeDatabaseWriterHead(client: unknown) {
if (!(pool instanceof RuntimeCheckedPool) || !pool.readWriterHead) return undefined
if (!(client instanceof pg.Client)) throw new DatabaseRuntimeSourceRefused()
return pool.readWriterHead(client)
}
export function readRuntimeDatabaseArchivePeer(client: unknown): DatabaseArchivePeer {
if (!(pool instanceof RuntimeCheckedPool) || !pool.archivePeer || !(client instanceof pg.Client)) throw new DatabaseRuntimeSourceRefused()
return pool.archivePeer(client)
}
export const db = drizzle(pool, { schema })
export async function dbQuery<T extends pg.QueryResultRow = pg.QueryResultRow>(
text: string,
params?: unknown[] | Record<string, unknown>,
): Promise<pg.QueryResult<T>> {
const q = bindSql(text, params)
return pool.query<T>(q)
}
export async function dbAll<T extends pg.QueryResultRow = pg.QueryResultRow>(
text: string,
params?: unknown[] | Record<string, unknown>,
): Promise<T[]> {
const res = await dbQuery<T>(text, params)
return res.rows
}
export async function dbGet<T extends pg.QueryResultRow = pg.QueryResultRow>(
text: string,
params?: unknown[] | Record<string, unknown>,
): Promise<T | undefined> {
const rows = await dbAll<T>(text, params)
return rows[0]
}
export async function withAdvisoryLock<T>(key: number, fn: () => Promise<T>): Promise<T> {
const client = await pool.connect()
try {
await client.query("SELECT pg_advisory_lock($1)", [key])
return await fn()
} finally {
try {
await client.query("SELECT pg_advisory_unlock($1)", [key])
} catch {
/* ignore */
}
client.release()
}
}
export async function closePool(): Promise<void> {
await pool.end()
}