Files
MikrotikManager/backend/src/services/ospf-state-read.ts
T

101 lines
6.5 KiB
TypeScript

import type { ServerRow } from "../modules/servers/repository/servers-repository.js"
import { MikrotikClient } from "./mikrotik.js"
import { readOspfCatalogRaw, readOspfCoreRaw, readOspfRoutesRaw, type OspfCatalogCollections } from "./ospf-catalog-poll.js"
import { buildAreaMap, buildObservedAreaMap, parseNeighbors, parseInterfaces, parseInstances, parseOspfRoutes, parseBfdSessions, parseBfdCatalogSessions, parseCatalogNeighbors, parseCatalogInterfaces, parseCatalogInstances, parseCatalogRoutes } from "./ospf-read-model.js"
import { observedBoolean, observedInteger } from "./ospf-observed-values.js"
function assertSource(server: ServerRow) {
if (server.enabled === false) throw new Error("Сервер выключен. Опрос OSPF/BFD не выполнялся")
}
function validateRows(rows: unknown): asserts rows is (Record<string, unknown> & { ".id": string })[] {
if (!Array.isArray(rows) || rows.length > 10000 || rows.some(row => !row || typeof row !== "object" || Array.isArray(row) || typeof row[".id"] !== "string" || !row[".id"].trim()) || new Set(rows.map(row => row[".id"])).size !== rows.length) throw new Error("Недостоверные идентификаторы OSPF/BFD")
}
function observeCore(server: ServerRow, { neighbors, areas, ifaceTemplates, instances }: Awaited<ReturnType<typeof readOspfCoreRaw>>) {
const areaMap = buildObservedAreaMap(areas)
return {
neighbors: parseCatalogNeighbors(server, neighbors, areaMap), interfaces: parseCatalogInterfaces(server, ifaceTemplates, areas, instances, areaMap),
instances: parseCatalogInstances(server, instances),
areas: areas.map(area => ({ id: area[".id"], serverId: server.id, name: area.name, areaId: area["area-id"]?.trim() || null, type: area.type?.trim() || null, disabled: observedBoolean(area.disabled), inactive: observedBoolean(area.inactive), instance: area.instance })),
}
}
/** One poll and shared models for the legacy REST views and nullable MCP DTOs.
* Compatibility defaults stay in legacy only; observed never fabricates them. */
export async function readOspfStateForServer(server: ServerRow, client?: MikrotikClient) {
assertSource(server)
const raw = await readOspfCatalogRaw(client ?? MikrotikClient.fromServer(server))
for (const rows of Object.values(raw)) validateRows(rows)
const { neighbors, areas, ifaceTemplates, instances, bfdSessions, ipRoutes } = raw, areaMap = buildAreaMap(areas)
const legacy = {
neighbors: parseNeighbors(server, neighbors, areaMap), interfaces: parseInterfaces(server, ifaceTemplates, areas, instances, areaMap),
instances: parseInstances(server, instances), bfdSessions: parseBfdSessions(server, bfdSessions), routes: parseOspfRoutes(server, ipRoutes),
areas: areas.map(area => ({ name: area.name, areaId: area["area-id"] ?? "0.0.0.0", type: area.type, disabled: area.disabled === "true", inactive: area.inactive === "true", instance: area.instance })),
}
const observed = {
...observeCore(server, raw), bfdSessions: parseBfdCatalogSessions(server, bfdSessions), routes: parseCatalogRoutes(server, ipRoutes),
}
return { legacy, observed }
}
const runtimeStates = new Set(["down", "loopback", "ptp", "passive", "waiting", "standby", "dr-other", "bdr", "dr"])
const runtimeFields = ".id,interface,address,area,type,state,dr,bdr,cost,priority,dynamic,disabled,passive,use-bfd"
const lsaFields = ".id,id,instance,area,type,originator,sequence,age,self-originated,flushing"
async function readOspfLsaMetadata(client: MikrotikClient, serverId: number, signal?: AbortSignal) {
const rows = await client.get<unknown>(`/routing/ospf/lsa?.proplist=${lsaFields}`, 10_000, signal, 1_048_576)
validateRows(rows)
return rows.map(row => {
const text = (key: string) => typeof row[key] === "string" ? row[key].trim() || null : null
return {
id: row[".id"], serverId, linkStateId: text("id"), instance: text("instance"), area: text("area"),
type: text("type"), originator: text("originator"), sequence: text("sequence"),
ageSeconds: observedInteger(text("age") ?? undefined),
selfOriginated: observedBoolean(text("self-originated") ?? undefined), flushing: observedBoolean(text("flushing") ?? undefined),
}
})
}
export async function readOspfMcpStateForServer(server: ServerRow, signal?: AbortSignal, includeLsas = false) {
assertSource(server)
signal?.throwIfAborted()
const client = MikrotikClient.fromServer(server)
const runtimeRead = async () => {
const rows = await client.get<unknown>(`/routing/ospf/interface?.proplist=${runtimeFields}`, 10_000, signal, 1_048_576)
validateRows(rows)
return rows.map(row => {
const text = (key: string) => typeof row[key] === "string" ? row[key].trim() || null : null
const state = text("state")
return {
id: row[".id"], serverId: server.id, interface: text("interface"), address: text("address"), area: text("area"),
type: text("type"), state: state && runtimeStates.has(state) ? state : null, dr: text("dr"), bdr: text("bdr"),
cost: observedInteger(text("cost") ?? undefined), priority: observedInteger(text("priority") ?? undefined, 0, 255),
dynamic: observedBoolean(text("dynamic") ?? undefined), disabled: observedBoolean(text("disabled") ?? undefined),
passive: observedBoolean(text("passive") ?? undefined), useBfd: observedBoolean(text("use-bfd") ?? undefined),
}
})
}
const [core, runtimeInterfaces, bfdSessions, routes, lsas] = await Promise.all([
readOspfCoreRaw(client),
runtimeRead().catch(() => null),
client.getBfdSessions().then(rows => { validateRows(rows); return parseBfdCatalogSessions(server, rows) }).catch(() => null),
readOspfRoutesRaw(client).then(rows => { validateRows(rows); return parseCatalogRoutes(server, rows) }).catch(() => null),
includeLsas ? readOspfLsaMetadata(client, server.id, signal).catch(() => null) : undefined,
])
signal?.throwIfAborted()
for (const rows of Object.values(core)) validateRows(rows)
return { ...observeCore(server, core), runtimeInterfaces, bfdSessions, routes, ...(lsas === undefined ? {} : { lsas }) }
}
export async function readBfdStateForServer(server: ServerRow) {
assertSource(server)
const raw = await MikrotikClient.fromServer(server).getBfdSessions()
validateRows(raw)
return { legacy: parseBfdSessions(server, raw), observed: parseBfdCatalogSessions(server, raw) }
}
export async function readOspfCatalogForServer(server: ServerRow): Promise<OspfCatalogCollections> {
const { areas: _areas, ...collections } = (await readOspfStateForServer(server)).observed
return collections
}