63 lines
3.6 KiB
TypeScript
63 lines
3.6 KiB
TypeScript
import type { z } from "zod"
|
|
import type { recursiveInputRowSchema } from "./recursive-route-validation.js"
|
|
|
|
export type RecursiveIdentityRow = Omit<z.infer<typeof recursiveInputRowSchema>, "checkGateway"> & { checkGateway: string }
|
|
export type RecursiveIdentityMode = "observed" | "apply" | "copy" | "rollback"
|
|
|
|
// RouterOS may spell a host route with or without /32. Keep host bits for other
|
|
// prefixes: BGP filters derive their gateway from the literal destination IP.
|
|
function destination(value: string) {
|
|
const [ip, suffix] = value.split("/")
|
|
const bits = suffix === undefined ? 32 : Number(suffix)
|
|
const address = ip.split(".").reduce((n, octet) => n * 256 + Number(octet), 0)
|
|
return `${address}/${bits}`
|
|
}
|
|
function prefix(row: RecursiveIdentityRow) { return JSON.stringify([destination(row.dstAddress), row.routingTable]) }
|
|
function exact(row: RecursiveIdentityRow) {
|
|
return JSON.stringify([prefix(row), row.gateway, row.distance, row.scope, row.targetScope, row.checkGateway, row.comment, row.disabled])
|
|
}
|
|
|
|
/** Match logical routes without letting observation or RouterOS recreation change
|
|
* rec:<id> references. Ambiguous changes require explicit DB IDs from the editor. */
|
|
export function planRecursiveIdentities(
|
|
current: RecursiveIdentityRow[], desired: RecursiveIdentityRow[],
|
|
referenced: ReadonlySet<string>, mode: RecursiveIdentityMode,
|
|
) {
|
|
const available = new Map(current.map(row => [row.id, row]))
|
|
const matches = new Map<number, RecursiveIdentityRow>()
|
|
const bind = (index: number, row: RecursiveIdentityRow) => {
|
|
matches.set(index, row); available.delete(row.id)
|
|
}
|
|
if (mode === "apply") desired.forEach((row, index) => {
|
|
if (!/^\d+$/.test(row.id)) return
|
|
const old = available.get(row.id)
|
|
if (!old) throw new Error("Идентификатор маршрута отсутствует на выбранном сервере или повторяется")
|
|
bind(index, old)
|
|
})
|
|
// Match unchanged entries before considering changed next hops or priorities.
|
|
desired.forEach((row, index) => {
|
|
if (matches.has(index)) return
|
|
const candidates = [...available.values()].filter(old => exact(old) === exact(row))
|
|
if (new Set(candidates.map(old => old.country)).size > 1) throw new Error("Неоднозначные метки одинаковых рекурсивных маршрутов")
|
|
if (candidates.length) bind(index, candidates[0])
|
|
})
|
|
for (const key of new Set(desired.map(prefix))) {
|
|
const pending = desired.flatMap((row, index) => !matches.has(index) && prefix(row) === key ? [index] : [])
|
|
const candidates = [...available.values()].filter(old => prefix(old) === key)
|
|
if (!pending.length || !candidates.length) continue
|
|
if (pending.length !== 1 || candidates.length !== 1) throw new Error("Неоднозначное изменение рекурсивных маршрутов: нужны сохранённые идентификаторы")
|
|
bind(pending[0], candidates[0])
|
|
}
|
|
for (const [index, old] of matches) {
|
|
if (referenced.has(old.id) && prefix(old) !== prefix(desired[index])) throw new Error("Префикс или таблица маршрута используются BGP-фильтром")
|
|
}
|
|
for (const row of available.values()) if (referenced.has(row.id)) throw new Error("Маршрут используется BGP-фильтром: сначала измените ссылку rec:<id>")
|
|
return {
|
|
rows: desired.map((row, index) => {
|
|
const old = matches.get(index)
|
|
return { ...row, id: old?.id ?? "", country: mode === "observed" && !row.country ? old?.country ?? "" : row.country }
|
|
}),
|
|
deletedIds: [...available.keys()],
|
|
}
|
|
}
|