Docker images / prepare-release (push) Successful in 9s
Docker images / updater-image (push) Successful in 3m22s
Docker images / frontend-image (push) Successful in 3m26s
Docker images / netflow-agent-image (push) Successful in 3m21s
Docker images / backend-test (push) Successful in 25m38s
Docker images / backend-image (push) Successful in 20m27s
Docker images / notify-webhook (push) Successful in 1s
Docker images / publish-release (push) Successful in 9s
88 lines
4.3 KiB
TypeScript
88 lines
4.3 KiB
TypeScript
import { setTimeout as delay } from "node:timers/promises"
|
|
import { and, desc, eq } from "drizzle-orm"
|
|
import { db } from "../db/index.js"
|
|
import { configRevisions, servers, type Server } from "../db/schema.js"
|
|
import { McpError } from "../modules/mcp/security.js"
|
|
import { fingerprintPayload, type ConfigSection } from "./config-revisions.js"
|
|
import { ConfigurationBusyError, withApplicationCollectorLock, withApplicationMutationLock, withConfigMutationLock } from "./config-mutation-lock.js"
|
|
|
|
/** Web reads share only the in-flight poll of this catalogue and endpoint generation. */
|
|
export function coalesceCatalogReads<T>(poll: (server: Server) => Promise<T>) {
|
|
const pending = new Map<string, Promise<T>>()
|
|
return (server: Server) => {
|
|
const key = server.id + ":" + server.routingEndpointEpoch
|
|
const current = pending.get(key)
|
|
if (current) return current
|
|
const request = poll(server).finally(() => { pending.delete(key) })
|
|
pending.set(key, request)
|
|
return request
|
|
}
|
|
}
|
|
|
|
async function latestRevision(serverId: number, section: ConfigSection) {
|
|
const [latest] = await db.select({ id: configRevisions.id, fingerprint: configRevisions.fingerprint }).from(configRevisions)
|
|
.where(and(eq(configRevisions.serverId, serverId), eq(configRevisions.section, section)))
|
|
.orderBy(desc(configRevisions.createdAt)).limit(1)
|
|
return latest
|
|
}
|
|
|
|
/** A live read matching both the cache and its revision has nothing to persist. */
|
|
export async function observationIsCurrent(serverId: number, section: ConfigSection, live: unknown[], cached: unknown[]) {
|
|
const fingerprint = fingerprintPayload(live)
|
|
return fingerprint === fingerprintPayload(cached) && (await latestRevision(serverId, section))?.fingerprint === fingerprint
|
|
}
|
|
|
|
async function assertCatalogSource(server: Server) {
|
|
const [source] = await db.select({ epoch: servers.routingEndpointEpoch }).from(servers).where(eq(servers.id, server.id))
|
|
if (!source || source.epoch !== server.routingEndpointEpoch) throw new McpError("STATE_CONFLICT", "Источник опроса изменился. Обновите каталог.", 409)
|
|
}
|
|
|
|
/** Retry only lock admission. Release DB clients before sleeping and never replay admitted work. */
|
|
async function enterCatalogLock<T>(lock: (run: () => Promise<T>) => Promise<T>, run: () => Promise<T>) {
|
|
const deadline = performance.now() + 5000
|
|
for (;;) {
|
|
let admitted = false
|
|
try { return await lock(() => { admitted = true; return run() }) }
|
|
catch (error) {
|
|
if (admitted || !(error instanceof ConfigurationBusyError) || performance.now() >= deadline) throw error
|
|
}
|
|
await delay(200)
|
|
}
|
|
}
|
|
|
|
export async function withCatalogWriteLock<T>(server: Server, section: ConfigSection, run: () => Promise<T>) {
|
|
const before = await latestRevision(server.id, section)
|
|
return enterCatalogLock(work => withApplicationMutationLock(() => withConfigMutationLock([server.id], work)), async () => {
|
|
await assertCatalogSource(server)
|
|
if ((await latestRevision(server.id, section))?.id !== before?.id) throw new McpError("STATE_CONFLICT", "Конфигурация изменилась во время ожидания. Обновите каталог.", 409)
|
|
return run()
|
|
})
|
|
}
|
|
|
|
// Waiting for a cache refresh must not occupy the DB connections needed by writers.
|
|
const catalogRefreshes = new Map<number, Promise<void>>()
|
|
export async function readCatalogWithObservedCache<T extends { current: boolean }>(
|
|
server: Server, read: (fresh: boolean) => Promise<T>, save: (observed: T) => Promise<T>,
|
|
): Promise<T> {
|
|
const observed = await read(false)
|
|
if (observed.current) return observed
|
|
const serverId = server.id
|
|
while (catalogRefreshes.has(serverId) || catalogRefreshes.size >= 2) {
|
|
const refreshing = catalogRefreshes.get(serverId)
|
|
await (refreshing ?? Promise.race(catalogRefreshes.values()))
|
|
if (refreshing) {
|
|
const latest = await read(false)
|
|
if (latest.current) return latest
|
|
}
|
|
}
|
|
let done!: () => void
|
|
catalogRefreshes.set(serverId, new Promise(resolve => { done = resolve }))
|
|
try {
|
|
return await enterCatalogLock(work => withApplicationCollectorLock(() => withConfigMutationLock([serverId], work), { waitMs: 0 }), async () => {
|
|
await assertCatalogSource(server)
|
|
const latest = await read(true)
|
|
return latest.current ? latest : save(latest)
|
|
})
|
|
} finally { catalogRefreshes.delete(serverId); done() }
|
|
}
|