Files
MikrotikManager/backend/src/services/bridge-vlan-configuration.ts
T

339 lines
29 KiB
TypeScript

import { isIP } from "node:net"
import type { z } from "zod"
import { bridgeVlanDesiredSchema, bridgeVlanRowIdSchema as id, bridgeVlanInterfaceReferenceSchema as reference, bridgeVlanIdSchema as vid, bridgeVlanFrameTypesSchema as frames, type BridgeVlanDesired, type BridgeVlanState } from "@mmapp/contracts/bridge-vlan"
import type { ConfigurationRow, RosStep } from "../modules/mcp/resources.js"
export { bridgeVlanDesiredSchema, type BridgeVlanDesired, type BridgeVlanState }
export type BridgeVlanInterface = { resource: string; id: string; name: string; disabled?: unknown }
/** This argument belongs to the trusted server adapter, never the public request.
* The adapter verifies channel identity/revocation and decrypts its literal host.
* These values and all source snapshots must be sealed and rechecked on apply. */
export type BridgeVlanManagement = { channelId: string; serverId: number; expiresAt: string; host: string }
export class BridgeVlanConfigurationError extends Error {
constructor(readonly code: "INVALID_INPUT" | "STATE_CONFLICT" | "MANAGEMENT_UNSAFE" | "UNSUPPORTED_CAPABILITY", message: string) { super(message) }
}
/** L2 port kinds available in the actual typed configuration catalogue.
* RouterOS also supports EoIP/bond/Wi-Fi, but they need their own indexed
* configuration resource before this planner can prove their stable identity.
* GRE and WireGuard carry L3 traffic and cannot be native bridge ports.
* https://manual.mikrotik.com/docs/bridging-and-switching/
* https://help.mikrotik.com/docs/spaces/ROS/pages/24805531/GRE
* https://help.mikrotik.com/docs/spaces/ROS/pages/69664792/WireGuard */
export const BRIDGE_VLAN_L2_PORT_RESOURCES = ["ethernet", "vlan", "vxlan"] as const
function reject(message: string, code: BridgeVlanConfigurationError["code"] = "STATE_CONFLICT"): never { throw new BridgeVlanConfigurationError(code, message) }
const text = (row: ConfigurationRow, key: string): string => typeof row[key] === "string" ? row[key] as string : reject(`Не подтверждено поле ${key}`)
function flag(value: unknown): boolean {
if ([true, "true", "yes"].includes(value as boolean | string)) return true
if ([false, "false", "no"].includes(value as boolean | string)) return false
return reject("Не подтверждено логическое свойство")
}
const mutable = (row: ConfigurationRow) => !["dynamic", "builtin", "default"].some(key => row[key] !== undefined && flag(row[key]))
const enabled = (row: ConfigurationRow) => !flag(row.disabled)
const rowId = (row: ConfigurationRow) => id.parse(row[".id"])
const keyOf = (value: { resource: string; id: string }) => `${value.resource}:${value.id}`
const unique = (values: string[], label: string) => { if (new Set(values).size !== values.length) reject(`Повтор ${label}`, "INVALID_INPUT") }
/** Ranges are inclusive. Reject overlaps rather than silently deduplicating. */
export function parseBridgeVlanIds(value: string): number[] {
const found = new Set<number>()
for (const part of value.split(",")) {
if (!/^[1-9]\d{0,3}(?:-[1-9]\d{0,3})?$/.test(part)) reject("Некорректный VLAN ID/диапазон", "INVALID_INPUT")
const [start, rawEnd] = part.split("-").map(Number), end = rawEnd ?? start
if (start < 1 || end > 4094 || end < start) reject("VLAN ID вне 1..4094", "INVALID_INPUT")
for (let n = start; n <= end; n++) { if (found.has(n)) reject("Повтор VLAN ID", "INVALID_INPUT"); found.add(n) }
}
return [...found].sort((a, b) => a - b)
}
const names = (row: ConfigurationRow, field: string): string[] => {
if (row[field] === undefined && ["tagged", "untagged"].includes(field)) return []
const value = text(row, field)
if (!value) return []
const result = value.split(",")
if (result.some(name => !name || name.trim() !== name)) reject("Неоднозначный список интерфейсов")
unique(result, "интерфейса")
return result
}
const numberVid = (value: unknown) => vid.parse(typeof value === "string" && /^\d+$/.test(value) ? Number(value) : value)
type Topology = { bridge: ConfigurationRow; ports: ConfigurationRow[]; vlans: ConfigurationRow[] }
type Admission = { interface: string; mode: "tagged" | "untagged" }
export type BridgeVlanConfigurationPlan = {
serverId: number; bridgeId: string; steps: RosStep[];
objects: Array<{ kind: string; id: string; serverId: number }>;
managementPath: { channelId: string; addressId: string; interfaceName: string; bridgeName?: string; vlanId?: number };
inverse: { desired: BridgeVlanDesired; created: Array<{ stepIndex: number; resource: "bridge_port" | "bridge_vlan" }> };
}
/** Convert observed static rows without replacing unknown native properties
* with assumed defaults. Used by the editor and generic effective PATCH guard. */
export function bridgeVlanCurrentDesired(state: BridgeVlanState, bridgeId: string): BridgeVlanDesired {
const bridges = state.bridges.filter(row => row[".id"] === bridgeId)
if (bridges.length !== 1) reject("Bridge не найден однозначно")
const bridge = bridges[0], bridgeName = text(bridge, "name")
const refFor = (name: string) => {
const found = state.interfaces.filter(value => value.name === name)
if (found.length !== 1) reject("Не подтверждена идентичность интерфейса")
return { resource: found[0].resource, id: id.parse(found[0].id) }
}
return {
filtering: flag(bridge["vlan-filtering"]), pvid: numberVid(bridge.pvid), frameTypes: frames.parse(bridge["frame-types"]), ingressFiltering: flag(bridge["ingress-filtering"]),
ports: state.ports.filter(row => row.bridge === bridgeName && mutable(row)).map(row => ({ id: rowId(row), interface: refFor(text(row, "interface")), pvid: numberVid(row.pvid), ingressFiltering: flag(row["ingress-filtering"]), frameTypes: frames.parse(row["frame-types"]), disabled: flag(row.disabled), ...(row.comment === undefined ? {} : { comment: text(row, "comment") }) })),
vlans: state.vlans.filter(row => row.bridge === bridgeName && mutable(row)).map(row => ({ id: rowId(row), vlanIds: text(row, "vlan-ids"), tagged: names(row, "tagged").map(refFor), untagged: names(row, "untagged").map(refFor), disabled: flag(row.disabled), ...(row.comment === undefined ? {} : { comment: text(row, "comment") }) })),
removePortIds: [], removeVlanIds: [],
}
}
export function buildBridgeVlanConfiguration(input: {
serverId: number; bridgeId: string; desired: BridgeVlanDesired; state: BridgeVlanState; management: BridgeVlanManagement; now: number;
}): BridgeVlanConfigurationPlan {
const { serverId, bridgeId, state, management } = input, desired = bridgeVlanDesiredSchema.parse(input.desired)
if (!Number.isSafeInteger(serverId) || serverId <= 0 || management.serverId !== serverId || !management.channelId || !Number.isFinite(input.now) || !(Date.parse(management.expiresAt) > input.now) || !isIP(management.host)) reject("Нет актуального канала управления", "MANAGEMENT_UNSAFE")
const bridges = state.bridges.filter(row => row[".id"] === bridgeId)
if (bridges.length !== 1 || !mutable(bridges[0]) || !enabled(bridges[0])) reject("Bridge не подтверждён или отключён")
const bridge = bridges[0], bridgeName = text(bridge, "name")
// A dynamic VLAN table is not evidence of caller-owned rows. PVID-generated
// untagged membership is derived below; protocol registrations are unsupported.
if (bridge.mvrp !== undefined && flag(bridge.mvrp)) reject("MVRP создаёт программируемые VLAN memberships; этот режим не поддерживается", "UNSUPPORTED_CAPABILITY")
const cpuFrames = frames.parse(bridge["frame-types"]), cpuIngress = flag(bridge["ingress-filtering"])
const byRef = new Map(state.interfaces.map(iface => [keyOf(iface), iface]))
unique(state.interfaces.map(keyOf), "идентичности интерфейса")
unique(state.interfaces.map(iface => iface.name), "имени интерфейса")
const bridgeRef = state.interfaces.find(iface => iface.resource === "bridge" && iface.id === bridgeId && iface.name === bridgeName)
if (!bridgeRef) reject("Не подтверждена идентичность CPU bridge")
const resolve = (ref: z.infer<typeof reference>) => byRef.get(keyOf(ref)) ?? reject("Неизвестный стабильный ID интерфейса", "INVALID_INPUT")
const oldPorts = state.ports.filter(row => row.bridge === bridgeName), oldVlans = state.vlans.filter(row => row.bridge === bridgeName)
unique(state.ports.map(rowId), "ID порта"); unique(state.vlans.map(rowId), "ID membership")
// Dynamic rows remain owned by RouterOS; they are never converted to commands.
const staticPorts = oldPorts.filter(mutable), staticVlans = oldVlans.filter(mutable)
const account = (rows: ConfigurationRow[], keep: Array<{ id?: string }>, remove: string[], label: string) => {
const requested = [...keep.flatMap(row => row.id ? [row.id] : []), ...remove]
unique(requested, label)
const existing = rows.map(rowId)
if (requested.length !== existing.length || requested.some(value => !existing.includes(value))) reject(`Нужен явный полный список ${label}`, "INVALID_INPUT")
}
account(staticPorts, desired.ports, desired.removePortIds, "портов")
account(staticVlans, desired.vlans, desired.removeVlanIds, "VLAN memberships")
unique(desired.ports.map(port => keyOf(port.interface)), "порта bridge")
const portRows = desired.ports.map((port, index) => {
const iface = resolve(port.interface)
if (iface.name === bridgeName || iface.resource === "bridge" || state.ports.some(row => row.interface === iface.name && row.bridge !== bridgeName)) reject("Интерфейс уже принадлежит другому bridge или является bridge", "INVALID_INPUT")
if (!(BRIDGE_VLAN_L2_PORT_RESOURCES as readonly string[]).includes(iface.resource)) reject("Тип интерфейса не поддерживает подтверждённый L2 bridge port", "UNSUPPORTED_CAPABILITY")
let parent = iface.name
const ancestors = new Set<string>()
while (true) {
if (ancestors.has(parent)) reject("Цикл VLAN родителей bridge-порта", "INVALID_INPUT")
ancestors.add(parent)
const vlans = state.vlanInterfaces.filter(row => row.name === parent)
if (!vlans.length) {
if (parent === iface.name && iface.resource === "vlan") reject("Не подтверждён VLAN parent bridge-порта", "UNSUPPORTED_CAPABILITY")
break
}
if (vlans.length !== 1) reject("Неоднозначный VLAN parent bridge-порта", "STATE_CONFLICT")
parent = text(vlans[0], "interface")
if (parent === bridgeName) reject("VLAN над выбранным bridge нельзя вернуть в его собственные порты", "INVALID_INPUT")
}
if (!port.disabled && iface.disabled !== undefined && flag(iface.disabled)) reject("Порт ссылается на отключённый интерфейс", "INVALID_INPUT")
const previous = staticPorts.find(row => row[".id"] === port.id)
return { ".id": port.id ?? `new-port-${index}`, bridge: bridgeName, interface: iface.name, pvid: String(port.pvid), "ingress-filtering": String(port.ingressFiltering), "frame-types": port.frameTypes, disabled: String(port.disabled), ...(port.comment !== undefined ? { comment: port.comment } : previous?.comment !== undefined ? { comment: text(previous, "comment") } : {}) }
})
const vlanRows = desired.vlans.map((vlan, index) => {
const tagged = vlan.tagged.map(ref => resolve(ref).name), untagged = vlan.untagged.map(ref => resolve(ref).name)
unique([...tagged, ...untagged], "tagged/untagged участника")
parseBridgeVlanIds(vlan.vlanIds)
const previous = staticVlans.find(row => row[".id"] === vlan.id)
return { ".id": vlan.id ?? `new-vlan-${index}`, bridge: bridgeName, "vlan-ids": vlan.vlanIds, ...(tagged.length || previous?.tagged !== undefined ? { tagged: tagged.join(",") } : {}), ...(untagged.length || previous?.untagged !== undefined ? { untagged: untagged.join(",") } : {}), disabled: String(vlan.disabled), ...(vlan.comment !== undefined ? { comment: vlan.comment } : previous?.comment !== undefined ? { comment: text(previous, "comment") } : {}) }
})
const target: Topology = { bridge: { ...bridge, pvid: String(desired.pvid), "vlan-filtering": String(desired.filtering), "frame-types": desired.frameTypes ?? cpuFrames, "ingress-filtering": String(desired.ingressFiltering ?? cpuIngress) }, ports: [...oldPorts.filter(row => !mutable(row)), ...portRows], vlans: [...oldVlans.filter(row => !mutable(row)), ...vlanRows] }
const activePorts = (topology: Topology) => topology.ports.filter(enabled)
const membership = (topology: Topology, vlanId: number, mode: "tagged" | "untagged") => {
const members = new Set(topology.vlans.filter(row => mutable(row) && enabled(row) && parseBridgeVlanIds(text(row, "vlan-ids")).includes(vlanId)).flatMap(row => names(row, mode)))
// RouterOS automatically includes CPU/ports that accept untagged ingress
// as untagged PVID members. Never synthesize a VLAN table command for it.
if (mode === "untagged") for (const port of [topology.bridge, ...activePorts(topology)]) {
if (enabled(port) && frames.parse(port["frame-types"]) !== "admit-only-vlan-tagged" && numberVid(port.pvid) === vlanId) members.add(port === topology.bridge ? bridgeName : text(port, "interface"))
}
return members
}
// Validate effective static state; dynamic PVID membership is derived from
// the actual port PVID, never accepted as caller-owned VLAN configuration.
const validate = (topology: Topology) => {
const ports = activePorts(topology), allowed = new Set([bridgeName, ...topology.ports.map(row => text(row, "interface"))])
const used = new Set<string>(), configuredVids = new Set<number>()
for (const vlan of topology.vlans.filter(row => mutable(row) && enabled(row))) {
const vids = parseBridgeVlanIds(text(vlan, "vlan-ids")), tagged = names(vlan, "tagged"), untagged = names(vlan, "untagged")
unique([...tagged, ...untagged], "tagged/untagged участника")
if ([...tagged, ...untagged].some(name => !allowed.has(name))) reject("Участник VLAN не принадлежит выбранному bridge", "INVALID_INPUT")
for (const n of vids) { if (configuredVids.has(n)) reject("Неоднозначная эффективная VLAN membership", "INVALID_INPUT"); configuredVids.add(n) }
for (const n of vids) for (const name of [...tagged, ...untagged]) {
const key = `${n}:${name}`
if (used.has(key)) reject("Неоднозначная эффективная VLAN membership", "INVALID_INPUT")
used.add(key)
const pvid = name === bridgeName ? numberVid(topology.bridge.pvid) : numberVid(topology.ports.find(row => row.interface === name)!.pvid)
if (untagged.includes(name) && (vids.length !== 1 || pvid !== n)) reject("Untagged VLAN не соответствует PVID", "INVALID_INPUT")
}
}
if (flag(topology.bridge["vlan-filtering"])) for (const port of ports) {
const frameTypes = frames.parse(port["frame-types"])
if (frameTypes !== "admit-only-vlan-tagged" && membership(topology, numberVid(port.pvid), "tagged").has(text(port, "interface"))) reject("PVID создаёт конфликт tagged/untagged membership", "INVALID_INPUT")
}
if (flag(topology.bridge["vlan-filtering"]) && frames.parse(topology.bridge["frame-types"]) !== "admit-only-vlan-tagged" && membership(topology, numberVid(topology.bridge.pvid), "tagged").has(bridgeName)) reject("CPU PVID создаёт конфликт tagged/untagged membership", "INVALID_INPUT")
}
validate(target)
const addresses = [...state.ipv4Addresses, ...state.ipv6Addresses].filter(row => typeof row.address === "string" && isIP(row.address.split("/")[0]) === isIP(management.host) && sameAddress(row.address.split("/")[0], management.host) && enabled(row))
if (addresses.length !== 1) reject("Адрес канала не найден однозначно в конфигурации", "MANAGEMENT_UNSAFE")
const address = addresses[0], addressInterface = text(address, "interface")
let managementInterface = addressInterface, managementVid: number | undefined
const visited = new Set<string>()
while (true) {
if (visited.has(managementInterface)) reject("Цикл родителей management", "MANAGEMENT_UNSAFE")
visited.add(managementInterface)
const candidates = state.vlanInterfaces.filter(row => row.name === managementInterface)
if (!candidates.length) break
if (candidates.length !== 1 || !enabled(candidates[0]) || managementVid !== undefined) reject("Не подтверждён management VLAN parent", "MANAGEMENT_UNSAFE")
managementVid = numberVid(candidates[0]["vlan-id"]); managementInterface = text(candidates[0], "interface")
}
const managementPort = state.ports.find(row => row.interface === managementInterface)
const affected = managementInterface === bridgeName || managementPort?.bridge === bridgeName
// An IP directly assigned to a bridge slave does not prove CPU delivery.
if (managementPort?.bridge === bridgeName) reject("Management IP на slave-порту не доказывает CPU-доступ", "MANAGEMENT_UNSAFE")
if (target.ports.some(row => row.interface === managementInterface)) reject("План превращает management интерфейс в slave-порт", "MANAGEMENT_UNSAFE")
const managementBase = state.interfaces.find(iface => iface.name === managementInterface)
if (!managementBase || !["ethernet", "bridge"].includes(managementBase.resource)) reject("Не подтверждён физический management parent", "MANAGEMENT_UNSAFE")
if (managementPort) reject("Management IP на slave-порту не доказывает CPU-доступ", "MANAGEMENT_UNSAFE")
// A different bridge is independent only if none of its actual member
// interfaces depends on this bridge (for example a VLAN over this bridge).
const dependentOnTarget = (name: string, visiting = new Set<string>()): boolean => {
if (name === bridgeName || target.ports.some(row => row.interface === name)) return true
if (visiting.has(name)) reject("Цикл management зависимостей", "MANAGEMENT_UNSAFE")
const next = new Set(visiting).add(name)
const vlan = state.vlanInterfaces.find(row => row.name === name)
if (vlan) return dependentOnTarget(text(vlan, "interface"), next)
const iface = state.interfaces.find(item => item.name === name)
if (!iface || !["ethernet", "bridge"].includes(iface.resource)) reject("Не подтверждены management зависимости", "MANAGEMENT_UNSAFE")
return iface.resource === "bridge" && state.ports.filter(row => row.bridge === name && enabled(row)).some(row => dependentOnTarget(text(row, "interface"), next))
}
if (!affected && dependentOnTarget(managementInterface)) reject("Management зависит от изменяемого bridge", "MANAGEMENT_UNSAFE")
if (!state.interfaces.some(iface => iface.name === managementInterface && (iface.disabled === undefined || !flag(iface.disabled)))) reject("Не подтверждён management интерфейс", "MANAGEMENT_UNSAFE")
const admissions = (topology: Topology): Admission[] => {
if (!affected) return []
const filtering = flag(topology.bridge["vlan-filtering"]), vlanId = managementVid ?? numberVid(topology.bridge.pvid)
if (!filtering) return activePorts(topology).map(port => ({ interface: text(port, "interface"), mode: managementVid === undefined ? "untagged" as const : "tagged" as const }))
const cpuMode = managementVid === undefined ? "untagged" : "tagged"
const cpuFrameTypes = frames.parse(topology.bridge["frame-types"])
if (cpuMode === "untagged" && cpuFrameTypes === "admit-only-vlan-tagged" || cpuMode === "tagged" && cpuFrameTypes === "admit-only-untagged-and-priority-tagged") return []
if (filtering && !membership(topology, vlanId, cpuMode).has(bridgeName)) return []
if (membership(topology, vlanId, "tagged").has(bridgeName) && membership(topology, vlanId, "untagged").has(bridgeName)) return []
return activePorts(topology).flatMap(port => {
const name = text(port, "interface"), frameTypes = frames.parse(port["frame-types"]), result: Admission[] = []
if (membership(topology, vlanId, "tagged").has(name) && membership(topology, vlanId, "untagged").has(name)) return []
if (frameTypes !== "admit-only-untagged-and-priority-tagged" && membership(topology, vlanId, "tagged").has(name)) result.push({ interface: name, mode: "tagged" })
if (frameTypes !== "admit-only-vlan-tagged" && numberVid(port.pvid) === vlanId && (!filtering || membership(topology, vlanId, "untagged").has(name))) result.push({ interface: name, mode: "untagged" })
return result
})
}
let current: Topology = structuredClone({ bridge, ports: oldPorts, vlans: oldVlans })
const baseline = admissions(current)
if (affected && !baseline.length) reject("Не подтверждён исходный CPU management-доступ", "MANAGEMENT_UNSAFE")
const preservesManagement = (topology: Topology) => !affected || baseline.every(old => admissions(topology).some(next => old.interface === next.interface && old.mode === next.mode))
if (!preservesManagement(target)) reject("План изменяет подтверждённые пути CPU management", "MANAGEMENT_UNSAFE")
const inverseDesired = bridgeVlanCurrentDesired(state, bridgeId)
for (const port of inverseDesired.ports) {
if (desired.removePortIds.includes(port.id!)) delete port.id
else if (port.comment === undefined && desired.ports.some(next => next.id === port.id && next.comment !== undefined)) port.comment = ""
}
for (const vlan of inverseDesired.vlans) {
if (desired.removeVlanIds.includes(vlan.id!)) delete vlan.id
else if (vlan.comment === undefined && desired.vlans.some(next => next.id === vlan.id && next.comment !== undefined)) vlan.comment = ""
}
const steps: RosStep[] = [], created: BridgeVlanConfigurationPlan["inverse"]["created"] = []
const append = (step: RosStep) => { if (step.action === "create") created.push({ stepIndex: steps.length, resource: step.resource as "bridge_port" | "bridge_vlan" }); steps.push(step) }
const mutation = (resource: "bridge_port" | "bridge_vlan", old: ConfigurationRow[], next: ConfigurationRow[], deleted: string[]) => {
const result: Array<{ step: RosStep; modelId: string }> = []
for (const row of next) {
const nativeId = String(row[".id"]), previous = old.find(value => value[".id"] === nativeId)
const fields = Object.fromEntries(Object.entries(row).filter(([key, value]) => key !== ".id" && (!previous || String(previous[key]) !== value)).map(([key, value]) => [key, String(value)]))
if (Object.keys(fields).length) result.push({ step: { serverId, resource, action: previous ? "update" : "create", ...(previous ? { id: nativeId } : {}), fields }, modelId: nativeId })
}
for (const nativeId of deleted) result.push({ step: { serverId, resource, action: "delete", id: nativeId, fields: {} }, modelId: nativeId })
return result
}
const pending = [...mutation("bridge_vlan", staticVlans, vlanRows, desired.removeVlanIds), ...mutation("bridge_port", staticPorts, portRows, desired.removePortIds)]
// Independent management permits a disabled intermediate topology. A channel
// on this bridge instead requires every acknowledged prefix to preserve it.
if (flag(bridge["vlan-filtering"]) && (!desired.filtering || pending.length > 0) && !affected) {
append({ serverId, resource: "bridge", action: "update", id: bridgeId, fields: { "vlan-filtering": "false" } }); current.bridge["vlan-filtering"] = "false"
}
while (pending.length) {
let selected = -1, next: Topology | undefined
for (let index = 0; index < pending.length; index++) {
const item = pending[index], candidate = structuredClone(current), field = item.step.resource === "bridge_port" ? "ports" : "vlans"
if (item.step.action === "delete") candidate[field] = candidate[field].filter(row => row[".id"] !== item.modelId)
else if (item.step.action === "create") candidate[field].push({ ".id": item.modelId, ...item.step.fields })
else candidate[field] = candidate[field].map(row => row[".id"] === item.modelId ? { ...row, ...item.step.fields } : row)
// RouterOS permits only one bridge-port row per interface, including
// disabled rows. Explicit replacement must DELETE before CREATE, and
// swaps requiring an invented temporary interface are not admitted.
const claimed = candidate.ports.map(row => text(row, "interface"))
if (new Set(claimed).size !== claimed.length) continue
if (preservesManagement(candidate)) { selected = index; next = candidate; break }
}
if (selected < 0 || !next) reject("Не существует порядка без конфликта интерфейсов или потери management", "STATE_CONFLICT")
append(pending.splice(selected, 1)[0].step); current = next
}
const finalFields: Record<string, string> = {}
if (numberVid(current.bridge.pvid) !== desired.pvid) finalFields.pvid = String(desired.pvid)
if (desired.frameTypes !== undefined && frames.parse(current.bridge["frame-types"]) !== desired.frameTypes) finalFields["frame-types"] = desired.frameTypes
if (desired.ingressFiltering !== undefined && flag(current.bridge["ingress-filtering"]) !== desired.ingressFiltering) finalFields["ingress-filtering"] = String(desired.ingressFiltering)
if (flag(current.bridge["vlan-filtering"]) !== desired.filtering) finalFields["vlan-filtering"] = String(desired.filtering)
if (Object.keys(finalFields).length) {
if (!preservesManagement({ ...current, bridge: { ...current.bridge, ...finalFields } })) reject("Финальное переключение теряет management", "MANAGEMENT_UNSAFE")
append({ serverId, resource: "bridge", action: "update", id: bridgeId, fields: finalFields })
}
const objectMap = new Map<string, { kind: string; id: string; serverId: number }>()
for (const [kind, rows] of [["bridge", [bridge]], ["bridge_port", oldPorts], ["bridge_vlan", oldVlans]] as const) for (const row of rows) objectMap.set(`${kind}:${rowId(row)}`, { kind, id: rowId(row), serverId })
for (const ref of [...desired.ports.map(port => port.interface), ...desired.vlans.flatMap(vlan => [...vlan.tagged, ...vlan.untagged])]) objectMap.set(keyOf(ref), { kind: ref.resource, id: ref.id, serverId })
const oldMemberNames = new Set([...oldPorts.map(row => text(row, "interface")), ...oldVlans.flatMap(row => [...names(row, "tagged"), ...names(row, "untagged")])])
for (const name of oldMemberNames) {
const iface = state.interfaces.find(value => value.name === name) ?? reject("Не подтверждена прежняя зависимость bridge")
objectMap.set(keyOf(iface), { kind: iface.resource, id: iface.id, serverId })
}
const addressResource = state.ipv4Addresses.includes(address) ? "ipv4_address" : "ipv6_address"
objectMap.set(`${addressResource}:${rowId(address)}`, { kind: addressResource, id: rowId(address), serverId })
const managementVisited = new Set<string>()
const includeManagement = (name: string) => {
if (managementVisited.has(name)) return
managementVisited.add(name)
const iface = state.interfaces.find(value => value.name === name) ?? reject("Не подтверждена идентичность management dependency")
objectMap.set(keyOf(iface), { kind: iface.resource, id: iface.id, serverId })
const vlan = state.vlanInterfaces.find(row => row.name === name)
if (vlan) includeManagement(text(vlan, "interface"))
if (iface.resource === "bridge") for (const port of state.ports.filter(row => row.bridge === name && enabled(row))) {
objectMap.set(`bridge_port:${rowId(port)}`, { kind: "bridge_port", id: rowId(port), serverId })
includeManagement(text(port, "interface"))
}
}
includeManagement(addressInterface)
return { serverId, bridgeId, steps, objects: [...objectMap.values()], managementPath: { channelId: management.channelId, addressId: rowId(address), interfaceName: addressInterface, ...(affected ? { bridgeName, ...(managementVid === undefined ? {} : { vlanId: managementVid }) } : {}) }, inverse: { desired: inverseDesired, created } }
}
function sameAddress(left: string, right: string): boolean {
if (isIP(left) === 4) return left === right
// WHATWG URL canonicalizes equivalent compressed IPv6 spellings.
try { return new URL(`http://[${left}]/`).hostname === new URL(`http://[${right}]/`).hostname } catch { return false }
}
/** ACKs must come from successful executor read-back, never from user JSON.
* Re-prepare this desired state against fresh snapshots and obtain approval;
* this function grants no automatic compensation or replay authority. */
export function bridgeVlanInverseDesired(plan: BridgeVlanConfigurationPlan, createAcks: Array<{ stepIndex: number; id: string }>): BridgeVlanDesired {
unique(createAcks.map(ack => String(ack.stepIndex)), "create ACK")
if (createAcks.length !== plan.inverse.created.length) reject("Нет точных ACK всех созданных объектов")
const desired = structuredClone(plan.inverse.desired)
for (const created of plan.inverse.created) {
const ack = createAcks.find(value => value.stepIndex === created.stepIndex)
if (!ack) reject("Нет create ACK")
const nativeId = id.parse(ack.id)
if (created.resource === "bridge_port") desired.removePortIds.push(nativeId)
else desired.removeVlanIds.push(nativeId)
}
return desired
}