Files
MikrotikManager/backend/src/modules/mcp/database-request-lease.ts
T

95 lines
5.1 KiB
TypeScript

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<Promise<unknown>>; signal: AbortSignal }>()
let active = 0
export function mcpDatabaseRequestSignal(): AbortSignal | undefined { return context.getStore()?.signal }
export function withActiveDatabaseRequest<T>(run: (signal: AbortSignal) => Promise<T>): Promise<T> | 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<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, true) }
export function withDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, false) }
export function checkDatabaseApiStartup(): Promise<void> {
return withDatabaseRequest(async () => {}, false, false, true)
}
async function withDatabaseRequest<T>(run: () => Promise<T>, mcp: boolean, detached = false, starting = false): Promise<T> {
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<Promise<unknown>>(), 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<T>(run: () => Promise<T>): Promise<T> {
return context.exit(() => withMcpDatabaseRequest(run))
}
/** Detached jobs keep their own lease through terminal persistence after the HTTP response. */
export function withDetachedDatabaseApiRequest<T>(run: () => Promise<T>): Promise<T> {
return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, false, true)))
}