Files
MikrotikManager/backend/src/services/evobgp-catalog.ts
T

43 lines
2.6 KiB
TypeScript

import { z } from "zod"
const id = z.string().trim().min(1)
const count = z.number().int().nonnegative().safe()
const communityId = id.nullish()
function items<T extends z.ZodType>(row: T, key: (value: z.output<T>) => string) {
return z.object({ items: z.array(row).refine(rows => new Set(rows.map(key)).size === rows.length) })
}
const schema = z.object({
modules: items(z.object({ id, name: z.string(), type: z.string() }), row => row.id),
domains: items(z.object({ module_id: id, entry: z.object({ id, fqdn: id, community_id: communityId }) }), row => `${row.module_id}:${row.entry.id}`),
ip_ranges: items(z.object({ module_id: id, entry: z.object({ id, prefix: id, community_id: id }) }), row => `${row.module_id}:${row.entry.id}`),
asns: items(z.object({ module_id: id, entry: z.object({
id, asn: z.number().int().min(1).max(4294967295), community_id: communityId,
asn_name: z.string().nullish(), prefix_count: count.nullish(),
asn_resolved_at: z.string().nullish(),
}) }), row => `${row.module_id}:${row.entry.id}`),
communities: items(z.object({ id, community: z.string().optional(), title: z.string().optional() }), row => row.id),
})
export type EvoCatalogRaw = z.output<typeof schema>
export function parseEvoCatalogRaw(raw: unknown): EvoCatalogRaw {
const result = schema.safeParse(raw)
if (!result.success) throw new Error("Каталог Evolution не подтверждён: получен некорректный ответ интеграции")
return result.data
}
/** Домен/CIDR дают один маршрут; неизвестный prefix_count ASN делает итог community неизвестным. */
export function aggregateCommunityRouteCounts(catalog: EvoCatalogRaw): Map<string, number | null> {
const totals = new Map<string, number | null>()
function add(community: string, count: number | null) {
const previous = totals.has(community) ? totals.get(community)! : 0
if (previous === null || count === null) { totals.set(community, null); return }
const total = previous + count
if (!Number.isSafeInteger(total)) throw new Error("Каталог Evolution не подтверждён: итог маршрутов вне допустимого диапазона")
totals.set(community, total)
}
for (const { entry } of catalog.domains.items) if (entry.community_id) add(entry.community_id, 1)
for (const { entry } of catalog.ip_ranges.items) add(entry.community_id, 1)
for (const { entry } of catalog.asns.items) if (entry.community_id) add(entry.community_id, entry.prefix_count ?? null)
return totals
}