Files
MikrotikManager/backend/src/services/database-request-gate.ts
T

87 lines
4.5 KiB
TypeScript

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<Promise<void>> }
/** Handler lifetime, not socket lifetime: disconnect does not finish an active write. */
export class DatabaseRequestGate {
private readonly requestContext = new AsyncLocalStorage<DatabaseAdmission>()
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<T>(run: () => Promise<T>): Promise<T> {
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<void>(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<void> {
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<void> {
if (!this.isPaused()) return Promise.resolve()
return new Promise(resolve => { this.openWaiters.add(resolve) })
}
private paused = false
private active = new Map<symbol, (() => void) | undefined>()
private idle: (() => void) | undefined
async request<T>(run: () => Promise<T>, cancelStream?: () => void): Promise<T> {
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<T>(run: () => Promise<T>, timeoutMs = 30_000): Promise<T> {
if (this.paused) throw conflict("Операция с базой приложения уже выполняется")
this.paused = true
let timer: ReturnType<typeof setTimeout> | undefined
try {
for (const cancel of this.active.values()) cancel?.()
if (this.active.size) await new Promise<void>((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()
}
}
}