import { AsyncLocalStorage } from "node:async_hooks" import { assertRuntimeDatabaseActivationCurrent, createPool } from "../../db/index.js" import { SYSTEM_DATABASE_REQUEST_LOCK } from "../../db/operation-lock.js" import { assertDatabaseRestoreQuarantineOpen, databaseRestoreQuarantineEnabled } from "../../db/database-restore-quarantine.js" import { sharedDatabaseGate } from "../../services/shared-database-gate.js" import { McpError } from "./security.js" const limit = 8 const leases = createPool(limit, true) leases.on("error", () => console.error("MCP database request lease lost on idle connection")) const apiLeases = createPool(limit, true) apiLeases.on("error", () => console.error("REST database request lease lost on idle connection")) const detachedApiLeases = createPool(2, true) detachedApiLeases.on("error", () => console.error("Detached REST database lease lost on idle connection")) const context = new AsyncLocalStorage<{ accepting: boolean; children: Set>; signal: AbortSignal }>() let active = 0 export function mcpDatabaseRequestSignal(): AbortSignal | undefined { return context.getStore()?.signal } export function withActiveDatabaseRequest(run: (signal: AbortSignal) => Promise): Promise | undefined { const parent = context.getStore() if (parent?.signal.aborted) return Promise.reject(parent.signal.reason) if (!parent?.accepting) return undefined const child = Promise.resolve().then(() => { parent.signal.throwIfAborted(); return run(parent.signal) }) parent.children.add(child) const settled = () => { parent.children.delete(child) } void child.then(settled, settled) return child } export function withMcpDatabaseRequest(run: () => Promise): Promise { return withDatabaseRequest(run, true) } export function withDatabaseApiRequest(run: () => Promise): Promise { return withDatabaseRequest(run, false) } export function checkDatabaseApiStartup(): Promise { return withDatabaseRequest(async () => {}, false, false, true) } async function withDatabaseRequest(run: () => Promise, mcp: boolean, detached = false, starting = false): Promise { const nested = withActiveDatabaseRequest(run) if (nested) return nested if (mcp && active >= limit) throw new McpError("RATE_LIMITED", "Лимит одновременно выполняемых запросов MCP", 429) if (mcp) active++ try { const client = await (detached ? detachedApiLeases : mcp ? leases : apiLeases).connect() let destroy = true, acquired = false const lifetime = new AbortController() const disconnected = () => lifetime.abort(new McpError("PROTOCOL_STORAGE_BUSY", "Соединение с допуском MCP потеряно", 503)) client.on("error", disconnected) client.on("end", disconnected) try { if (starting) await client.query("SET lock_timeout = '10s'") const { rows } = await client.query<{ acquired: boolean }>(starting ? "SELECT true AS acquired FROM pg_catalog.pg_advisory_lock_shared($1::bigint)" : "SELECT pg_catalog.pg_try_advisory_lock_shared($1::bigint) AS acquired", [SYSTEM_DATABASE_REQUEST_LOCK]) lifetime.signal.throwIfAborted() if (rows[0]?.acquired === false) { destroy = false throw new McpError("PROTOCOL_STORAGE_BUSY", "Выполняется операция с базой приложения", 503) } if (rows[0]?.acquired !== true) throw new McpError("AUDIT_UNAVAILABLE", "Допуск MCP не подтверждён", 503) acquired = true if (starting) await client.query("RESET lock_timeout") if (databaseRestoreQuarantineEnabled()) await assertDatabaseRestoreQuarantineOpen(client) assertRuntimeDatabaseActivationCurrent() lifetime.signal.throwIfAborted() const owner = { accepting: true, children: new Set>(), signal: lifetime.signal } try { return await context.run(owner, run) } finally { owner.accepting = false await Promise.allSettled(owner.children) } } finally { if (acquired && !lifetime.signal.aborted) { try { const { rows } = await client.query<{ released: boolean }>( "SELECT pg_catalog.pg_advisory_unlock_shared($1::bigint) AS released", [SYSTEM_DATABASE_REQUEST_LOCK]) destroy = rows[0]?.released !== true } catch { /* Destroy the backend rather than return an uncertain session lock. */ } } client.off("error", disconnected) client.off("end", disconnected) client.release(destroy || lifetime.signal.aborted) } } finally { if (mcp) active-- } } /** A scheduled operation owns a new lease, even when the submitting request is still active. */ export function withMcpRunnerDatabaseRequest(run: () => Promise): Promise { return context.exit(() => withMcpDatabaseRequest(run)) } /** Detached jobs keep their own lease through terminal persistence after the HTTP response. */ export function withDetachedDatabaseApiRequest(run: () => Promise): Promise { return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, false, true))) }