Compare commits

...
1 Commits
Author SHA1 Message Date
Denozordec ee6fd675ac fix(routing): устранить конфликты чтения фильтров и маршрутов
Docker images / prepare-release (push) Successful in 10s
Docker images / backend-test (push) Successful in 10m25s
Docker images / frontend-image (push) Successful in 3m18s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m48s
Docker images / publish-release (push) Successful in 10s
Docker images / notify-webhook (push) Successful in 1s
2026-11-24 12:46:31 +07:00
19 changed files with 344 additions and 61 deletions

No files matched your search

+2
View File
@@ -27,6 +27,7 @@ import internetPathRoutes from "./routes/internet-path.js"
import evobgpRoutes from "./routes/evobgp.js"
import { createStorageProbeRoutes } from "./routes/probe-storage-handler.js"
import schedulerRoutes from "./routes/scheduler.js"
import { ConfigurationBusyError } from "./services/config-mutation-lock.js"
import sidebarCountsRoutes from "./routes/sidebar-counts.js"
import alertsRoutes from "./routes/alerts.js"
import backupsRoutes from "./routes/backups.js"
@@ -105,6 +106,7 @@ export async function buildApp(opts?: {
return reply.status(status).send({ error: "Внутренняя ошибка сервера" })
}
const message = error instanceof Error ? error.message : "Ошибка запроса"
if (error instanceof ConfigurationBusyError) return reply.code(409).send({ error: message, code: error.code })
return reply.status(status).send({ error: message })
})
@@ -10,6 +10,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 writeReserve = createPool(2, true)
writeReserve.on("error", () => console.error("REST write database 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 }>()
@@ -28,19 +30,24 @@ export function withActiveDatabaseRequest<T>(run: (signal: AbortSignal) => Promi
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 withMcpDatabaseRequest<T>(run: () => Promise<T>): Promise<T> { return withDatabaseRequest(run, leases) }
export function withDatabaseApiRequest<T>(run: () => Promise<T>, mutation = false): Promise<T> {
// A burst of slow GETs must leave room for a configuration change to reach its lock.
const saturated = apiLeases.totalCount >= limit && apiLeases.idleCount === 0
return withDatabaseRequest(run, mutation && saturated ? writeReserve : apiLeases)
}
export function checkDatabaseApiStartup(): Promise<void> {
return withDatabaseRequest(async () => {}, false, false, true)
return withDatabaseRequest(async () => {}, apiLeases, true)
}
async function withDatabaseRequest<T>(run: () => Promise<T>, mcp: boolean, detached = false, starting = false): Promise<T> {
async function withDatabaseRequest<T>(run: () => Promise<T>, pool: typeof apiLeases, starting = false): Promise<T> {
const nested = withActiveDatabaseRequest(run)
if (nested) return nested
const mcp = pool === leases
if (mcp && active >= limit) throw new McpError("RATE_LIMITED", "Лимит одновременно выполняемых запросов MCP", 429)
if (mcp) active++
try {
const client = await (detached ? detachedApiLeases : mcp ? leases : apiLeases).connect()
const client = await pool.connect()
let destroy = true, acquired = false
const lifetime = new AbortController()
const disconnected = () => lifetime.abort(new McpError("PROTOCOL_STORAGE_BUSY", "Соединение с допуском MCP потеряно", 503))
@@ -90,5 +97,5 @@ export function withMcpRunnerDatabaseRequest<T>(run: () => Promise<T>): Promise<
/** 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)))
return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, detachedApiLeases)))
}
@@ -94,6 +94,7 @@ test("actual collector initial settings failures release resource/ping/group bus
const modules:Record<string,unknown>={"../db/index.js":{db,dbAll:async()=>[]},"../db/schema.js":tables,"drizzle-orm":Object.fromEntries(["and","asc","eq","gte","lte","inArray","max","sql"].map(name=>[name,()=>null])),
"./config-mutation-policy.js":{executeGuardedApplicationWrite:()=>assert.fail("no config mutation")},"./monitoring-server-catalog.js":{listEnabledMonitoringServers:async()=>[]},"./mikrotik.js":{MikrotikClient:class{}},"../types/scheduler-run-snapshot.js":{SCHEDULER_RUN_SNAPSHOT_VERSION:1},"../constants/ping-probe.js":{PING_PROBE_WARN_RTT_MS:100},"./ros-metric-parse.js":{},"./ping-probe-replacement.js":{},"./partition-write-transaction.js":{withPartitionWrite:()=>assert.fail("no targets"),isPartitionWriteOutcomeUnknown:()=>false,PartitionWriteError:class extends Error{}}}
const exports:Record<string,(...args:unknown[])=>Record<string,unknown>|Promise<Record<string,unknown>>>={}
modules["./config-mutation-lock.js"] = { withApplicationCollectorLock: (collect: () => Promise<unknown>) => collect() }
const code=ts.transpileModule(await readFile(new URL("../../services/uptime-collector.ts",import.meta.url),"utf8"),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText
runInNewContext(code,{exports,require:(name:string)=>{assert(name in modules,name);return modules[name]},Date,performance,console,Set,Map,Promise,Number,String,Math,Object,JSON,Error})
for(const method of ["collectResourceSamplesOnce","collectPingProbesOnce","collectPingForProbeIds"]){
+1 -1
View File
@@ -23,7 +23,7 @@ export function installDatabaseRequestGate(app: FastifyInstance, admit = withDat
const run = async () => withConfigurationActor(request.authUser?.id ?? "system", async () => await original.call(this, request, reply))
// The service owns exclusivity, including calls that do not originate in HTTP.
if (operation) return run()
if (!stream) return gate.request(() => admit(run))
if (!stream) return gate.request(() => admit(run, !["GET", "HEAD", "OPTIONS"].includes(request.method)))
const state = { cancelled: false, abort: undefined as (() => void) | undefined }
streams.set(request, state)
try {
+22 -12
View File
@@ -1,3 +1,4 @@
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
import { and, asc, eq, inArray } from "drizzle-orm"
import { z } from "zod"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
@@ -8,7 +9,6 @@ import { pollGreCatalog } from "../services/gre-catalog-poll.js"
import { parseKeepalive } from "../services/gre-live.js"
import { parseDbServerId } from "../utils/server-id.js"
import { observeBgpFilterRules } from "../services/filter-rules-observed.js"
import { withApplicationMutationLock, withConfigMutationLock } from "../services/config-mutation-lock.js"
import { appendEvent } from "../modules/events/service/events-service.js"
import { managedComment, hasManagedCommentPrefix } from "../managed-markers.js"
import { compileManagedFilterRules, filterRuleBranches, filterRuleDescriptions, filterRuleToken, validatedFilterRules } from "../services/filter-rules-write-model.js"
@@ -282,6 +282,8 @@ export async function fetchServerFilters(server: ServerRow) {
}
}
const readWebFilters = coalesceCatalogReads(fetchServerFilters)
async function toApiRulesets(serverRows: ServerRow[]) {
const dbRules = serverRows.length ? await db.select().from(filterRules).where(inArray(filterRules.serverId, serverRows.map(server => server.id))).orderBy(asc(filterRules.serverId), asc(filterRules.sortOrder), asc(filterRules.id)) : []
return serverRows.map(s => ({
@@ -381,20 +383,26 @@ export async function readFilterRulesCatalog(selected: ServerRow[], options: { s
const rulesets = await toApiRulesets(selected)
return rulesets.map(ruleset => ({ ...ruleset, greTunnels: [] as LiveGreTunnel[], nativeRules: null as ReturnType<typeof observeBgpFilterRules> | null, live: false, stale: false, source: "cache" as const, error: null as string | null }))
}
const readSelected = () => Promise.all(selected.map(async server => {
return Promise.all(selected.map(async server => {
try {
const remote = await fetchServerFilters(server)
if (options.persistObserved) {
const read = async (fresh: boolean) => {
const remote = await (fresh || !options.persistObserved ? fetchServerFilters : readWebFilters)(server)
if (!options.persistObserved) return { remote, rules: remote.rules, current: true }
const rules = await cacheRulesetsForServer(server.id)
const current = await observationIsCurrent(server.id, "filters", canonicalFilterRules(remote.rules), canonicalFilterRules(rules))
return { remote, rules, current }
}
const { remote, rules } = await readCatalogWithObservedCache(server, read, async ({ remote }) => {
await replaceDbRules(server.id, remote.rules)
await appendRevisionIfChanged({ serverId: server.id, section: "filters", source: "observed", payload: canonicalFilterRules(remote.rules) })
}
return { serverId: String(server.id), rules: options.persistObserved ? await cacheRulesetsForServer(server.id) : remote.rules, greTunnels: remote.tunnels, nativeRules: remote.nativeRules, live: true, stale: false, source: "device" as const, error: null as string | null }
} catch {
return { remote, rules: await cacheRulesetsForServer(server.id), current: true }
})
return { serverId: String(server.id), rules, greTunnels: remote.tunnels, nativeRules: remote.nativeRules, live: true, stale: false, source: "device" as const, error: null as string | null }
} catch (error) {
if (error instanceof McpError && error.statusCode === 409) throw error
return { serverId: String(server.id), rules: await cacheRulesetsForServer(server.id), greTunnels: [] as LiveGreTunnel[], nativeRules: null, live: false, stale: true, source: "cache" as const, error: server.enabled ? "Не подтверждено чтение фильтров выбранного сервера" : "Сервер выключен. Опрос фильтров недоступен." }
}
}))
return options.persistObserved
? withApplicationMutationLock(() => withConfigMutationLock(selected.map(server => server.id), readSelected)) : readSelected()
}
export async function applyFiltersToServer(
@@ -406,7 +414,7 @@ export async function applyFiltersToServer(
if (!server.enabled) throw new McpError("DEVICE_UNAVAILABLE", "Сервер выключен; изменение фильтров запрещено", 409)
if (options.managedRuleComment !== undefined && !hasManagedCommentPrefix(options.managedRuleComment)) throw new McpError("PROTECTED_OBJECT", "Сохранённый comment фильтра не принадлежит приложению", 409)
rules = validatedFilterRules(rules)
return executeGuardedApplicationWrite({ kind: "filters", id: "managed-bgp-in" }, [server.id], () => withConfigMutationLock([server.id], async () => {
return withCatalogWriteLock(server, "filters", () => executeGuardedApplicationWrite({ kind: "filters", id: "managed-bgp-in" }, [server.id], async () => {
const client = MikrotikClient.fromServer(server)
const interfaces = rules.some(rule => rule.action !== "blackhole" && rule.gatewayTunnelId && !rule.gatewayTunnelId.startsWith("rec:")) ? nativeBgpRows(await client.get("/interface/gre")) : []
const ruleBody = await toRouterRuleBody(server.id, rules, interfaces)
@@ -442,7 +450,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
const server = enabledServers.find(s => s.id === sid)
if (!server) return reply.status(404).send({ error: "Server not found" })
try {
const remote = await fetchServerFilters(server)
const remote = await readWebFilters(server)
return reply.send({ tunnels: remote.tunnels })
} catch (error) {
app.log.warn({ serverId: sid, err: String(error) }, "filters GRE catalog unavailable")
@@ -450,7 +458,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
}
}
return reply.send(await pollGreCatalog(enabledServers, fetchServerFilters))
return reply.send(await pollGreCatalog(enabledServers, readWebFilters))
})
/** Без serverId — cache для дашборда. С serverId — live с CHR, cache fallback. */
@@ -523,6 +531,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
rules: cached,
})
} catch (err) {
if (err instanceof McpError && err.statusCode === 409) throw err
app.log.error({ serverId, err: String(err) }, "filters apply failed")
await appendEvent({
level: "critical",
@@ -588,6 +597,7 @@ const filtersRoutes: FastifyPluginAsyncZod = async (app) => {
})
return reply.send({ ok: true, rules: cached, pushedRules: result.pushed })
} catch (err) {
if (err instanceof McpError) throw err
app.log.error({ serverId: server.id, err: String(err) }, "filters restore failed")
return reply.status(500).send({ error: String(err) })
}
+1 -1
View File
@@ -53,7 +53,7 @@ const ixRoutes: FastifyPluginAsync = async app => {
app.setErrorHandler((error, request, reply) => {
if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues })
if (error instanceof IxConflict) return reply.code(error.statusCode).send({ error: error.message })
if (error instanceof McpError) return reply.code(error.statusCode).send({ error: error.message })
if (error instanceof McpError) return reply.code(error.statusCode).send({ error: error.message, code: error.code })
if (error instanceof RestRequestProvenanceError) return reply.code(403).send({ error: "Нет действующего права изменения IX" })
request.log.error({ error: error instanceof Error ? error.name : "unknown" }, "IX request failed")
const errorMessage = request.method === "DELETE" ? "Удаление сегмента IX не подтверждено. Обновите данные и проверьте план."
+41 -25
View File
@@ -1,9 +1,10 @@
import { coalesceCatalogReads, observationIsCurrent, readCatalogWithObservedCache, withCatalogWriteLock } from "../services/routing-catalog-observation.js"
import { recursiveApplyBodySchema, recursiveTargetSchema, recursiveInputRowsSchema } from '../services/recursive-route-validation.js'
import { parseRecursiveCatalog, parseRecursiveGatewayCatalog, readRecursiveEffectiveProperties, type RecursiveObservedProperty } from "../services/recursive-route-catalog.js"
import { executeRecursiveApply, RecursiveApplyError } from "../services/recursive-apply.js"
import { storeRecursiveRoutes } from "../services/recursive-route-store.js"
import { planRecursiveIdentities } from "../services/recursive-route-identity.js"
import { withApplicationMutationLock, withConfigMutationLock } from "../services/config-mutation-lock.js"
import { McpError } from "../modules/mcp/security.js"
import { asc, eq } from "drizzle-orm"
import { z } from "zod"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
@@ -100,7 +101,7 @@ export async function applyRecursiveToServer(
source: ConfigRevisionSource,
validateExisting?: (rows: ReturnType<typeof parseRecursiveCatalog>) => void | Promise<void>,
): Promise<{ pushed: number; deleted: number }> {
return withApplicationMutationLock(() => withConfigMutationLock([server.id], async () => {
return withCatalogWriteLock(server, "recursive-routes", async () => {
await storeRecursiveRoutes(server.id, routes, source, true)
const client = MikrotikClient.fromServer(server)
return executeRecursiveApply(client, routes.map(toRouterPayload), async () => {
@@ -116,7 +117,7 @@ export async function applyRecursiveToServer(
await validateExisting?.(parseRecursiveCatalog(observed))
return observed
}, () => readRecursiveNativeRowsForServer(server))
}))
})
}
const RevisionIdParamSchema = z.object({ id: z.string().min(1) })
@@ -158,16 +159,32 @@ const recursiveDefaults: RecursiveRouteDependencies = {
/** Strict observation shared by both transports. REST can persist metadata;
* observers opt out. An unavailable source always fails this catalog read. */
export async function readRecursiveCatalogForServer(server: ServerRow, deps: Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved"> = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
const read = async () => {
type RecursiveReadDependencies = Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved">
const readWebRecursiveRows = coalesceCatalogReads(readRecursiveNativeRowsForServer)
async function observeRecursiveRoutes(server: ServerRow, deps: RecursiveReadDependencies, persist: boolean) {
const read = async (fresh: boolean) => {
if (!server.enabled) throw new Error("Устройство отключено: каталог маршрутов недоступен")
const observed = await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property))
const routes = mergeCachedCountry(parseRecursiveCatalog(observed), await deps.getRoutes(server.id))
if (options.persistObserved !== false) await deps.saveObserved(server.id, routes)
return { serverId: server.id, routes, live: true, stale: false }
const observed = !fresh && persist && deps === recursiveDefaults ? await readWebRecursiveRows(server)
: await readRecursiveEffectiveProperties(await deps.readRaw(server), (id, property) => deps.readProperty(server, id, property))
const cached = await deps.getRoutes(server.id)
const routes = mergeCachedCountry(parseRecursiveCatalog(observed), cached)
const current = !persist || deps === recursiveDefaults && await observationIsCurrent(server.id, "recursive-routes", canonicalRecursiveRoutes(routes), canonicalRecursiveRoutes(cached))
return { routes, cached, current }
}
return deps === recursiveDefaults && options.persistObserved !== false
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read()
const save = async (snapshot: Awaited<ReturnType<typeof read>>) => {
await deps.saveObserved(server.id, snapshot.routes)
return { ...snapshot, cached: await deps.getRoutes(server.id), current: true }
}
if (deps === recursiveDefaults) return readCatalogWithObservedCache(server, read, save)
const snapshot = await read(true)
return snapshot.current ? snapshot : save(snapshot)
}
export async function readRecursiveCatalogForServer(server: ServerRow, deps: RecursiveReadDependencies = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
const { routes } = await observeRecursiveRoutes(server, deps, options.persistObserved !== false)
return { serverId: server.id, routes, live: true, stale: false }
}
export async function readRecursiveNativeRowsForServer(server: ServerRow) {
@@ -187,22 +204,18 @@ export async function readRecursiveGatewaysForServer(server: ServerRow, deps: Pi
/** Legacy application read, including its explicit stale fallback. MCP observers
* share the source/parser while leaving cache and revision history untouched. */
export async function readRecursiveRoutesForServer(server: ServerRow, deps: Pick<RecursiveRouteDependencies, "readRaw" | "readProperty" | "getRoutes" | "saveObserved"> = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
export async function readRecursiveRoutesForServer(server: ServerRow, deps: RecursiveReadDependencies = recursiveDefaults, options: { persistObserved?: boolean } = {}) {
if (!server.enabled) throw new Error("Устройство отключено: опрос маршрутов недоступен")
const read = async () => {
const cached = await deps.getRoutes(server.id)
try {
const result = await readRecursiveCatalogForServer(server, deps, options)
const routes = options.persistObserved === false
? planRecursiveIdentities(cached, result.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || result.routes[index].id }))
: await deps.getRoutes(server.id)
return { ...result, routes }
} catch {
return { serverId: server.id, routes: cached, live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
}
try {
const observed = await observeRecursiveRoutes(server, deps, options.persistObserved !== false)
const routes = options.persistObserved === false
? planRecursiveIdentities(observed.cached, observed.routes, new Set(), "observed").rows.map((row, index) => ({ ...row, id: row.id || observed.routes[index].id }))
: observed.cached
return { serverId: server.id, routes, live: true, stale: false }
} catch (error) {
if (error instanceof McpError && (error.code === "CONFIGURATION_BUSY" || error.code === "STATE_CONFLICT")) throw error
return { serverId: server.id, routes: await deps.getRoutes(server.id), live: false, stale: true, error: "Не удалось подтвердить живой каталог; возвращена сохранённая конфигурация" }
}
return deps === recursiveDefaults && options.persistObserved !== false
? withApplicationMutationLock(() => withConfigMutationLock([server.id], read)) : read()
}
export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependencies> = {}): FastifyPluginAsyncZod {
@@ -218,6 +231,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
try {
return reply.send(await readRecursiveCatalogForServer(server, deps))
} catch (error) {
if (error instanceof McpError) throw error
return reply.status(503).send({ error: error instanceof Error ? error.message : "Не удалось прочитать каталог маршрутов" })
}
})
@@ -276,6 +290,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
return reply.send({ ok: true, serverId, routes: stored, pushedRoutes: result.pushed })
} catch (err) {
const receipt = recursiveFailureReceipt(err, result)
if (!receipt && err instanceof McpError) throw err
return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId, ...receipt })
}
})
@@ -313,6 +328,7 @@ export function createRecursiveRoutes(overrides: Partial<RecursiveRouteDependenc
return reply.send({ ok: true, serverId: server.id, routes: stored, pushedRoutes: result.pushed })
} catch (err) {
const receipt = recursiveFailureReceipt(err, result)
if (!receipt && err instanceof McpError) throw err
return reply.status(receipt ? 502 : 500).send({ error: String(err), serverId: server.id, ...receipt })
}
})
+11
View File
@@ -5,6 +5,7 @@ import { createSchedulerRoutes } from "./scheduler.js"
import type { SchedulerRunReceipt } from "../services/scheduler-recorded-run.js"
import { pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../services/scheduler-running.js"
import { runSchedulerJobNow } from "../services/scheduler.js"
import { ConfigurationBusyError } from "../services/config-mutation-lock.js"
const receipt: SchedulerRunReceipt = { status: "ok", error: null, result: { v: 1, job: "backups", sampledAt: "2026-10-01T00:00:00Z", due: true, created: 1, failures: 0, pruned: 0 } }
async function setup(patch: Partial<Parameters<typeof createSchedulerRoutes>[0]> = {}) {
const app = Fastify(); let calls = 0
@@ -39,3 +40,13 @@ test("collector or journal rejection remains explicit without a fabricated recei
const { app } = await setup({ run: async () => { throw Error("journal not confirmed; retry may repeat operations") } })
try { const response = await app.inject({ method: "POST", url: "/scheduler/jobs/backups/run-now" }); assert.equal(response.statusCode, 500); assert.match(response.json().error, /retry may repeat/); assert.equal(response.json().result, undefined) } finally { await app.close() }
})
test("configuration contention is distinguishable from an already running job", async () => {
const busy = new ConfigurationBusyError("server")
const { app } = await setup({ run: async () => { throw busy } })
try {
const response = await app.inject({ method: "POST", url: "/scheduler/jobs/uptime_ping/run-now" })
assert.equal(response.statusCode, 409)
assert.deepEqual(response.json(), { code: "CONFIGURATION_BUSY", error: busy.message })
} finally { await app.close() }
})
+4 -4
View File
@@ -51,11 +51,11 @@ return async (app) => {
return reply.send({ ok: result.status === "ok", result, status, ...(statusError ? { statusError } : {}) })
} catch (e) {
const statusCode = (e as Error & { statusCode?: number }).statusCode
if (statusCode === 409) {
const paused = (e as Error & { code?: string }).code === "SCHEDULER_PAUSED"
return reply.status(409).send({ error: paused ? "Планировщик приостановлен для операции с базой" : "Задача уже выполняется" })
}
const msg = e instanceof Error ? e.message : String(e)
if (statusCode === 409) {
const code = (e as Error & { code?: string }).code
return reply.status(409).send({ error: msg, ...(code ? { code } : {}) })
}
return reply.status(500).send({ error: msg })
}
})
+5 -5
View File
@@ -14,10 +14,10 @@ const held = new AsyncLocalStorage<ServerLockCompletion>()
const applicationLease = new AsyncLocalStorage<LockCompletion>()
const collectorLease = new AsyncLocalStorage<LockCompletion>()
const applicationLockKey = "hashtextextended('mm-config:application',0)"
/** Another mutation holds the global configuration lock, or collectors hold it shared while they read routers.
* Same message and 409 as before; the code lets MCP report it instead of a generic device failure. */
export class ConfigurationBusyError extends McpError {
constructor() { super("CONFIGURATION_BUSY", "Глобальная конфигурация изменяется другой операцией", 409) }
constructor(scope: "application" | "server" = "application") {
super("CONFIGURATION_BUSY", scope === "server" ? "Конфигурация сервера временно занята другой операцией" : "Глобальная конфигурация временно занята другой операцией", 409)
}
}
export async function acquireApplicationMutationTransactionLock(client: Pick<PoolClient, "query">): Promise<void> {
@@ -90,7 +90,7 @@ export async function withApplicationCollectorLock<T>(work: () => Promise<T>): P
let acquired = false, unsafe = false
try {
acquired = (await client.query(`SELECT pg_try_advisory_lock_shared(${applicationLockKey}) AS acquired`)).rows[0].acquired
if (!acquired) throw Object.assign(new Error("Глобальная конфигурация изменяется другой операцией"), { statusCode: 409 })
if (!acquired) throw new ConfigurationBusyError()
return await collectorLease.run(context, work)
} finally {
context.active = false
@@ -159,7 +159,7 @@ async function runConfigMutationLock<T>(serverIds: number[], work: () => Promise
}
for (const id of requested) {
const { rows: [row] } = await client.query<{ acquired: boolean }>("SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS acquired", ["mm-config:" + id])
if (!row.acquired) throw Object.assign(new Error("Конфигурация сервера изменяется другой операцией"), { statusCode: 409 })
if (!row.acquired) throw new ConfigurationBusyError("server")
acquired.push(id)
signal.throwIfAborted()
}
@@ -47,7 +47,7 @@ async function getSettingsRow() {
retentionDays: 14,
createdAt: now,
updatedAt: now,
})
}).onConflictDoNothing({ target: internetPathSettings.id })
return (await db.select().from(internetPathSettings).where(eq(internetPathSettings.id, 1)).limit(1))[0]
}
@@ -1,5 +1,4 @@
import {assertOwnedBandwidthSql,prepareOwnedBandwidthState} from "./bandwidth-admission-process.sql-helper.js"
assertOwnedBandwidthSql();await prepareOwnedBandwidthState()
const {pool,closePool}=await import("../db/index.js")
const {applySqlMigrations}=await import("../db/migrate.js")
@@ -12,6 +11,8 @@ try{
const {acceptRoutingMeasurementPoolSql}=await import("../modules/mcp/routing-measurement-pool.sql-helper.js")
const routing=await acceptRoutingMeasurementPoolSql(ids)
console.log("Owned operation lock routing: "+JSON.stringify(routing))
const { checkCatalogReadContention } = await import("./routing-catalog-observation.sql-helper.js")
await checkCatalogReadContention(ids[0])
const {acceptAutomaticSchedulerSql}=await import("./scheduler-automatic-root.sql-helper.js")
console.log("Owned automatic scheduler: "+JSON.stringify(await acceptAutomaticSchedulerSql(ids)))
}finally{
@@ -0,0 +1,146 @@
import assert from "node:assert/strict"
import { AsyncResource } from "node:async_hooks"
import { mock } from "node:test"
import { setTimeout as delay } from "node:timers/promises"
import { assertOwnedBandwidthSql } from "./bandwidth-admission-process.sql-helper.js"
export async function checkCatalogReadContention(serverId: number) {
assertOwnedBandwidthSql()
const { db, pool } = await import("../db/index.js")
const { default: Fastify } = await import("fastify")
const { installDatabaseRequestGate } = await import("../plugins/database-request-gate.js")
const app = Fastify()
installDatabaseRequestGate(app)
let releaseHttp!: () => void
const httpGate = new Promise<void>(resolve => { releaseHttp = resolve })
let activeReads = 0
app.get("/api/test/catalog", async () => { activeReads++; await httpGate; return { ok: true } })
app.put("/api/test/catalog", async () => ({ ok: true }))
await app.ready()
const requests = Promise.all(Array.from({ length: 12 }, () => app.inject({ method: "GET", url: "/api/test/catalog" })))
try {
const until = Date.now() + 5000
while (activeReads < 8) { assert(Date.now() < until, "REST read pool did not fill"); await delay(10) }
assert.equal((await app.inject({ method: "PUT", url: "/api/test/catalog" })).statusCode, 200)
assert.equal(activeReads, 8, "Write admitted while every ordinary REST lease was held by a GET")
} finally {
releaseHttp()
try { assert((await requests).every(response => response.statusCode === 200)) }
finally { await app.close() }
}
const { ensurePartitionFor } = await import("../db/partitions.js")
await ensurePartitionFor(pool, "internet_path_snapshots", "week", new Date())
const { getSettings } = await import("./uptime-collector.js")
const { getTrafficSettings } = await import("./traffic-collector.js")
const { getInternetPathSettings } = await import("./internet-path-collector.js")
const { getServersApiPingSettings } = await import("./servers-rest-ping-collector.js")
for (const [table, get] of [["uptime_settings", getSettings], ["traffic_settings", getTrafficSettings],
["internet_path_settings", getInternetPathSettings], ["servers_api_ping_settings", getServersApiPingSettings]] as const) {
// Two readers see the missing row before either INSERT can commit.
await pool.query(`DELETE FROM ${table} WHERE id=1`)
const gate = await pool.connect()
let results
try {
await gate.query("BEGIN")
await gate.query(`LOCK TABLE ${table} IN SHARE MODE`)
results = Promise.allSettled([get(), get()])
const until = Date.now() + 5000
while ((await gate.query("SELECT count(*)::int AS n FROM pg_locks WHERE relation=$1::regclass AND NOT granted", [table])).rows[0].n < 2) {
assert(Date.now() < until, "Concurrent initializers did not reach INSERT: " + table)
await delay(10)
}
} finally { await gate.query("ROLLBACK"); gate.release() }
const [first, second] = await results
assert(first.status === "fulfilled" && second.status === "fulfilled", table)
assert.deepEqual(first.value, second.value)
}
const { readFilterRulesCatalog } = await import("../routes/filters.js")
const { readRecursiveRoutesForServer, readRecursiveCatalogForServer, applyRecursiveToServer } = await import("../routes/recursive-routes.js")
const { servers } = await import("../db/schema.js")
const { eq } = await import("drizzle-orm")
const { runSchedulerJobNow } = await import("./scheduler.js")
const { MikrotikClient } = await import("./mikrotik.js")
const { coalesceCatalogReads, readCatalogWithObservedCache } = await import("./routing-catalog-observation.js")
const { ConfigurationBusyError, withApplicationCollectorLock, withApplicationMutationLock } = await import("./config-mutation-lock.js")
const [fixture] = await db.select().from(servers).where(eq(servers.id, serverId))
const server = { ...fixture, enabled: true }
let attempts = 0
const poll = coalesceCatalogReads(async () => {
attempts++
if (attempts === 1) throw new Error("RouterOS unavailable")
return attempts
})
const first = poll(server)
assert.equal(first, poll(server))
assert.equal(await poll({ ...server, routingEndpointEpoch: "new-source" }), 2)
await assert.rejects(first, /RouterOS unavailable/)
assert.equal(await poll(server), 3, "Errors must not be cached")
assert.equal(await poll(server), 4, "A later refresh must start a new poll")
const independent = new AsyncResource("other-catalog-request")
const route = { id: "", dstAddress: "192.0.2.1/32", gateway: "192.0.2.2", distance: 1, scope: 30, targetScope: 10,
routingTable: "main", checkGateway: "ping", disabled: false, country: "", comment: "test" }
let native: Record<string, string>[] = [], blocked = 0, hold = false
let resume!: () => void
const gate = new Promise<void>(resolve => { resume = resolve })
const readRouter = async (path: string) => {
if (path === "/interface/gre") return []
assert(["/routing/filter/rule", "/ip/route/print"].includes(path))
const snapshot = path === "/ip/route/print" ? [...native] : []
if (hold) { blocked++; await gate }
return snapshot
}
const get = mock.method(MikrotikClient.prototype, "get", readRouter)
const post = mock.method(MikrotikClient.prototype, "post", readRouter)
const put = mock.method(MikrotikClient.prototype, "put", async (path: string, body: Record<string, string>) => {
assert.equal(path, "/ip/route")
native = [{ ...body, ".id": "*A", static: "true" }]
return { ".id": "*A" }
})
const load = () => Promise.all([readFilterRulesCatalog([server], { source: "live", persistObserved: true }),
readRecursiveCatalogForServer(server), readRecursiveRoutesForServer(server)])
try {
const cold = await Promise.all(Array.from({ length: 24 }, load))
assert(cold.every(([filters, catalog, routes]) => filters[0].live && catalog.live && routes.live))
const revisions = () => pool.query("SELECT section,source FROM config_revisions WHERE server_id=$1 ORDER BY section,created_at", [server.id])
assert.equal((await revisions()).rowCount, 2)
hold = true
const reading = Promise.all(Array.from({ length: 24 }, load))
try {
const until = Date.now() + 5000
while (blocked < 2) { assert(Date.now() < until, "Read traffic blocked before reaching RouterOS"); await delay(10) }
assert.equal(blocked, 2, "72 simultaneous requests share one RouterOS poll per catalogue")
hold = false
for (const job of ["uptime_resources", "uptime_ping", "traffic", "internet_path"]) {
const run = await runSchedulerJobNow(job)
assert.equal(run.status, "ok", job + ": " + run.error)
}
const apply = () => independent.runInAsyncScope(() => applyRecursiveToServer(server, [route], "apply", () =>
independent.runInAsyncScope(() => assert.rejects(withApplicationMutationLock(async () => assert.fail("Overlapping writer")), ConfigurationBusyError))))
let pending!: Promise<PromiseSettledResult<Awaited<ReturnType<typeof apply>>>[]>
await withApplicationCollectorLock(async () => {
pending = Promise.allSettled([apply(), apply()])
await delay(500)
assert.equal(put.mock.callCount(), 0)
})
const results = await pending
assert.equal(results.filter(result => result.status === "fulfilled" && result.value.pushed === 1).length, 1)
assert.equal(results.filter(result => result.status === "rejected" && result.reason.code === "STATE_CONFLICT").length, 1)
} finally { hold = false; resume(); await reading }
for (const [filters, catalog, routes] of await reading) {
assert(filters[0].live && catalog.live && routes.live)
assert.equal(catalog.routes[0].dstAddress, route.dstAddress)
assert.match(routes.routes[0].id, /^\d+$/)
}
assert.equal(put.mock.callCount(), 1)
assert.equal((await revisions()).rowCount, 3, "Late reads must not overwrite the applied revision")
let writes = 0
await assert.rejects(readCatalogWithObservedCache(server, async () => ({ current: false }), async () => {
writes++; throw new ConfigurationBusyError()
}), ConfigurationBusyError)
assert.equal(writes, 1)
await assert.rejects(readCatalogWithObservedCache({ ...server, routingEndpointEpoch: "retired" },
async () => ({ current: false }), async () => assert.fail("Old endpoint wrote to cache")), { code: "STATE_CONFLICT" })
console.log("Catalog contention: 72 simultaneous WebUI reads, two shared catalogue polls, four scheduler jobs, one verified route write and no stale cache publication")
} finally { get.mock.restore(); post.mock.restore(); put.mock.restore(); independent.emitDestroy() }
}
@@ -0,0 +1,87 @@
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)), async () => {
await assertCatalogSource(server)
const latest = await read(true)
return latest.current ? latest : save(latest)
})
} finally { catalogRefreshes.delete(serverId); done() }
}
+1 -1
View File
@@ -216,7 +216,7 @@ export async function runSchedulerJobNow(jobKey: string): Promise<SchedulerRunRe
throw new Error(`Unknown job key: ${jobKey}`)
}
if (!tryBeginSchedulerJob(jobKey)) {
const err = new Error(isSchedulerJobsPaused() ? "Планировщик приостановлен для операции с базой" : "Job already running")
const err = new Error(isSchedulerJobsPaused() ? "Планировщик приостановлен для операции с базой" : "Задача уже выполняется")
;(err as Error & { statusCode?: number }).statusCode = 409
if (isSchedulerJobsPaused()) (err as Error & { code?: string }).code = "SCHEDULER_PAUSED"
throw err
@@ -20,7 +20,7 @@ async function getSettingsRow() {
intervalSec: 120,
createdAt: now,
updatedAt: now,
})
}).onConflictDoNothing({ target: serversApiPingSettings.id })
return (await db.select().from(serversApiPingSettings).where(eq(serversApiPingSettings.id, 1)).limit(1))[0]
}
+1 -1
View File
@@ -80,7 +80,7 @@ async function getSettingsRow() {
...trafficSettingsDefaults,
createdAt: now,
updatedAt: now,
})
}).onConflictDoNothing({ target: trafficSettings.id })
return readSettingsRow()
}
+1 -1
View File
@@ -72,7 +72,7 @@ export async function getSettings() {
retentionDays: 14,
createdAt: now,
updatedAt: now,
})
}).onConflictDoNothing({ target: uptimeSettings.id })
return (await db.select().from(uptimeSettings).where(eq(uptimeSettings.id, 1)).limit(1))[0]
}
+3 -1
View File
@@ -71,7 +71,9 @@ test("Filters: чтение под общей блокировкой повто
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
await page.route("**/api/**", async route => {
const { pathname, searchParams } = new URL(route.request().url())
const conflict = () => route.fulfill({ status: 409, json: { error: "Глобальная конфигурация изменяется другой операцией" } })
const conflict = () => route.fulfill({ status: 409, json: lock === "held"
? { code: "CONFIGURATION_BUSY", error: "Конфигурация временно занята другой операцией" }
: { error: "Глобальная конфигурация изменяется другой операцией" } })
if (pathname === "/api/filters/rules" && searchParams.has("serverId")) {
if (lock === "held" || lock === "brief") {
conflicts++