"use client" import { useEffect, useState } from "react" import Link from "next/link" import { UsersIcon, XIcon } from "lucide-react" import type { IxLinuxBinding, IxSegment } from "@mmapp/contracts/internet-exchange" import type { FlowMapService, FlowMapServicePath } from "@mmapp/contracts/traffic-flow" import { Badge } from "@/components/reui/badge" import { Button, buttonVariants } from "@/components/ui/button" import { Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command" import { INIT_USERS } from "@/lib/users" import { fmtRate } from "@/lib/fmt-rate" import { formatNetflowRate } from "@/lib/map-netflow-hops" import { projectTrafficObservations } from "@/lib/traffic-observations" import { requestJson } from "@/shared/api/http-client" import { listAppUsers } from "@/shared/api/users" type AccessBinding = { id: string; node: string; name: string; kind: string; enabled?: boolean; peerScoped?: boolean; identity?: string } export type MapAccessUser = { id: string; name: string; login?: string; linux?: true; bindings: AccessBinding[] } type AccessRate = { rxNow: number | null; txNow: number | null } type UserTrafficSnapshot = { interfaces: Array<{ bindingId: string }>; observations?: { sampledAt?: string | null } } const mapUsers = (users: typeof INIT_USERS): MapAccessUser[] => users.map(user => ({ id: user.id, name: user.name || user.login, login: user.login, bindings: user.bindings.map(binding => ({ id: binding.id, node: binding.serverId, name: binding.interfaceName, kind: binding.interfaceType, peerScoped: Boolean(binding.peerPublicKey), identity: JSON.stringify([binding.serverId, binding.interfaceName, binding.peerPublicKey || null]) })), })) const demoUsers = mapUsers(INIT_USERS) export function useMapAccess(base: string | null, hasIx: boolean, refresh: number, userId: string | null) { const [directory, setDirectory] = useState<{ base: string; users: MapAccessUser[]; unavailable: boolean }>() const [linux, setLinux] = useState<{ base: string; users: MapAccessUser[]; unavailable: boolean }>() const [traffic, setTraffic] = useState<{ base: string; userId: string; user?: UserTrafficSnapshot }>() useEffect(() => { if (base === null) return const controller = new AbortController() void listAppUsers(base, { signal: controller.signal }).then(users => { if (!controller.signal.aborted) setDirectory({ base, users: mapUsers(users), unavailable: false }) }).catch(() => { if (!controller.signal.aborted) setDirectory({ base, users: [], unavailable: true }) }) return () => controller.abort() }, [base, refresh]) useEffect(() => { if (base === null || !hasIx) return const controller = new AbortController() const init = { signal: controller.signal } async function load() { const payload = await requestJson<{ items: IxSegment[] }>(base!, "/api/ix/segments?limit=100", init) const clients = new Map() function add(segment: IxSegment, node: number, iface: string, kind: string, name: string, enabled?: boolean, clientId?: string) { const id = "ix:" + (clientId ?? `${segment.id}:${node}:${iface}`) const user = clients.get(id) ?? { id, name, linux: true, bindings: [] } if (!user.bindings.some(binding => binding.node === String(node) && binding.name === iface)) { user.bindings.push({ id: `${node}:${iface}`, node: String(node), name: iface, kind, enabled }) } clients.set(id, user) } const applied = await Promise.allSettled(payload.items.map(segment => segment.appliedRevision === null ? [] : requestJson<{ items: IxLinuxBinding[] }>(base!, `/api/ix/segments/${encodeURIComponent(segment.id)}/linux`, init).then(result => result.items))) payload.items.forEach((segment, index) => { const rows = applied[index] if (rows.status === "fulfilled") for (const row of rows.value) { add(segment, row.serverId, row.interfaceName, row.kind, row.name ?? row.interfaceName, row.enabled, row.policy?.clientId) } }) if (!controller.signal.aborted) setLinux({ base: base!, users: [...clients.values()], unavailable: applied.some(result => result.status === "rejected") }) } void load().catch(() => { if (!controller.signal.aborted) setLinux({ base, users: [], unavailable: true }) }) return () => controller.abort() }, [base, hasIx, refresh]) useEffect(() => { if (base === null || !userId || userId.startsWith("ix:")) return const controller = new AbortController() let timer: ReturnType async function load() { try { const { user } = await requestJson<{ user: UserTrafficSnapshot }>(base!, `/api/traffic/users/${encodeURIComponent(userId!)}?range=5m`, { signal: controller.signal }) if (!controller.signal.aborted) setTraffic({ base: base!, userId: userId!, user }) } catch { if (!controller.signal.aborted) setTraffic({ base: base!, userId: userId! }) } finally { if (!controller.signal.aborted) { timer = setTimeout(() => { void load() }, 15_000) } } } void load() return () => { controller.abort(); clearTimeout(timer) } }, [base, refresh, userId]) const users = base === null ? demoUsers : directory?.base === base ? directory.users : [] const snapshot = traffic?.base === base && traffic.userId === userId ? traffic.user : undefined const rates = new Map() let userRate: ReturnType | undefined if (snapshot) { try { userRate = projectTrafficObservations(snapshot) } catch { /* Invalid measurements remain unknown. */ } for (const row of snapshot.interfaces ?? []) { try { rates.set(row.bindingId, projectTrafficObservations(row)) } catch { /* Invalid measurements remain unknown. */ } } } const bindingsByInterface = new Map() for (const user of users) for (const binding of user.bindings) { const key = JSON.stringify([binding.node, binding.name]) const entries = bindingsByInterface.get(key) ?? [] entries.push({ user: user.id, binding }) bindingsByInterface.set(key, entries) } for (const entries of bindingsByInterface.values()) for (const { user, binding } of entries) { if (entries.some(other => other.user !== user && other.binding.identity === binding.identity) || !binding.peerScoped && entries.some(other => other.binding.peerScoped)) rates.delete(binding.id) } return { users, linux: base !== null && hasIx && linux?.base === base ? linux.users : [], pending: base !== null && directory?.base !== base, unavailable: base !== null && directory?.base === base && directory.unavailable, linuxPending: base !== null && hasIx && linux?.base !== base, linuxUnavailable: base !== null && hasIx && linux?.base === base && linux.unavailable, rates, userRate, } } export function accessRate(bindings: AccessBinding[], rates?: Map) { let measured = 0, rx = 0, tx = 0 const counted = new Set() for (const binding of bindings) { const row = rates?.get(binding.id) const identity = binding.identity ?? binding.id if (row?.rxNow == null || row.txNow == null || counted.has(identity)) continue counted.add(identity) measured++ rx += row.rxNow tx += row.txNow } const total = new Set(bindings.map(binding => binding.identity ?? binding.id)).size return { measured, total, rx, tx, label: measured ? `${measured < total ? "≥ " : ""}${fmtRate(rx + tx)}` : "Нет замера" } } export function MapUserPicker({ open, onOpenChange, users, pending, unavailable, selectedUser, nodeName, onPick, onClear }: { open: boolean; onOpenChange: (open: boolean) => void; users: MapAccessUser[]; pending: boolean; unavailable: boolean; onPick: (user: MapAccessUser) => void selectedUser?: MapAccessUser; nodeName: (id: string) => string; onClear: () => void }) { const ordered = [...users].sort((a, b) => a.name.localeCompare(b.name, "ru")) return

Кого показать на карте?

Выберите пользователя, чтобы увидеть его подключения и сервисы.

{pending ? "Загрузка пользователей…" : unavailable ? "Каталог пользователей недоступен" : "Пользователи не найдены"} {selectedUser && Вся схема} {ordered.map(user => { const nodes = [...new Set(user.bindings.map(binding => nodeName(binding.node)))].sort() return binding.name)]} onSelect={() => onPick(user)}> {user.name} {[user.login !== user.name && user.login, ...nodes].filter(Boolean).join(" · ")} {selectedUser?.id === user.id ? На карте : {user.bindings.length} инт.} })}

↑ ↓ выбор · Enter открыть · Esc закрыть

} export function MapUserDetails({ user, groups, paths, services, rates, userRate, windowLabel, onClose, onService, nodeName, trafficHref }: { user: MapAccessUser; groups: Map; paths: FlowMapServicePath[]; services: FlowMapService[]; rates?: Map; windowLabel: string userRate?: ReturnType onClose: () => void; onService: (service: FlowMapService) => void; nodeName: (id: string) => string; trafficHref?: string }) { return <>

{user.name}

{user.linux ? "Linux-клиент IX" : user.login}

{!user.linux &&

Счётчики подключений · RouterOS

RX {fmtRate(userRate?.rxNow ?? null)} · TX {fmtRate(userRate?.txNow ?? null)}

{userRate?.observations?.sampledAt && (userRate.rxNow !== null || userRate.txNow !== null) && }
}

Подключения

{[...groups].map(([node, bindings]) => { const rate = accessRate(bindings, rates) return

{nodeName(node)}{rate.label}

{bindings.map(binding => `${binding.name} · ${binding.kind}${binding.enabled === false ? " · отключён" : ""}`).join(", ")}

{rate.measured > 0 &&

RX {fmtRate(rate.rx)} · TX {fmtRate(rate.tx)} · {rate.measured}/{rate.total}

}
})} {!groups.size &&

Нет привязок к узлам текущего вида.

}

Сервисы · IPFIX · {windowLabel}

{services.filter(service => paths.some(path => path.serviceId === service.id)).map(service => )} {!paths.length &&

Нет потоков с подтверждённой привязкой к пользователю.

} {!paths.length && user.bindings.some(binding => binding.peerScoped) &&

Для привязки IPFIX к peer последний опрос RouterOS должен подтвердить, что на интерфейсе он один.

}
{trafficHref && {user.linux ? "Открыть Linux-клиентов IX" : "Открыть в «Трафике»"}}
}