Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 10m50s
Docker images / backend-image (push) Successful in 2m5s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 41s
Docker images / frontend-image (push) Successful in 2m13s
Docker images / publish-release (push) Successful in 12s
Docker images / notify-webhook (push) Successful in 2s
88 lines
5.1 KiB
TypeScript
88 lines
5.1 KiB
TypeScript
import { ipv4ToInt, parseCidrV4 } from "./traffic-flow-ip.js"
|
|
|
|
// No database or RouterOS imports: this boundary can be checked with injected readers.
|
|
type PathServer = {id: number | string; type: string; enabled: boolean}
|
|
export async function collectConfirmedInternetPath<S extends PathServer, G, F, P, R extends object, W extends object>(sampledAt: string, readers: {
|
|
servers(): Promise<S[]>; gre(): Promise<G>; filters(): Promise<F>; speed(): Promise<P>
|
|
route(id: number): Promise<R | null>; wan(id: number): Promise<W | null>
|
|
}) {
|
|
const servers = await readers.servers()
|
|
const homes = servers.filter(s => s.enabled && s.type === "home-router")
|
|
const [greTunnels, filtersRulesets, speedProbes] = await Promise.all([readers.gre(), readers.filters(), readers.speed()])
|
|
const routeLookupByServerId: Record<string, R> = {}
|
|
const wanRuntimeByHomeId: Record<string, W> = {}
|
|
for (const home of homes) {
|
|
const [route, wan] = await Promise.all([readers.route(Number(home.id)), readers.wan(Number(home.id))])
|
|
if (route == null || wan == null) throw new Error("Internet path: устройство " + home.id + " не подтвердило route/WAN")
|
|
routeLookupByServerId[String(home.id)] = route
|
|
wanRuntimeByHomeId[String(home.id)] = wan
|
|
}
|
|
return {collectionComplete: true as const, sampledAt, servers, greTunnels, filtersRulesets, speedProbes, routeLookupByServerId, wanRuntimeByHomeId}
|
|
}
|
|
|
|
export function readInternetPathRows(raw: unknown, source: string, requiredFields: string[] = []): Array<Record<string, string>> {
|
|
if (!Array.isArray(raw) || raw.some(row => !row || typeof row !== "object" || Array.isArray(row) || Object.values(row).some(value => typeof value !== "string") || requiredFields.some(field => typeof row[field] !== "string" || !row[field].trim()))) {
|
|
throw new Error("Internet path: повреждён ответ " + source)
|
|
}
|
|
return raw as Array<Record<string, string>>
|
|
}
|
|
|
|
export function readStoredInternetPathPayload(raw: unknown): object {
|
|
const payload: unknown = typeof raw === "string" ? JSON.parse(raw) : raw
|
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) throw new Error("Сохранённый снимок Internet path повреждён")
|
|
return payload
|
|
}
|
|
|
|
/** PostgreSQL string-mode timestamps must be normalized at the HTTP boundary. */
|
|
export function mapStoredInternetPathResponse(row: { payloadJson: unknown; sampledAt: string }) {
|
|
if (typeof row.sampledAt !== "string" || !row.sampledAt.trim()) throw new Error("Сохранённая дата Internet path повреждена")
|
|
return { snapshot: readStoredInternetPathPayload(row.payloadJson), sampledAt: new Date(row.sampledAt).toISOString() }
|
|
}
|
|
|
|
|
|
// Enrichment may be unauthorized on otherwise observable GRE routers.
|
|
export async function readGreEnrichment(read: () => Promise<unknown>, source: string, fields: string[]) {
|
|
try { return readInternetPathRows(await read(), source, fields) } catch { return [] }
|
|
}
|
|
|
|
// A shared point-to-point subnet and matching outer peers identify the exact next hop on this exporter.
|
|
export function observedGrePeers<T extends {serverId: string; enabled: boolean; localAddress: string; remoteAddress: string; currentRemoteAddress?: string; localInnerIp?: string; observedAddresses: string[]}>(
|
|
tunnels: T[], hosts: Map<string, string>, assignedAddresses: Map<string, Set<string>>,
|
|
) {
|
|
const subnets = new Map<string, Array<{ tunnel: T; ip: string }>>()
|
|
const peers = new Map<T, Array<{ ip: string; serverId: string }>>()
|
|
for (const tunnel of tunnels) {
|
|
if (!tunnel.enabled) continue
|
|
for (const cidr of tunnel.observedAddresses) {
|
|
if (!/^[0-9.]+\/(30|31)$/.test(cidr)) continue
|
|
const parsed = parseCidrV4(cidr)
|
|
const ip = cidr.split("/")[0]!
|
|
if (!parsed || (parsed.prefixLen === 30 && (ipv4ToInt(ip) === parsed.net || ipv4ToInt(ip) === parsed.net + 3))) continue
|
|
const key = parsed.net + "/" + parsed.prefixLen
|
|
const entries = subnets.get(key) ?? []
|
|
entries.push({ tunnel, ip })
|
|
subnets.set(key, entries)
|
|
}
|
|
}
|
|
function pointsTo(local: T, peer: T) {
|
|
const current = local.currentRemoteAddress?.trim().toLowerCase()
|
|
const remote = current && current !== "0.0.0.0" ? current : local.remoteAddress.trim().toLowerCase()
|
|
return remote && remote !== "0.0.0.0" && (remote === peer.localAddress.toLowerCase() ||
|
|
remote === hosts.get(peer.serverId)?.toLowerCase() || assignedAddresses.get(peer.serverId)?.has(remote))
|
|
}
|
|
for (const endpoints of subnets.values()) {
|
|
if (endpoints.length !== 2) continue
|
|
const [a, b] = endpoints as [typeof endpoints[number], typeof endpoints[number]]
|
|
if (a.ip === b.ip || a.tunnel.serverId === b.tunnel.serverId || !pointsTo(a.tunnel, b.tunnel) || !pointsTo(b.tunnel, a.tunnel)) continue
|
|
for (const [local, peer] of [[a, b], [b, a]] as const) {
|
|
const matches = peers.get(local.tunnel) ?? []
|
|
matches.push({ ip: peer.ip, serverId: peer.tunnel.serverId })
|
|
peers.set(local.tunnel, matches)
|
|
}
|
|
}
|
|
return tunnels.map(tunnel => {
|
|
const { observedAddresses, ...rest } = tunnel
|
|
return { ...rest, localInnerIp: observedAddresses[0] ?? tunnel.localInnerIp ?? "", observedNextHops: peers.get(tunnel) ?? [] }
|
|
})
|
|
}
|