Files
MikrotikManager/backend/src/services/ospf-cost-optimization.ts
T

178 lines
18 KiB
TypeScript

import { readEditableOspfTemplates } from "./ospf-optimizer-plan.js"
import { z } from "zod"
import { readOspfLinkCatalog, resolveOspfLinkOwner, type OspfLinkCatalog } from "./ospf-link-catalog.js"
import { readOspfIdentityCatalog } from "./ospf-identity-catalog.js"
import { observedBoolean } from "./ospf-observed-values.js"
import { ospfCostConnectionProof } from "./ospf-template-cost-write.js"
import { readRoutingObservations } from "../modules/mcp/routing-observations.js"
import { assertRoutingChecksFresh, latestRoutingMetric } from "../modules/mcp/routing-observations-model.js"
import { createRoutingSourceContext, readRoutingEndpoints } from "../modules/mcp/routing-observation-source.js"
import { fresh } from "../modules/mcp/routing-model.js"
import { fingerprint, McpError } from "../modules/mcp/security.js"
import { configurationRows, readRosSnapshot, resourceById, routerClient, type RosSnapshot } from "../modules/mcp/resources.js"
import { ospfTable, requireOspfBfdSession } from "../modules/mcp/ospf-health.js"
import type { ChangeEvidence } from "../modules/mcp/action-types.js"
import { addOspfPrefixListDependencies, ospfInterfaceResources, resolveOspfInterfaceSelectors } from "../modules/mcp/routing-dependencies.js"
export interface OspfRank { id: string; interface: string; currentCost: number; proposedCost: number; score: number; pingMs: number | null; lossPct: number | null; dlMbps: number | null; ulMbps: number | null; observationId: string; bandwidthObservationId: string | null; peerId: number; validUntil: string }
/** Seal a current source-bound snapshot only if it still matches the catalog
* used for ranking/identity resolution. Never attach new provenance to old rows. */
export async function captureOspfOptimizationSnapshot(serverId: number, resource: string, payload: unknown, beforeRead: () => Promise<unknown>, read: typeof readRosSnapshot = readRosSnapshot): Promise<RosSnapshot> {
const originalFingerprint = fingerprint(configurationRows(resourceById(resource), payload))
const current = await read(serverId, resource, beforeRead)
if (current.fingerprint !== originalFingerprint) throw new McpError("STATE_CONFLICT", "Каталог OSPF изменился после построения рейтинга или графа зависимостей", 409)
return current
}
export async function buildOspfCostOptimizationEvidence(input: Record<string, unknown>, allowedServerIds: number[], authorize: () => Promise<unknown> = async () => {}): Promise<ChangeEvidence & { before: { ranking: OspfRank[] } }> {
if (!allowedServerIds.includes(Number(input.serverId))) throw new McpError("SERVER_DENIED", "Сервер оптимизации OSPF вне разрешённой области", 403)
await authorize()
const family = z.enum(["ipv4", "ipv6"]).parse(input.family)
const candidateIds = [...new Set(allowedServerIds)].sort((a, b) => a - b)
const sourceContext = await createRoutingSourceContext(await readRoutingEndpoints(candidateIds))
// App monitoring disabled does not prove that a router stopped owning its ID.
if (fingerprint(sourceContext.expected.map(row => row.serverId)) !== fingerprint(candidateIds)) throw new McpError("DEVICE_UNAVAILABLE", "Не все источники графа OSPF доступны и включены; отключение опроса не доказывает отсутствие владельца Router ID", 409)
const beforeRead = async () => { await authorize(); await sourceContext.assertCurrent() }
await beforeRead()
const serverId = Number(input.serverId), { client, server } = await routerClient(serverId), expectedServerProof = await ospfCostConnectionProof(serverId, server), snapshot = await readRosSnapshot(serverId, "ospf_template", beforeRead)
await beforeRead()
const neighbors = await client.getOspfNeighbors(), primaryIdentity = await readOspfIdentityCatalog(client, beforeRead), instances = primaryIdentity.instances
await beforeRead()
const areas = await client.getOspfAreas()
const selectedTemplates = snapshot.rows.filter((template): template is typeof template & { ".id": string } => {
if (typeof template[".id"] !== "string" || typeof template.disabled !== "string" || typeof template.passive !== "string") return false
const area = areas.find(area => area.name === template.area || area[".id"] === template.area), instance = instances.find(instance => instance.name === area?.instance || instance[".id"] === area?.instance)
return !!instance && observedBoolean(template.disabled) === false && observedBoolean(template.passive) === false && observedBoolean(instance.disabled) === false && observedBoolean(area?.disabled) === false && String(instance.version) === (family === "ipv4" ? "2" : "3") && ospfTable(instance) === input.table
})
const templateContext = (template: { id: string; interface: string }) => {
const native = snapshot.rows.find(row => row[".id"] === template.id), area = areas.find(area => area.name === native?.area || area[".id"] === native?.area), instance = instances.find(instance => instance.name === area?.instance || instance[".id"] === area?.instance)
const matches = instance ? neighbors.filter(neighbor => neighbor.interface === template.interface && [instance.name, instance[".id"]].includes(neighbor.instance) && String(neighbor.state).toLowerCase() === "full") : []
return { instance, matches }
}
const selectorSnapshots = [snapshot]
const selectorObjects = new Map<string, ChangeEvidence["objects"]>()
const templateInterfaces = new Map<string, Set<string>>()
const affected = new Map<string, number>()
const scopedTemplates = []
const knownInterfaces = new Set(neighbors.map(neighbor => neighbor.interface).filter((name): name is string => typeof name === "string"))
for (const template of selectedTemplates) {
if (typeof template.interfaces !== "string" || !template.interfaces.trim()) throw new McpError("MEASUREMENT_UNKNOWN", "Область действия активного шаблона OSPF не подтверждена", 409)
const objects: ChangeEvidence["objects"] = []
const names = await resolveOspfInterfaceSelectors(serverId, template.interfaces.split(",").map(name => name.trim()), knownInterfaces, selectorSnapshots, objects, beforeRead)
for (const name of names) affected.set(name, (affected.get(name) ?? 0) + 1)
if (!names.size || (template.networks !== undefined && (typeof template.networks !== "string" || template.networks.trim()))) continue
const [name] = names
templateInterfaces.set(template[".id"], names)
if (objects.length) selectorObjects.set(template[".id"], objects)
scopedTemplates.push({ ...template, interfaces: name })
}
const templates = readEditableOspfTemplates(scopedTemplates.filter(template =>
[...templateInterfaces.get(template[".id"])!].every(name => affected.get(name) === 1),
)).flatMap(template => [...templateInterfaces.get(template.id)!].map(name => ({ ...template, interface: name }))).filter(template => {
const { instance, matches } = templateContext(template)
return instance && ospfTable(instance) === input.table && matches.length === 1 && matches[0][".id"]
})
const eligibleIds = new Set(templates.map(template => template.id))
const bfdFlags = new Map<string, boolean>()
for (const template of selectedTemplates.filter(template => eligibleIds.has(template[".id"]))) {
const useBfd = template["use-bfd"]
let enabled = typeof useBfd === "string" ? observedBoolean(useBfd) : null
if (useBfd === undefined) {
await beforeRead()
const value = await client.post<{ ret?: unknown }>("/routing/ospf/interface-template/get", { ".id": template[".id"], "value-name": "use-bfd" })
enabled = typeof value?.ret === "string" ? observedBoolean(value.ret) : null
}
if (enabled === null) throw new McpError("MEASUREMENT_UNKNOWN", "Не подтверждён use-bfd шаблона OSPF", 409)
bfdFlags.set(template[".id"], enabled)
}
await beforeRead()
const bfdRequired = [...bfdFlags.values()].some(Boolean), bfdSessions = bfdRequired ? await client.getBfdSessions() : []
const capture = (id: number, resource: string, payload: unknown) => captureOspfOptimizationSnapshot(id, resource, payload, beforeRead)
const ownerSnapshots = new Map<number, RosSnapshot>()
const identityFingerprints = new Map<number, string>(), links = new Map<number, OspfLinkCatalog>()
let ownerRows = 0, ownerBytes = 0
for (const id of candidateIds) {
await beforeRead()
const link = await readOspfLinkCatalog(id === serverId ? client : (await routerClient(id)).client, family, beforeRead, id === serverId ? { identity: primaryIdentity, neighbors } : undefined)
ownerRows += link.rows; ownerBytes += link.bytes
if (ownerRows > 10000 || ownerBytes > 1048576) throw new McpError("STATE_UNAVAILABLE", "Граф владельцев OSPF превышает 10000 строк или 1 МиБ", 409)
links.set(id, link); ownerSnapshots.set(id, await capture(id, "ospf_instance", link.identity.raw)); identityFingerprints.set(id, link.fingerprint)
}
await beforeRead()
const observations = await readRoutingObservations(allowedServerIds), now = Date.now()
const measured = templates.flatMap(template => {
const { instance, matches } = templateContext(template)
if (!instance || ospfTable(instance) !== input.table) return []
if (matches.length !== 1 || !matches[0][".id"]) return []
const owner = resolveOspfLinkOwner(serverId, links.get(serverId)!, instance[".id"], matches[0][".id"], [...links].map(([id, catalog]) => ({ serverId: id, catalog })))
if (!owner) return []
const peer = owner.serverId
const linkObservations = observations.filter(row => row.srcServerId === serverId && row.dstServerId === peer && row.srcInterface === template.interface && row.dstInterface === owner.interface && row.family === input.family && row.table === input.table)
const ping = latestRoutingMetric(linkObservations, "pingAt")
if (!ping?.contextVerified || !fresh(ping.pingAt, 300, now) || ping.pingMs === null || ping.lossPct === null || ping.lossPct > Number(input.maxLossPct)) return []
const pingWeight = Number(input.pingWeight) / 100
const bandwidth = pingWeight === 1 ? undefined : latestRoutingMetric(linkObservations, "bandwidthAt")
if (pingWeight !== 1 && (!bandwidth?.contextVerified || !fresh(bandwidth.bandwidthAt, 3600, now) || bandwidth.dlMbps === null || bandwidth.ulMbps === null)) return []
const score = pingWeight * Math.max(0, 100 - ping.pingMs * 0.6) + (1 - pingWeight) * Math.min(100, ((bandwidth?.dlMbps ?? 0) + (bandwidth?.ulMbps ?? 0)) / 18)
const pingUntil = Date.parse(ping.pingAt!) + 300000
const bandwidthUntil = bandwidth ? Date.parse(bandwidth.bandwidthAt!) + 3600000 : Infinity
const validUntil = Math.min(pingUntil, bandwidthUntil)
const bfd = bfdFlags.get(template.id) ? requireOspfBfdSession(bfdSessions as unknown as Record<string, unknown>[], matches[0].address, template.interface, String(input.table)) : null
return [{ template, owner, score, ping, bandwidth, pingUntil, bandwidthUntil, validUntil, peerId: peer, neighborId: String(matches[0][".id"]), bfd }]
})
const measuredCounts = new Map<string, number>()
for (const item of measured) measuredCounts.set(item.template.id, (measuredCounts.get(item.template.id) ?? 0) + 1)
const ranked = measured.filter(item => measuredCounts.get(item.template.id) === templateInterfaces.get(item.template.id)!.size)
.sort((a, b) => b.score - a.score || a.template.interface.localeCompare(b.template.interface))
if (!ranked.length) throw new McpError("MEASUREMENT_UNKNOWN", "Нет однозначных шаблонов и свежих измерений нужного instance/family/VRF", 409)
const optimalCost = (index: number) => index < Number(input.ecmpPaths) ? 10 : (index - Number(input.ecmpPaths) + 2) * 10
const before = { ranking: ranked.map((item, index) => ({ id: item.template.id, interface: item.template.interface, currentCost: item.template.cost, proposedCost: optimalCost(index), score: item.score, pingMs: item.ping.pingMs, lossPct: item.ping.lossPct, dlMbps: item.bandwidth?.dlMbps ?? null, ulMbps: item.bandwidth?.ulMbps ?? null, observationId: item.ping.id, bandwidthObservationId: item.bandwidth?.id ?? null, peerId: item.peerId, peerInstance: item.owner.instanceId, peerVrf: item.owner.vrf, peerInterface: item.owner.interface, validUntil: new Date(item.validUntil).toISOString() })) }
const costsByTemplate = new Map<string, { current: number; proposed: number }>()
for (const item of before.ranking) {
const previous = costsByTemplate.get(item.id)
if (previous && previous.proposed !== item.proposedCost) {
throw new McpError("STATE_CONFLICT", "Для интерфейсов одного шаблона OSPF рассчитаны разные cost", 409)
}
costsByTemplate.set(item.id, { current: item.currentCost, proposed: item.proposedCost })
}
const steps: ChangeEvidence["steps"] = []
for (const [id, cost] of costsByTemplate) {
if (cost.current !== cost.proposed) steps.push({ kind: "ros", step: { serverId, resource: "ospf_template", action: "update", id, fields: { cost: String(cost.proposed) }, expectedCost: cost.current, expectedServerProof } })
}
await beforeRead()
const dependencyIds = candidateIds
const dependencySnapshots = candidateIds.filter(id => id !== serverId).map(id => ownerSnapshots.get(id)!)
if (dependencySnapshots.some(value => !value)) throw new McpError("STATE_UNAVAILABLE", "Не подтверждены OSPF instances соседнего устройства", 409)
const healthChecks: NonNullable<ChangeEvidence["healthChecks"]> = ranked.map(item => ({ serverId, resource: "ospf_neighbor", id: item.neighborId, field: "state", identity: { interface: item.template.interface, instance: String(neighbors.find(row => row[".id"] === item.neighborId)!.instance) } }))
for (const item of ranked) if (item.bfd) healthChecks.push({ serverId, resource: "bfd_session", id: String(item.bfd[".id"]), field: "bfd-up", identity: Object.fromEntries(["remote-address", "local-address", "vrf", "interface"].filter(key => typeof item.bfd![key] === "string").map(key => [key, String(item.bfd![key])])) })
const bfdSnapshots = bfdRequired ? [await readRosSnapshot(serverId, "bfd_configuration", beforeRead), await capture(serverId, "bfd_session", bfdSessions)] : []
const objects: ChangeEvidence["objects"] = ranked.flatMap(item => [{ kind: "ospf_template", id: item.template.id, serverId }, ...selectorObjects.get(item.template.id) ?? []])
if (family === "ipv6") {
const lists = new Set(selectedTemplates.filter(template => costsByTemplate.has(template[".id"])).map(template => template["prefix-list"]))
for (const list of lists) await addOspfPrefixListDependencies(serverId, undefined, list, selectorSnapshots, objects, beforeRead)
}
const namedInterfaces = new Set(ranked.filter(item => selectorObjects.has(item.template.id)).map(item => item.template.interface))
if (namedInterfaces.size) for (const kind of ospfInterfaceResources) {
const dependency = await readRosSnapshot(serverId, kind, beforeRead, snapshot.sourceProof)
selectorSnapshots.push(dependency)
for (const row of dependency.rows) {
if (typeof row.name !== "string" || !namedInterfaces.has(row.name)) continue
if (typeof row[".id"] !== "string" || !/^\*[a-z0-9]+$/i.test(row[".id"])) throw new McpError("STATE_UNAVAILABLE", "Не подтверждён ID интерфейса OSPF", 409)
objects.push({ kind, id: row[".id"], serverId })
}
}
const uniqueObjects = [...new Map(objects.map(object => [`${object.kind}/${object.id}`, object])).values()]
if (uniqueObjects.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Слишком много защищаемых зависимостей OSPF", 409)
const observationChecks = ranked.flatMap<NonNullable<ChangeEvidence["observationChecks"]>[number]>(item => {
const link = { srcServerId: serverId, dstServerId: item.peerId, srcInterface: item.template.interface, dstInterface: item.owner.interface, family, table: String(input.table) }
const ping = { ...link, id: item.ping.id, metric: "pingAt" as const, fingerprint: fingerprint(item.ping), validUntil: new Date(item.pingUntil).toISOString() }
if (!item.bandwidth) return [ping]
return [ping, { ...link, id: item.bandwidth.id, metric: "bandwidthAt" as const, fingerprint: fingerprint(item.bandwidth), validUntil: new Date(item.bandwidthUntil).toISOString() }]
})
const snapshots = [...selectorSnapshots, await capture(serverId, "ospf_neighbor", neighbors), await capture(serverId, "ospf_instance", primaryIdentity.raw), await capture(serverId, "ospf_area", areas), ...dependencySnapshots, ...bfdSnapshots]
await beforeRead()
assertRoutingChecksFresh(observationChecks)
return { before, observationChecks, ospfOwnerGraph: { family, sourceSecretProofs: sourceContext.expected, instances: [...ownerSnapshots.values()].map(row => ({ serverId: row.serverId, fingerprint: fingerprint({ native: row.fingerprint, identity: identityFingerprints.get(row.serverId) }) })) }, target: { scope: "servers", serverIds: dependencyIds }, objects: uniqueObjects, snapshots, steps, healthChecks, validUntil: new Date(Math.min(...ranked.map(item => item.validUntil))).toISOString(), warnings: ["Рейтинг локальных интерфейсов не доказывает глобальный оптимум.", "Неизвестные шаблоны не меняются.", "Full выбранных соседств и Up включённых BFD-сессий проверяются до и после cost-записей. Сквозная связность требует контрольных проб; после истечения измерений нужен новый план."], requiresHuman: true }
}