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

37 lines
3.3 KiB
TypeScript

import { isDeepStrictEqual } from "node:util"
import { observedInteger } from "./ospf-observed-values.js"
import { privateSecretFingerprint, fingerprint } from "../modules/mcp/security.js"
interface Connection { host: string; port: number; useSsl: boolean; verifySsl: boolean; username: string; password: string; routingEndpointEpoch?: string }
export function ospfCostConnectionProof(serverId: number, source: Connection) {
return privateSecretFingerprint(fingerprint({ serverId, host: source.host, port: source.port, useSsl: source.useSsl, verifySsl: source.verifySsl, username: source.username, password: source.password, routingEndpointEpoch: source.routingEndpointEpoch ?? null }), "ospf-cost-connection")
}
export class OspfCostWriteError extends Error {
constructor(message: string, readonly writeAttempted: boolean) { super(message) }
}
type Row = Record<string, unknown> & { ".id": string }
function configuration(payload: unknown): Row[] {
if (!Array.isArray(payload) || payload.length > 10000 || payload.some(row => !row || typeof row !== "object" || Array.isArray(row) || typeof row[".id"] !== "string" || !row[".id"].trim()) || new Set(payload.map(row => row[".id"])).size !== payload.length) throw new OspfCostWriteError("Не подтверждён каталог шаблонов OSPF", false)
return payload.map(row => ({ ...row, ...(typeof row.cost === "number" ? { cost: String(row.cost) } : {}) }))
}
/** Compare the entire native template collection, including fields the UI does
* not edit. No write or read-back failure is retried. Call under the router lock. */
export async function writeOspfTemplateCost(id: string, cost: number, dependencies: {
read: () => Promise<unknown>; write: (id: string, cost: number) => Promise<unknown>; expectedCost?: number
}) {
if (!/^\*[a-z0-9]+$/i.test(id) || !Number.isInteger(cost) || cost < 1 || cost > 65535 || dependencies.expectedCost !== undefined && (!Number.isInteger(dependencies.expectedCost) || dependencies.expectedCost < 1 || dependencies.expectedCost > 65535)) throw new OspfCostWriteError("Некорректный ID или cost шаблона OSPF", false)
const before = configuration(await dependencies.read()), target = before.find(row => row[".id"] === id)
const current = target && typeof target.cost === "string" ? observedInteger(target.cost, 1, 65535) : null
if (current === null || dependencies.expectedCost !== undefined && current !== dependencies.expectedCost) throw new OspfCostWriteError("Cost или шаблон OSPF изменился после подготовки", false)
const changed = current !== cost
if (changed) await dependencies.write(id, cost)
let after: Row[]
try { after = configuration(await dependencies.read()) }
catch { throw new OspfCostWriteError("Чтение OSPF после записи не подтверждено; проверьте состояние перед новым планом", changed) }
const expected = before.map(row => row[".id"] === id ? { ...row, cost: String(cost) } : row)
if (!isDeepStrictEqual(after, expected)) throw new OspfCostWriteError("После записи OSPF не подтверждён cost или изменились другие параметры; дальнейшие записи остановлены", changed)
return { id, from: current, to: cost, changed }
}