From ee6fd675ac84f69e6fd21bbe80b60362523d7415 Mon Sep 17 00:00:00 2001 From: Denozordec Date: Tue, 24 Nov 2026 12:46:31 +0700 Subject: [PATCH] =?UTF-8?q?fix(routing):=20=D1=83=D1=81=D1=82=D1=80=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D1=82=D1=8C=20=D0=BA=D0=BE=D0=BD=D1=84=D0=BB=D0=B8?= =?UTF-8?q?=D0=BA=D1=82=D1=8B=20=D1=87=D1=82=D0=B5=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D1=84=D0=B8=D0=BB=D1=8C=D1=82=D1=80=D0=BE=D0=B2=20=D0=B8=20?= =?UTF-8?q?=D0=BC=D0=B0=D1=80=D1=88=D1=80=D1=83=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/index.ts | 2 + .../src/modules/mcp/database-request-lease.ts | 19 ++- .../modules/mcp/manual-uptime-actions.test.ts | 1 + backend/src/plugins/database-request-gate.ts | 2 +- backend/src/routes/filters.ts | 34 ++-- backend/src/routes/internet-exchange.ts | 2 +- backend/src/routes/recursive-routes.ts | 66 +++++--- backend/src/routes/scheduler.test.ts | 11 ++ backend/src/routes/scheduler.ts | 8 +- backend/src/services/config-mutation-lock.ts | 10 +- .../src/services/internet-path-collector.ts | 2 +- .../operation-config-lock-lease.sql.test.ts | 3 +- .../routing-catalog-observation.sql-helper.ts | 146 ++++++++++++++++++ .../services/routing-catalog-observation.ts | 87 +++++++++++ backend/src/services/scheduler.ts | 2 +- .../services/servers-rest-ping-collector.ts | 2 +- backend/src/services/traffic-collector.ts | 2 +- backend/src/services/uptime-collector.ts | 2 +- tests/e2e/filters-read-race.spec.ts | 4 +- 19 files changed, 344 insertions(+), 61 deletions(-) create mode 100644 backend/src/services/routing-catalog-observation.sql-helper.ts create mode 100644 backend/src/services/routing-catalog-observation.ts diff --git a/backend/src/index.ts b/backend/src/index.ts index 33c14be0..878fb8ad 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -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 }) }) diff --git a/backend/src/modules/mcp/database-request-lease.ts b/backend/src/modules/mcp/database-request-lease.ts index e49a7fc4..101888a3 100644 --- a/backend/src/modules/mcp/database-request-lease.ts +++ b/backend/src/modules/mcp/database-request-lease.ts @@ -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>; signal: AbortSignal }>() @@ -28,19 +30,24 @@ export function withActiveDatabaseRequest(run: (signal: AbortSignal) => Promi return child } -export function withMcpDatabaseRequest(run: () => Promise): Promise { return withDatabaseRequest(run, true) } -export function withDatabaseApiRequest(run: () => Promise): Promise { return withDatabaseRequest(run, false) } +export function withMcpDatabaseRequest(run: () => Promise): Promise { return withDatabaseRequest(run, leases) } +export function withDatabaseApiRequest(run: () => Promise, mutation = false): Promise { + // 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 { - return withDatabaseRequest(async () => {}, false, false, true) + return withDatabaseRequest(async () => {}, apiLeases, true) } -async function withDatabaseRequest(run: () => Promise, mcp: boolean, detached = false, starting = false): Promise { +async function withDatabaseRequest(run: () => Promise, pool: typeof apiLeases, starting = false): Promise { 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(run: () => Promise): Promise< /** Detached jobs keep their own lease through terminal persistence after the HTTP response. */ export function withDetachedDatabaseApiRequest(run: () => Promise): Promise { - return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, false, true))) + return context.exit(() => sharedDatabaseGate.request(() => withDatabaseRequest(run, detachedApiLeases))) } diff --git a/backend/src/modules/mcp/manual-uptime-actions.test.ts b/backend/src/modules/mcp/manual-uptime-actions.test.ts index ce1c2168..8f3f5a75 100644 --- a/backend/src/modules/mcp/manual-uptime-actions.test.ts +++ b/backend/src/modules/mcp/manual-uptime-actions.test.ts @@ -94,6 +94,7 @@ test("actual collector initial settings failures release resource/ping/group bus const modules:Record={"../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:RecordRecord|Promise>>={} + modules["./config-mutation-lock.js"] = { withApplicationCollectorLock: (collect: () => Promise) => 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"]){ diff --git a/backend/src/plugins/database-request-gate.ts b/backend/src/plugins/database-request-gate.ts index 168d60d6..9503482d 100644 --- a/backend/src/plugins/database-request-gate.ts +++ b/backend/src/plugins/database-request-gate.ts @@ -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 { diff --git a/backend/src/routes/filters.ts b/backend/src/routes/filters.ts index c40a1951..9cb77da3 100644 --- a/backend/src/routes/filters.ts +++ b/backend/src/routes/filters.ts @@ -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 | 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) }) } diff --git a/backend/src/routes/internet-exchange.ts b/backend/src/routes/internet-exchange.ts index 86871f38..95289a05 100644 --- a/backend/src/routes/internet-exchange.ts +++ b/backend/src/routes/internet-exchange.ts @@ -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 не подтверждено. Обновите данные и проверьте план." diff --git a/backend/src/routes/recursive-routes.ts b/backend/src/routes/recursive-routes.ts index 4bc1d04f..f903d3fc 100644 --- a/backend/src/routes/recursive-routes.ts +++ b/backend/src/routes/recursive-routes.ts @@ -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) => void | Promise, ): 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 = recursiveDefaults, options: { persistObserved?: boolean } = {}) { - const read = async () => { +type RecursiveReadDependencies = Pick + +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>) => { + 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 = 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 = {}): FastifyPluginAsyncZod { @@ -218,6 +231,7 @@ export function createRecursiveRoutes(overrides: Partial[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() } +}) diff --git a/backend/src/routes/scheduler.ts b/backend/src/routes/scheduler.ts index d04bfae5..fe0a59ec 100644 --- a/backend/src/routes/scheduler.ts +++ b/backend/src/routes/scheduler.ts @@ -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 }) } }) diff --git a/backend/src/services/config-mutation-lock.ts b/backend/src/services/config-mutation-lock.ts index ee6b58d3..39c3d217 100644 --- a/backend/src/services/config-mutation-lock.ts +++ b/backend/src/services/config-mutation-lock.ts @@ -14,10 +14,10 @@ const held = new AsyncLocalStorage() const applicationLease = new AsyncLocalStorage() const collectorLease = new AsyncLocalStorage() 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): Promise { @@ -90,7 +90,7 @@ export async function withApplicationCollectorLock(work: () => Promise): 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(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() } diff --git a/backend/src/services/internet-path-collector.ts b/backend/src/services/internet-path-collector.ts index 98cfc0ba..7b22d588 100644 --- a/backend/src/services/internet-path-collector.ts +++ b/backend/src/services/internet-path-collector.ts @@ -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] } diff --git a/backend/src/services/operation-config-lock-lease.sql.test.ts b/backend/src/services/operation-config-lock-lease.sql.test.ts index 6206adbf..1ab5d7e9 100644 --- a/backend/src/services/operation-config-lock-lease.sql.test.ts +++ b/backend/src/services/operation-config-lock-lease.sql.test.ts @@ -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{ diff --git a/backend/src/services/routing-catalog-observation.sql-helper.ts b/backend/src/services/routing-catalog-observation.sql-helper.ts new file mode 100644 index 00000000..ed3cb184 --- /dev/null +++ b/backend/src/services/routing-catalog-observation.sql-helper.ts @@ -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(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[] = [], blocked = 0, hold = false + let resume!: () => void + const gate = new Promise(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) => { + 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>>[]> + 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() } +} diff --git a/backend/src/services/routing-catalog-observation.ts b/backend/src/services/routing-catalog-observation.ts new file mode 100644 index 00000000..8a436e14 --- /dev/null +++ b/backend/src/services/routing-catalog-observation.ts @@ -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(poll: (server: Server) => Promise) { + const pending = new Map>() + 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(lock: (run: () => Promise) => Promise, run: () => Promise) { + 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(server: Server, section: ConfigSection, run: () => Promise) { + 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>() +export async function readCatalogWithObservedCache( + server: Server, read: (fresh: boolean) => Promise, save: (observed: T) => Promise, +): Promise { + 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() } +} diff --git a/backend/src/services/scheduler.ts b/backend/src/services/scheduler.ts index a3b43f4a..ec53c8d6 100644 --- a/backend/src/services/scheduler.ts +++ b/backend/src/services/scheduler.ts @@ -216,7 +216,7 @@ export async function runSchedulerJobNow(jobKey: string): Promise 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++