Compare commits

..
2 Commits
Author SHA1 Message Date
Denozordec 731c19a14d feat(mcp): добавить чтение полной таблицы маршрутов BGP
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 11m50s
Docker images / frontend-image (push) Successful in 4m5s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 35s
Docker images / backend-image (push) Successful in 2m29s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
2026-12-01 21:25:12 +07:00
Denozordec 94c50b9660 fix(mcp): разрешить правила обнаружения отказа по адресу соседа
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m46s
Docker images / backend-image (push) Successful in 2m44s
Docker images / frontend-image (push) Successful in 2m19s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-30 23:45:06 +07:00
7 changed files with 272 additions and 4 deletions

No files matched your search

+1 -1
View File
@@ -183,7 +183,7 @@
"test:traffic-flow:read-budget": "tsx --test src/services/traffic-flow-read-budget.test.ts src/modules/mcp/flow-read-quality.test.ts && node scripts/test-flow-read-adapters.mjs",
"test:traffic-flow:read-http:pg": "node scripts/test-flow-read-http-owned.mjs",
"test:traffic-flow:read-source:pg": "tsx scripts/test-flow-read-sql-owned.mts",
"test:mcp:routing-baseline": "tsx --test src/modules/mcp/routing-controller-active-writer.test.ts src/modules/mcp/routing-controller-baseline.test.ts src/modules/mcp/routing-controller-fence.test.ts src/modules/mcp/routing-community-public.test.ts src/modules/mcp/routing-controller-overlap.test.ts",
"test:mcp:routing-baseline": "tsx --test src/modules/mcp/routing-controller-active-writer.test.ts src/modules/mcp/routing-controller-baseline.test.ts src/modules/mcp/routing-controller-fence.test.ts src/modules/mcp/routing-community-public.test.ts src/modules/mcp/routing-controller-overlap.test.ts src/services/bgp-rib-observation.test.ts",
"test:mcp:routing-baseline:pg": "node scripts/test-routing-controller-baseline.mjs",
"test:mcp:routing-baseline-inverse:pg": "node scripts/test-routing-controller-baseline.mjs --default-scoped",
"test:sqlite-import-control:pg": "node scripts/test-sqlite-import-control-postgres.mjs",
+1 -1
View File
@@ -180,7 +180,7 @@ for (const resource of rosResources) {
: z.object({ serverId, id: rowId.optional(), fields: publicFields.default({}), ...(resource.id === "vrf" ? { productionAdmission: z.literal(true).optional() } : {}) }).strict()
const delegated = resource.id === "wireguard" && action !== "create" || resource.id === "wireguard_peer" || resource.id === "gre" && action !== "create" || resource.id === "ipsec_peer" && action !== "create" || resource.id === "certificate" && action === "delete" || resource.id === "container" && action === "delete"
const guardsOspfInterfaceUse = action !== "create" && !delegated && ospfInterfaceResources.includes(resource.id)
const previousVersion = action === "create" ? (["ospf_template", "wireguard_peer", "wireguard", "bfd_configuration"].includes(resource.id) ? 3 : 2) : resource.id === "ipsec_peer" || resource.id === "certificate" && action === "delete" ? 2 : resource.id === "wireguard" && action === "update" ? 3 : resource.id === "ospf_template" && action !== "delete" || resource.id === "wireguard_peer" || resource.id === "wireguard" || resource.id === "ip_settings" ? 2 : 1
const previousVersion = action === "create" ? (resource.id === "bfd_configuration" ? 4 : ["ospf_template", "wireguard_peer", "wireguard"].includes(resource.id) ? 3 : 2) : resource.id === "ipsec_peer" || resource.id === "certificate" && action === "delete" ? 2 : resource.id === "wireguard" && action === "update" ? 3 : resource.id === "ospf_template" && action !== "delete" || resource.id === "wireguard_peer" || resource.id === "wireguard" || resource.id === "ip_settings" ? 2 : 1
add(`ros.${resource.id}.${action}`, `mm_${resource.id}_${action}_plan`, `${resource.title}: ${action}`, resource.permission.split(":")[1], resource.id === "certificate" && action === "update" ? ["mm:certificates:write", "mm:network:write"] : resource.permission + ":write", "write", "servers", schema, {
version: resource.id === "ipsec_peer" ? (action === "create" ? 5 : 3) : resource.id === "certificate" ? (action === "update" ? 4 : 3) : previousVersion + (delegated ? 0 : 1) + (resource.id === "bfd_configuration" ? 4 : resource.id === "ospf_template" ? (action === "update" ? 8 : 7) : 0) + (resource.id === "vrf" ? (action === "delete" ? 3 : 2) : 0) + (resource.id === "ospf_instance" ? 2 : 0) + (["bridge", "bridge_port", "bridge_vlan", "ip_settings", "ipv6_settings"].includes(resource.id) ? 1 : 0) + (guardsOspfInterfaceUse ? 1 : 0),
prepare: async (input, context) => {
@@ -1,10 +1,12 @@
import { z } from "zod"
import { hasPermission } from "../../lib/permissions.js"
import { bgpPrefixRows } from "../../services/bgp-prefix-model.js"
import { BgpRibChanged, bgpRibSelection, readBgpRib } from "../../services/bgp-rib-observation.js"
import { nativeBgpRows } from "../../services/bgp-export-model.js"
import { getServerRowById } from "../servers/repository/servers-repository.js"
import { routerClient } from "./resources.js"
import { effectiveMcpConnection } from "./store.js"
import { createRoutingSourceContext, readRoutingEndpoints } from "./routing-observation-source.js"
import { fingerprint, McpError } from "./security.js"
import type { ActionContext } from "./action-types.js"
import type { add } from "./actions.js"
@@ -17,6 +19,27 @@ async function access(context: ActionContext) {
if (fingerprint(current.policy) !== fingerprint(context.connection.policy)) throw new McpError("RESET_REQUIRED", "Область чтения BGP изменилась", 409)
}
export function registerBgpPrefixActions(register: typeof add) {
const observation = bgpRibSelection.extend({ serverId: z.number().int().positive().safe() })
register("routing.bgp.rib.read", "mm_bgp_rib_get", "Нативная IPv4 BGP RIB по таблице: count-only или страницы всех путей, включая filtered. В следующих страницах передавайте expectedFingerprint первой страницы", "bgp", permissions, "read", "servers", observation, { read: async (input, context) => {
const { serverId, ...selection } = observation.parse(input)
await access(context)
const source = await createRoutingSourceContext(await readRoutingEndpoints([serverId]))
if (source.expected.length !== 1) throw new McpError("DEVICE_UNAVAILABLE", "Источник RIB недоступен", 409)
const check = async () => { await access(context); await source.assertCurrent() }
try {
await check()
const { client } = await routerClient(serverId)
const startedAt = new Date().toISOString()
const result = await readBgpRib(client, selection, check, context.signal)
await check()
return { serverId, ...result, startedAt, observedAt: new Date().toISOString(), timestampKind: "backend-receipt", forwardingVerified: false }
} catch (error) {
await check()
if (error instanceof McpError) throw error
if (error instanceof BgpRibChanged) throw new McpError("STATE_CONFLICT", "Состояние RIB изменилось; повторите чтение с первой страницы", 409)
throw new McpError("STATE_UNAVAILABLE", "Полнота нативного чтения IPv4 BGP RIB не подтверждена", 409)
}
} })
register("routing.bgp.prefixes.read", "mm_bgp_prefixes_get", "Наблюдаемые BGP-префиксы IPv4/IPv6 в явной таблице; active nullable, без доказательства forwarding или attribution к peer", "bgp", permissions, "read", "servers", z.object({
serverId: z.number().int().positive().safe(), family: z.enum(["ipv4", "ipv6"]).default("ipv4"),
table: z.string().trim().min(1).max(100).refine(value => !/[\u0000-\u001f\u007f]/.test(value)).default("main"),
@@ -11,7 +11,7 @@ const creates = rosResources.filter(resource => !resource.readOnly && resource.c
assert.equal(creates.length, 30)
for (const resource of creates) {
const action = findAction(`mm_${resource.id}_create_plan`)
assert.equal(action.operation.version, resource.id === "bfd_configuration" ? 8 : resource.id === "ospf_template" ? 11 : ["ipsec_peer", "vrf", "ospf_instance"].includes(resource.id) ? 5 : ["wireguard", "bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 4 : 3)
assert.equal(action.operation.version, resource.id === "bfd_configuration" ? 9 : resource.id === "ospf_template" ? 11 : ["ipsec_peer", "vrf", "ospf_instance"].includes(resource.id) ? 5 : ["wireguard", "bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 4 : 3)
assert.equal(action.schema.safeParse({ serverId: 1, fields: {} }).success, true)
for (const id of ["*OLD", undefined, null, ""]) {
const rejected = action.schema.safeParse({ serverId: 1, fields: {}, id })
@@ -27,6 +27,7 @@ assert.throws(() => validateRosStep(bfdConfig, "create", { vrf: "main" }), inval
assert.deepEqual(validateRosStep(bfdConfig, "create", { interfaces: "bridge1", vrf: "main" }), { interfaces: "bridge1", vrf: "main" })
for (const interfaces of ["all", "none", "bridge1,all", "bridge1,"]) assert.throws(() => validateRosStep(bfdConfig, "create", { interfaces, vrf: "main" }), invalid)
for (const [addresses, expected] of [["192.0.2.9/24", "192.0.2.0/24"], ["FD00::20/64", "fd00::/64"], ["192.0.2.9/32", "192.0.2.9/32"], ["fd00::20/128", "fd00::20/128"]]) {
assert.deepEqual(validateRosStep(bfdConfig, "create", { addresses, vrf: "main" }), { addresses: expected, vrf: "main" })
assert.deepEqual(validateRosStep(bfdConfig, "update", { addresses }, "*A"), { addresses: expected })
}
for (const addresses of ["0.0.0.0/0", "::/0", "192.0.2.1", "fd00::/129", "192.0.2.1/32/extra", "192.0.2.0/24,192.0.3.0/24", "fe80::%ether1/64"]) assert.equal(bfdConfig.fields.safeParse({ addresses }).success, false)
+1 -1
View File
@@ -381,7 +381,7 @@ export function validateRosStep(resource: RosResourceSpec, action: RosStep["acti
const parsed = resource.fields.parse(fields ?? {}) as Record<string, unknown>
if (action === "create" && resource.requiredOnCreate?.some(field => parsed[field] === undefined)) throw new McpError("INVALID_INPUT", "Не заполнены обязательные поля создания", 400)
if (resource.id === "bfd_configuration" && action === "create") {
if (!parsed.interfaces && !parsed["address-list"]) throw new McpError("INVALID_INPUT", "Для правила BFD укажите интерфейсы или address-list", 400)
if (!parsed.interfaces && !parsed.addresses && !parsed["address-list"]) throw new McpError("INVALID_INPUT", "Для правила BFD укажите interfaces, addresses или address-list", 400)
if (parsed.interfaces && parsed.addresses === undefined && String(parsed.interfaces).split(",").some(value => !value.trim() || /^(?:all|none)$/i.test(value.trim()))) {
throw new McpError("INVALID_INPUT", "Для правила BFD без адреса укажите конкретные интерфейсы", 400)
}
@@ -0,0 +1,130 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { readBgpRib } from "./bgp-rib-observation.js"
const table = "rtab-antiblock"
const primary = "*B000001"
const standby = "*B000002"
const selection = { table, mode: "page" as const, limit: 500, offset: 0 }
function route(index: number, overrides: Record<string, string> = {}): Record<string, string> {
return {
".id": "*" + (index + 1).toString(16).toUpperCase(),
afi: "ip", bgp: "true", dynamic: "true", "routing-table": table,
"dst-address": `198.18.${Math.floor(index / 256)}.${index % 256}/32`,
contribution: "active", active: "true", "bgp.peer-cache-id": primary,
gateway: "10.255.255.100", "immediate-gw": "10.253.250.1%gre-jh-test-msk",
...overrides,
}
}
function fixture(rows: Record<string, string>[]) {
const reads = { routePages: 0, counts: 0 }
const client = {
async get<T>(path: string, _timeout?: number, _signal?: AbortSignal, maxResponseBytes?: number) {
assert((maxResponseBytes ?? 8 * 1024 * 1024) <= 8 * 1024 * 1024, "MikrotikClient rejects GET limits above 8 MiB")
const { pathname, searchParams } = new URL(path, "http://router.invalid")
if (pathname === "/routing/table") return [{ ".id": "*1", name: table }] as T
assert.equal(pathname, "/routing/route")
assert(!searchParams.has("bgp") && !searchParams.has("afi"), "Independent RIB read must include unclassified rows")
assert.equal(searchParams.get("routing-table"), table)
reads.routePages++
const properties = searchParams.get(".proplist")?.split(",")
assert(properties)
return rows.filter(row => row["routing-table"] === table)
.map(row => Object.fromEntries(Object.entries(row).filter(([key]) => properties.includes(key)))) as T
},
async post<T>(path: string, body: Record<string, string | string[]>) {
assert.equal(path, "/routing/route/print")
assert.equal(body["count-only"], "")
const query = body[".query"]
assert(Array.isArray(query))
const peer = query.find(word => word.startsWith("bgp.peer-cache-id="))?.split("=")[1]
assert.deepEqual(query, [
"routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|",
...(peer ? ["bgp.peer-cache-id=" + peer] : []),
])
reads.counts++
const count = rows.filter(row =>
row["routing-table"] === table && row.bgp === "true" && (row.afi === "ip" || row.afi === "ip4") &&
(!peer || row["bgp.peer-cache-id"] === peer),
).length
return { ret: String(count) } as T
},
}
return { client, reads }
}
test("positive native count is cheap; a verified zero independently reads the target table", async () => {
const nonempty = fixture([route(0)])
assert.equal((await readBgpRib(nonempty.client, { ...selection, mode: "count" })).total, 1)
assert.equal(nonempty.reads.routePages, 0)
const { client, reads } = fixture([route(0, { "routing-table": "main" }), route(1, { afi: "ip6", "dst-address": "2001:db8::/32" })])
const result = await readBgpRib(client, { ...selection, mode: "count" })
assert.equal(result.total, 0)
assert(reads.counts > 0)
assert.equal(reads.routePages, 1)
for (const invalid of [[], {}, { ret: "" }, { ret: "0oops" }, { ret: "-1" }]) {
const broken = { ...client, post: async <T>() => invalid as T }
await assert.rejects(readBgpRib(broken, { ...selection, mode: "count" }))
}
})
test("zero fails closed on a missed IPv4 BGP route or ambiguous native BGP evidence", async () => {
const staticRow = { ".id": "*70", afi: "ip", static: "true", "routing-table": table, "dst-address": "198.18.250.1/32", contribution: "active", active: "true" }
const justStatic = fixture([staticRow])
assert.equal((await readBgpRib(justStatic.client, { ...selection, mode: "count" })).total, 0)
assert.equal(justStatic.reads.routePages, 1)
for (const ambiguous of [route(0), { ...staticRow, "bgp.peer-cache-id": primary }, { ...staticRow, "belongs-to": "BGP IP routes from 192.0.2.1" }]) {
const { client } = fixture([ambiguous])
const wrongZero = { ...client, post: async <T>() => ({ ret: "0" }) as T }
await assert.rejects(readBgpRib(wrongZero, { ...selection, mode: "count" }))
}
})
test("matching peer paths include filtered and inactive alternatives with distinct IDs", async () => {
const filtered = route(1, { "dst-address": "198.18.0.0/32", contribution: "filtered", filtered: "true", active: "false", "bgp.peer-cache-id": standby })
const candidate = route(2, { afi: "ip4", contribution: "candidate", active: "false" })
const { client } = fixture([route(0), filtered, candidate, route(3, { afi: "ip6", "dst-address": "2001:db8::/32" })])
const result = await readBgpRib(client, selection)
assert.equal(result.total, 3)
assert(result.items)
const samePrefix = result.items.filter(item => item.prefix === "198.18.0.0/32")
assert.equal(samePrefix.length, 2)
assert.equal(new Set(samePrefix.map(item => item.id)).size, 2)
assert.equal(samePrefix.find(item => item.peerCacheId === standby)?.filtered, true)
assert.equal(result.items.find(item => item.id === candidate[".id"])?.active, false)
const otherPeer = await readBgpRib(client, { ...selection, peerCacheId: standby })
assert.equal(otherPeer.total, 1)
assert.equal(otherPeer.items?.[0]?.id, filtered[".id"])
})
test("missing table and missing peer attribution cannot prove a scoped zero", async () => {
const { client } = fixture([])
const missingTable = { ...client, get: async <T>() => [] as T }
await assert.rejects(readBgpRib(missingTable, { ...selection, mode: "count" }), /table/i)
const unknownPeer = route(0)
delete unknownPeer["bgp.peer-cache-id"]
const result = await readBgpRib(fixture([unknownPeer]).client, selection)
assert.equal(result.items?.[0].peerCacheId, null)
await assert.rejects(readBgpRib(fixture([unknownPeer]).client, { ...selection, mode: "count", peerCacheId: standby }), /peer/i)
})
test("pages beyond 13,000 preserve snapshot identity and reject a changed next page", async () => {
const rows = Array.from({ length: 13_705 }, (_, i) => route(i))
const { client } = fixture(rows)
const first = await readBgpRib(client, selection)
assert.equal(first.total, rows.length)
assert.equal(first.items?.length, selection.limit)
assert.equal(first.nextOffset, selection.limit)
assert(first.fingerprint)
rows.reverse()
const tailSelection = { ...selection, offset: 13_700, expectedFingerprint: first.fingerprint }
const tail = await readBgpRib(client, tailSelection)
assert.equal(tail.items?.length, 5)
assert.equal(tail.nextOffset, null)
assert.equal(tail.fingerprint, first.fingerprint)
rows[0] = { ...rows[0], gateway: "10.255.255.101" }
await assert.rejects(readBgpRib(client, tailSelection))
})
+114
View File
@@ -0,0 +1,114 @@
import { createHash } from "node:crypto"
import { isIP } from "node:net"
import { z } from "zod"
import { canonicalBgpPolicyPrefix } from "./bgp-community-policy-model.js"
import type { MikrotikClient } from "./mikrotik.js"
const rosId = z.string().regex(/^\*[0-9a-z]+$/i).max(64)
export const bgpRibSelection = z.object({
table: z.string().min(1).max(100).refine(name => name.trim() === name && !/[\u0000-\u001f\u007f]/.test(name)),
peerCacheId: rosId.optional(),
mode: z.enum(["count", "page"]).default("count"),
offset: z.number().int().min(0).max(100_000).default(0),
limit: z.number().int().min(1).max(500).default(100),
expectedFingerprint: z.string().regex(/^[a-f0-9]{64}$/).optional(),
}).strict()
const nativeRow = z.record(z.string(), z.unknown())
const otherProtocols = ["static", "connect", "ospf", "dhcp", "rip", "isis", "modem", "slaac", "vpn", "fantasy"]
const properties = [".id", "afi", "dst-address", "routing-table", "bgp", "bgp.peer-cache-id", "bgp.session", "belongs-to", "contribution", "active", "filtered", "gateway", "immediate-gw", ...otherProtocols].join(",")
const otherFamilies = new Set(["ip6", "ipv6", "link", "vpnv4", "vpnv6", "l2vpn", "l2vpn-cisco", "l2vpn-link", "evpn", "mip4", "mip6"])
type Selection = z.infer<typeof bgpRibSelection>
const text = z.string().max(512)
export class BgpRibChanged extends Error {}
const contributions = new Set(["active", "filtered", "candidate", "best-candidate", "unreachable"])
function optionalFlag(value: unknown) {
if (value === undefined) return null
if (value === true || value === "true" || value === "yes") return true
if (value === false || value === "false" || value === "no") return false
throw new Error("Unrecognized RouterOS flag")
}
function ipv4Row(row: Record<string, unknown>, table: string) {
if (row["routing-table"] !== table) throw new Error("Unexpected native route table")
if (otherFamilies.has(String(row.afi))) return null
if (row.afi !== "ip" && row.afi !== "ip4") throw new Error("Unrecognized RouterOS address family")
const bgp = optionalFlag(row.bgp)
const other = otherProtocols.some(key => optionalFlag(row[key]) === true)
if (bgp !== true) {
// Missing origin flags occur on some RouterOS REST projections. Do not lose filtered paths or certify a false zero.
if (row["bgp.peer-cache-id"] || row["bgp.session"] || /\bbgp\b/i.test(String(row["belongs-to"] ?? "")) || bgp === null && !other) throw new Error("Unconfirmed native route origin")
return null
}
if (other) throw new Error("Conflicting native route origins")
const dst = text.parse(row["dst-address"])
const prefix = isIP(dst) === 4 ? dst + "/32" : dst
if (isIP(prefix.split("/")[0]) !== 4 || canonicalBgpPolicyPrefix(prefix) !== prefix) throw new Error("Invalid IPv4 destination")
const id = rosId.parse(row[".id"])
const peerCacheId = row["bgp.peer-cache-id"] === undefined ? null : rosId.parse(row["bgp.peer-cache-id"])
const contribution = text.nullable().parse(row.contribution ?? null)
const activeFlag = optionalFlag(row.active), filteredFlag = optionalFlag(row.filtered)
const known = contribution !== null && contributions.has(contribution)
if (known && (activeFlag !== null && activeFlag !== (contribution === "active") ||
filteredFlag !== null && filteredFlag !== (contribution === "filtered"))) throw new Error("Conflicting native route flags")
return {
id, prefix, table, peerCacheId, contribution,
active: activeFlag ?? (known ? contribution === "active" : null),
filtered: filteredFlag ?? (known ? contribution === "filtered" : null),
session: text.nullable().parse(row["bgp.session"] ?? null),
gateway: text.nullable().parse(row.gateway ?? null), immediateGateway: text.nullable().parse(row["immediate-gw"] ?? null),
}
}
/** Counts run on RouterOS. Page offsets use deterministic route IDs and a digest over the full selection. */
export async function readBgpRib(client: Pick<MikrotikClient, "get" | "post">, input: Selection,
beforeRead: () => Promise<unknown> = async () => {}, signal?: AbortSignal) {
const { table, peerCacheId, mode, limit, offset, expectedFingerprint } = bgpRibSelection.parse(input)
if (offset > 0 && !expectedFingerprint || mode === "count" && (offset || expectedFingerprint)) throw new Error("Invalid RIB page cursor")
const query = ["routing-table=" + table, "bgp=true", "afi=ip", "afi=ip4", "#|"]
const tablePath = "/routing/table?.proplist=.id,name,disabled,invalid&name=" + encodeURIComponent(table)
const tableIdentity = async () => {
const raw = await client.get<unknown>(tablePath, 10_000, signal, 16_384, beforeRead)
if (!Array.isArray(raw) || raw.length !== 1) throw new Error("Missing or ambiguous routing table")
const row = nativeRow.parse(raw[0])
if (row.name !== table || optionalFlag(row.disabled) || optionalFlag(row.invalid)) throw new Error("Routing table unavailable")
return rosId.parse(row[".id"])
}
const nativeCount = async (peer?: string) => {
const filter = peer ? [...query, "bgp.peer-cache-id=" + peer] : query
const raw = await client.post<unknown>("/routing/route/print", { "count-only": "", ".query": filter }, 15_000, signal, beforeRead)
const { ret } = z.object({ ret: z.string().regex(/^(?:0|[1-9]\d{0,14})$/) }).strict().parse(raw)
return Number(ret)
}
const identity = await tableIdentity()
const allCount = await nativeCount()
type Item = NonNullable<ReturnType<typeof ipv4Row>>
let items: Item[] = [], fingerprint: string | null = null, total = allCount, nextOffset: number | null = null
if (mode === "page" || peerCacheId || allCount === 0) {
if (allCount > 100_000) throw new Error("RIB row limit exceeded")
const path = "/routing/route?.proplist=" + properties + "&routing-table=" + encodeURIComponent(table)
const raw = await client.get<unknown>(path, 30_000, signal, 8 * 1024 * 1024, beforeRead)
if (!Array.isArray(raw) || raw.length > 100_000) throw new Error("Invalid or oversized RIB view")
const ids = new Set<string>(), selected: Item[] = []
for (const rawRow of raw) {
const observed = ipv4Row(nativeRow.parse(rawRow), table)
if (!observed) continue
if (ids.has(observed.id)) throw new Error("Duplicate native RIB identity")
ids.add(observed.id)
if (peerCacheId && !observed.peerCacheId) throw new Error("Native peer identity unavailable")
if (!peerCacheId || observed.peerCacheId === peerCacheId) selected.push(observed)
}
if (allCount !== ids.size || selected.length !== await nativeCount(peerCacheId)) throw new BgpRibChanged("Native RIB count changed or view incomplete")
total = selected.length
if (mode === "page") {
selected.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
fingerprint = createHash("sha256").update(JSON.stringify([table, identity, peerCacheId ?? null, selected])).digest("hex")
if (expectedFingerprint && fingerprint !== expectedFingerprint || offset > total) throw new BgpRibChanged("RIB snapshot changed; restart at offset 0")
items = selected.slice(offset, offset + limit)
nextOffset = offset + items.length < total ? offset + items.length : null
}
}
if (identity !== await tableIdentity()) throw new BgpRibChanged("Routing table changed during observation")
return { family: "ipv4", table, peerCacheId: peerCacheId ?? null, mode, total, items, nextOffset, fingerprint, source: "/routing/route", atomicSnapshot: false }
}