import { AsyncLocalStorage } from "node:async_hooks" function conflict(message: string): Error & { statusCode: number } { return Object.assign(new Error(message), { statusCode: 409 }) } type DatabaseAdmission = { active: boolean; kind: "request" | "exclusive"; requestAncestry: boolean; children: Set> } /** Handler lifetime, not socket lifetime: disconnect does not finish an active write. */ export class DatabaseRequestGate { private readonly requestContext = new AsyncLocalStorage() assertNoRequestContext(): void { if (this.requestContext.getStore()?.requestAncestry) throw conflict("Scheduler bootstrap inside request context") } /** Live private scope only; detached children cannot retain a settled admission. */ hasActiveAdmission(): boolean { return this.requestContext.getStore()?.active === true } /** Registration is synchronous; the parent drains this continuation and its * descendants even if the caller deliberately does not await its result. */ async withinAdmission(run: () => Promise): Promise { const parent = this.requestContext.getStore() if (!parent?.active) throw conflict("Database admission is no longer active") const admission: DatabaseAdmission = { active: true, kind: parent.kind, requestAncestry: parent.requestAncestry, children: new Set() } let release!: () => void const settled = new Promise(resolve => { release = resolve }) parent.children.add(settled) try { return await this.requestContext.run(admission, run) } finally { await this.drainAdmission(admission) parent.children.delete(settled) release() } } private async drainAdmission(admission: DatabaseAdmission): Promise { admission.active = false await Promise.all(admission.children) } private openWaiters = new Set<() => void>() // Replacement uncertainty survives the temporary exclusive operation. private admissionClosed = false closeAdmission(): void { this.admissionClosed = true } openAdmission(): void { this.admissionClosed = false; this.notifyOpen() } private notifyOpen(): void { if (this.isPaused()) return const waiting = [...this.openWaiters]; this.openWaiters.clear() for (const resolve of waiting) resolve() } isPaused(): boolean { return this.paused || this.admissionClosed } whenOpen(): Promise { if (!this.isPaused()) return Promise.resolve() return new Promise(resolve => { this.openWaiters.add(resolve) }) } private paused = false private active = new Map void) | undefined>() private idle: (() => void) | undefined async request(run: () => Promise, cancelStream?: () => void): Promise { if (this.paused) throw conflict("Выполняется операция с базой приложения; повторите запрос позже") if (this.admissionClosed) throw Object.assign(new Error("Схема базы после восстановления не подтверждена; требуется проверка или явное восстановление"), { statusCode: 503 }) const lease = Symbol() this.active.set(lease, cancelStream) const admission: DatabaseAdmission = { active: true, kind: "request", requestAncestry: true, children: new Set() } try { return await this.requestContext.run(admission, run) } finally { await this.drainAdmission(admission) this.active.delete(lease) if (!this.active.size) this.idle?.() } } async exclusive(run: () => Promise, timeoutMs = 30_000): Promise { if (this.paused) throw conflict("Операция с базой приложения уже выполняется") this.paused = true let timer: ReturnType | undefined try { for (const cancel of this.active.values()) cancel?.() if (this.active.size) await new Promise((resolve, reject) => { this.idle = resolve timer = setTimeout(() => reject(conflict("Не удалось дождаться завершения API-запросов; операция с базой отменена")), timeoutMs) }) const admission: DatabaseAdmission = { active: true, kind: "exclusive", requestAncestry: this.requestContext.getStore()?.requestAncestry === true, children: new Set() } try { return await this.requestContext.run(admission, run) } finally { await this.drainAdmission(admission) } } finally { if (timer) clearTimeout(timer) this.idle = undefined this.paused = false this.notifyOpen() } } }