Files
MikrotikManager/components/network-map/map-access.tsx
T
Denozordec d174bca5d6
Docker images / prepare-release (push) Successful in 11s
Docker images / backend-test (push) Successful in 3s
Docker images / frontend-image (push) Successful in 2m14s
Docker images / updater-image (push) Successful in 40s
Docker images / netflow-agent-image (push) Successful in 34s
Docker images / backend-image (push) Successful in 16s
Docker images / publish-release (push) Successful in 10s
Docker images / notify-webhook (push) Successful in 1s
fix(ui): интегрировать макет карты сети и трафика
2026-11-26 23:27:54 +07:00

178 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"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, 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 }
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, userSelected: boolean) {
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; rates: Map<string, AccessRate> }>()
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<string, MapAccessUser>()
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 || !userSelected) return
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout>
async function load() {
const rates = new Map<string, AccessRate>()
try {
const payload = await requestJson<{ interfaces: Array<{ bindingId: string; status?: string }> }>(base!, "/api/traffic/bound-interfaces?range=5m", { signal: controller.signal })
for (const row of payload.interfaces) {
if (row.status === "offline") continue
try { rates.set(row.bindingId, projectTrafficObservations(row)) } catch { /* Invalid measurements remain unknown. */ }
}
} finally {
if (!controller.signal.aborted) {
setTraffic({ base: base!, rates })
timer = setTimeout(() => { void load().catch(() => {}) }, 15_000)
}
}
}
void load().catch(() => {})
return () => { controller.abort(); clearTimeout(timer) }
}, [base, refresh, userSelected])
const users = base === null ? demoUsers : directory?.base === base ? directory.users : []
const rates = new Map(base !== null && traffic?.base === base ? traffic.rates : undefined)
const bindingsByInterface = new Map<string, { user: string; binding: AccessBinding }[]>()
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,
}
}
export function accessRate(bindings: AccessBinding[], rates?: Map<string, AccessRate>) {
let measured = 0, rx = 0, tx = 0
const counted = new Set<string>()
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, onPick }: {
open: boolean; onOpenChange: (open: boolean) => void; users: MapAccessUser[]; pending: boolean; unavailable: boolean; onPick: (user: MapAccessUser) => void
}) {
return <CommandDialog open={open} onOpenChange={onOpenChange} title="Выбор пользователя" description="Поиск по имени, логину или интерфейсу">
<Command>
<CommandInput aria-label="Поиск пользователей" placeholder="Имя, логин или интерфейс…" />
<CommandList>
<CommandEmpty>{pending ? "Загрузка пользователей…" : unavailable ? "Каталог пользователей недоступен" : "Пользователи не найдены"}</CommandEmpty>
{users.map(user => <CommandItem key={user.id} value={user.id} keywords={[user.name, user.login ?? "", ...user.bindings.map(binding => binding.name)]} onSelect={() => onPick(user)}>
<UsersIcon aria-hidden /><span className="min-w-0 flex-1 truncate">{user.name}</span>
<Badge variant="outline" size="xs">{user.bindings.length}</Badge>
</CommandItem>)}
</CommandList>
</Command>
</CommandDialog>
}
export function MapUserDetails({ user, groups, paths, services, rates, windowLabel, onClose, onService, nodeName, trafficHref }: {
user: MapAccessUser; groups: Map<string, AccessBinding[]>; paths: FlowMapServicePath[]; services: FlowMapService[]; rates?: Map<string, AccessRate>; windowLabel: string
onClose: () => void; onService: (service: FlowMapService) => void; nodeName: (id: string) => string; trafficHref?: string
}) {
return <>
<header className="flex items-center gap-2 border-b p-3">
<UsersIcon className="size-4 shrink-0" aria-hidden />
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold">{user.name}</h2><p className="text-xs text-muted-foreground">{user.linux ? "Linux-клиент IX" : user.login}</p></div>
<Button size="icon-xs" variant="ghost" onClick={onClose} aria-label="Закрыть детали пользователя"><XIcon /></Button>
</header>
<div className="flex flex-col gap-3 overflow-y-auto p-3">
<section className="grid gap-2"><h3 className="text-xs text-muted-foreground">Подключения</h3>
{[...groups].map(([node, bindings]) => {
const rate = accessRate(bindings, rates)
return <div key={node} className="grid gap-1 text-xs">
<p className="flex justify-between gap-2 font-medium"><span>{nodeName(node)}</span><span className="shrink-0 font-mono">{rate.label}</span></p>
<p className="text-muted-foreground wrap-anywhere">{bindings.map(binding => `${binding.name} · ${binding.kind}${binding.enabled === false ? " · отключён" : ""}`).join(", ")}</p>
{rate.measured > 0 && <p className="font-mono text-muted-foreground">RX {fmtRate(rate.rx)} · TX {fmtRate(rate.tx)} · {rate.measured}/{rate.total}</p>}
</div>
})}
{!groups.size && <p className="text-xs text-muted-foreground">Нет привязок к узлам текущего вида.</p>}
</section>
<section className="grid gap-1 border-t pt-3"><h3 className="text-xs text-muted-foreground">Сервисы · IPFIX · {windowLabel}</h3>
{services.filter(service => paths.some(path => path.serviceId === service.id)).map(service => <Button key={service.id} variant="ghost" size="xs" className="w-full justify-between" onClick={() => onService(service)}>{service.label}<span className="font-mono">{formatNetflowRate(service)}</span></Button>)}
{!paths.length && <p className="text-xs text-muted-foreground">Нет потоков с подтверждённой привязкой к пользователю.</p>}
</section>
{trafficHref && <Link href={trafficHref} className={buttonVariants({size:"xs"})}>{user.linux ? "Открыть Linux-клиентов IX" : "Открыть в «Трафике»"}</Link>}
</div>
</>
}