Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4097e1a6fc | ||
|
|
7cf17c7283 | ||
|
|
4eafc78c8e | ||
|
|
d174bca5d6 | ||
|
|
2ca40fbb4d | ||
|
|
589fc782f9 | ||
|
|
fcbf219725 | ||
|
|
95a0ebeb18 | ||
|
|
2b0b9a5fa5 | ||
|
|
9b2c2327a6 | ||
|
|
ec2fb54e04 |
No files matched your search
@@ -22,7 +22,7 @@ export default function MainLayout({ children }: { children: ReactNode }) {
|
||||
К содержимому
|
||||
</a>
|
||||
<AppSidebar />
|
||||
<SidebarInset tabIndex={-1} id="main-content" className="h-svh overflow-hidden md:h-[calc(100svh-1rem)] md:peer-data-[variant=inset]:rounded-[calc(var(--radius)*1.6)] md:peer-data-[variant=inset]:border">
|
||||
<SidebarInset tabIndex={-1} id="main-content" className="h-svh overflow-hidden">
|
||||
{children}
|
||||
</SidebarInset>
|
||||
<CommandPalette />
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useMemo, useEffect, type ReactNode } from "react"
|
||||
import { Suspense, useState, useMemo, useEffect, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import { Alert, AlertTitle, AlertDescription } from "@/components/reui/alert"
|
||||
import { peakOfCombinedTraffic, projectTrafficObservations, sumObservedTraffic, type TrafficObservationMeta } from "@/lib/traffic-observations"
|
||||
import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status"
|
||||
@@ -13,13 +15,13 @@ import { SectionFrame, ToneBadge, type Tone } from "@/components/reui-kit/ops-bl
|
||||
import { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
|
||||
import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart"
|
||||
import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-chart"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { Sparkline } from "@/components/sparkline"
|
||||
import { StatusDot } from "@/components/status-dot"
|
||||
import { Flag } from "@/components/flag"
|
||||
import {
|
||||
RefreshCwIcon, TrendingUpIcon, ChartPieIcon,
|
||||
ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon,
|
||||
ArrowUpIcon, ArrowDownIcon, ActivityIcon, UsersIcon, CableIcon, ServerIcon, SearchIcon, GitBranchIcon, PlusIcon, MapIcon,
|
||||
} from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { fmtGiB, fmtRate } from "@/lib/fmt-rate"
|
||||
@@ -37,6 +39,7 @@ import { Badge } from "@/components/reui/badge"
|
||||
import {
|
||||
IFACE_TYPE_LABEL,
|
||||
INIT_USERS,
|
||||
MOCK_IFACE_CATALOG,
|
||||
ROLE_LABEL,
|
||||
type InterfaceType,
|
||||
} from "@/lib/users"
|
||||
@@ -338,6 +341,7 @@ const TRAFFIC_RANGE_LABELS: Record<(typeof TRAFFIC_RANGE_KEYS)[number], string>
|
||||
|
||||
type GroupMode = "servers" | "users" | "ifaces" | "flows"
|
||||
type FlowScope = "servers" | "users"
|
||||
const ALL_EXPORTERS = "__all_exporters__"
|
||||
type SortField = "rx" | "tx" | "name" | "sessions"
|
||||
type SortDir = "asc" | "desc"
|
||||
|
||||
@@ -671,7 +675,7 @@ function ServerDetail({
|
||||
</div>
|
||||
</DetailHeader>
|
||||
<TrafficObservationStatus observations={sel.observations} unknown={sel.rxNow == null || sel.txNow == null} />
|
||||
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
|
||||
<TrafficRxTxChart key={range} rx={sel.rxSeries} tx={sel.txSeries} range={range} scrub embedded />
|
||||
<KvStats
|
||||
label="Скорость выбранного сервера"
|
||||
items={[
|
||||
@@ -703,7 +707,7 @@ function UserDetail({ sel, range, setRange }: { sel: UserTraffic; range: Range;
|
||||
<OfflinePlaceholder text="Нет привязанных интерфейсов у этого пользователя" />
|
||||
) : (
|
||||
<>
|
||||
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
|
||||
<TrafficRxTxChart key={range} rx={sel.rxSeries} tx={sel.txSeries} range={range} scrub embedded />
|
||||
<KvStats
|
||||
label="Скорость выбранного клиента"
|
||||
items={[
|
||||
@@ -742,7 +746,7 @@ function IfaceDetail({ sel, range, setRange }: { sel: BoundIfaceTraffic; range:
|
||||
<Flag code={sel.serverCountry} />{sel.serverSite}
|
||||
</span>
|
||||
</DetailHeader>
|
||||
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
|
||||
<TrafficRxTxChart key={range} rx={sel.rxSeries} tx={sel.txSeries} range={range} scrub embedded />
|
||||
<KvStats
|
||||
label="Скорость выбранного интерфейса"
|
||||
items={[
|
||||
@@ -818,6 +822,38 @@ const toLiveUser = (u: UserTraffic & { interfaces?: BoundIfaceTraffic[] }): User
|
||||
}
|
||||
|
||||
export default function TrafficPage() {
|
||||
return <Suspense fallback={<p role="status" className="p-4 text-sm">Загрузка трафика…</p>}><TrafficRoute /></Suspense>
|
||||
}
|
||||
|
||||
function TrafficRoute() {
|
||||
const params = useSearchParams()
|
||||
const read = (name: string, limit: number) => {
|
||||
const value = params.get(name)?.trim()
|
||||
return value && value.length <= limit ? value : undefined
|
||||
}
|
||||
const user = read("user", 128), server = read("server", 64)
|
||||
const service = read("service", 200)
|
||||
const map = new URLSearchParams()
|
||||
const ix = params.get("mapView") === "ix"
|
||||
if (ix) map.set("filter", "ix-node")
|
||||
const mapUser = read("mapUser", 128) ?? user
|
||||
if (mapUser) map.set("user", mapUser)
|
||||
const serviceId = read("serviceId", 240)
|
||||
if (serviceId) {
|
||||
map.set("service", serviceId)
|
||||
if (serviceId.startsWith("cc:")) map.set("dest", "countries")
|
||||
}
|
||||
else if (server) map.set("server", server)
|
||||
const view: GroupMode = params.get("view") === "flows" ? "flows" : user ? "users" : "servers"
|
||||
const ids = (name: string) => (params.get(name) ?? "").slice(0, 4096).split(",").filter(id => /^[1-9]\d*$/.test(id))
|
||||
const exporters = view === "flows" && params.has("exporters") ? ids("exporters") : undefined
|
||||
return <TrafficContent key={params.toString()} view={view} user={user} server={server} service={service} country={read("country", 32)}
|
||||
exporters={exporters} mapNodes={params.has("nodes") ? ids("nodes") : undefined} returnHref={params.get("from") === "map" ? `/network-map${map.size ? `?${map}` : ""}` : undefined} />
|
||||
}
|
||||
|
||||
function TrafficContent({ view, user, server, service, country, exporters: mapExporters, mapNodes, returnHref }: {
|
||||
view: GroupMode; user?: string; server?: string; service?: string; country?: string; exporters?: string[]; mapNodes?: string[]; returnHref?: string
|
||||
}) {
|
||||
const { mode, backendUrl } = useDataSource()
|
||||
const isLive = mode === "live"
|
||||
const [trafficClock, setTrafficClock] = useState(() => Date.now())
|
||||
@@ -828,11 +864,13 @@ export default function TrafficPage() {
|
||||
}, [isLive])
|
||||
const apiFetch = useMemo(() => makeApiFetch(backendUrl), [backendUrl])
|
||||
|
||||
const [groupMode, setGroupMode] = useState<GroupMode>("servers")
|
||||
const [groupMode, setGroupMode] = useState<GroupMode>(view)
|
||||
const [sortField, setSortField] = useState<SortField>("rx")
|
||||
const [sortDir, setSortDir] = useState<SortDir>("desc")
|
||||
const [selectedId, setSelectedId] = useState("srv1")
|
||||
const [range, setRange] = useState<Range>("1h")
|
||||
const linkedId = view === "servers" ? server : user ?? server
|
||||
const [selectedId, setSelectedId] = useState(linkedId ?? (view === "flows" ? mapExporters ? "" : ALL_EXPORTERS : "srv1"))
|
||||
const keptLink = groupMode === view && selectedId === linkedId
|
||||
const [range, setRange] = useState<Range>(view === "flows" ? "5m" : "1h")
|
||||
const [search, setSearch] = useState("")
|
||||
const [trafficRetry, setTrafficRetry] = useState(0)
|
||||
const [liveRetry, setLiveRetry] = useState(0)
|
||||
@@ -854,7 +892,7 @@ export default function TrafficPage() {
|
||||
const [detailResult, setDetailResult] = useState<{ key: string; server: ServerTraffic | null; receivedAt?: number; error: string | null } | null>(null)
|
||||
const [liveUsers, setLiveUsers] = useState<UserTraffic[]>([])
|
||||
const [liveBoundIfaces, setLiveBoundIfaces] = useState<BoundIfaceTraffic[]>([])
|
||||
const [flowScope, setFlowScope] = useState<FlowScope>("servers")
|
||||
const [flowScope, setFlowScope] = useState<FlowScope>(user ? "users" : "servers")
|
||||
const [flowRetry, setFlowRetry] = useState(0)
|
||||
const flowKey = JSON.stringify([isLive, groupMode, backendUrl, range, flowScope, flowRetry])
|
||||
const [flowResult, setFlowResult] = useState<{ key: string; receivedAt?: number; monthlyServers?: ServerRead[]; stats?: FlowStatsDto; exporters?: FlowEntityCard[]; clients?: FlowEntityCard[]; cardWindow?: FlowStatsDto["sourceWindow"]; error?: string } | null>(null)
|
||||
@@ -868,7 +906,7 @@ export default function TrafficPage() {
|
||||
&& trafficClock - collectorReading.receivedAt > 35_000
|
||||
? { ...collectorReading.status, listenerBound: false, collectorCountersSource: "last-known" }
|
||||
: collectorReading.status
|
||||
const flowExporters = useMemo(() => currentFlows?.exporters ?? [], [currentFlows])
|
||||
const flowExporters = useMemo(() => (currentFlows?.exporters ?? []).filter(card => !mapExporters || mapExporters.includes(card.id)), [currentFlows, mapExporters])
|
||||
const flowClients = useMemo(() => currentFlows?.clients ?? [], [currentFlows])
|
||||
const [flowMonth, setFlowMonth] = useState(() => new Date().toISOString().slice(0, 7))
|
||||
const flowMonthValid = /^(?!0000)\d{4}-(0[1-9]|1[0-2])$/.test(flowMonth) && flowMonth <= new Date().toISOString().slice(0, 7)
|
||||
@@ -884,6 +922,7 @@ export default function TrafficPage() {
|
||||
const [overlayOpen, setOverlayOpen] = useState(false)
|
||||
const [catalogServers, setCatalogServers] = useState<ServerRead[]>([])
|
||||
const effectiveMode: GroupMode = groupMode
|
||||
const allExporters = !mapExporters && flowScope === "servers" && selectedId === ALL_EXPORTERS && range !== "30d"
|
||||
const detailKey = JSON.stringify([isLive, backendUrl, effectiveMode, selectedId, range, selectedIface, detailRetry])
|
||||
const currentDetail = detailResult?.key === detailKey ? detailResult : null
|
||||
const detailBusy = isLive && effectiveMode === "servers" && Boolean(selectedId) && currentDetail === null
|
||||
@@ -898,7 +937,7 @@ export default function TrafficPage() {
|
||||
range === "30d"
|
||||
? /^[1-9]\d*$/.test(selectedId) && Number.isSafeInteger(Number(selectedId)) && Boolean(currentFlows?.monthlyServers?.some(server => String(server.id) === selectedId))
|
||||
: flowScope === "servers"
|
||||
? /^[1-9]\d*$/.test(selectedId) && Number.isSafeInteger(Number(selectedId)) && flowExporters.some(card => card.id === selectedId)
|
||||
? allExporters || /^[1-9]\d*$/.test(selectedId) && Number.isSafeInteger(Number(selectedId)) && flowExporters.some(card => card.id === selectedId)
|
||||
: Boolean(selectedId) && flowClients.some(card => card.id === selectedId)
|
||||
)
|
||||
const flowLiveEnabled = confirmedFlowSelection && effectiveMode === "flows" && range === "5m"
|
||||
@@ -906,7 +945,7 @@ export default function TrafficPage() {
|
||||
enabled: flowLiveEnabled,
|
||||
backendUrl,
|
||||
range,
|
||||
serverId: flowScope === "servers" ? selectedId : undefined,
|
||||
serverId: flowScope === "servers" && !allExporters ? selectedId : undefined,
|
||||
userId: flowScope === "users" ? selectedId : undefined,
|
||||
iface: flowIface,
|
||||
dedup: flowDedup,
|
||||
@@ -916,17 +955,32 @@ export default function TrafficPage() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLive || groupMode === "flows") return
|
||||
let cancelled = false
|
||||
const loadLiveTraffic = async (targetRange: Range) => {
|
||||
const key = JSON.stringify([isLive, backendUrl, targetRange, groupMode, trafficRetry])
|
||||
const controller = new AbortController()
|
||||
const init = { signal: controller.signal }
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const q = encodeURIComponent(range === "30d" ? "24h" : range)
|
||||
async function refreshUsers() {
|
||||
try {
|
||||
const { users } = await apiFetch<{ users: UserTraffic[] }>(`/api/traffic/users?range=${q}`, init)
|
||||
if (!controller.signal.aborted) {
|
||||
setLiveUsers(users.map(toLiveUser))
|
||||
const receivedAt = Date.now()
|
||||
setTrafficState(state => state?.key === trafficKey ? {...state, receivedAt} : state)
|
||||
}
|
||||
} catch {
|
||||
// Keep the last valid observation until its own expiry.
|
||||
} finally {
|
||||
if (!controller.signal.aborted) timer = setTimeout(() => { void refreshUsers() }, 15_000)
|
||||
}
|
||||
}
|
||||
const loadLiveTraffic = async () => {
|
||||
try {
|
||||
const q = encodeURIComponent(targetRange === "30d" ? "24h" : targetRange)
|
||||
const [srvRes, usersRes, ifacesRes] = await Promise.all([
|
||||
apiFetch<{ servers: LiveTrafficServer[]; peaks?: { rx: number | null; tx: number | null } }>(`/api/traffic/servers?range=${q}`),
|
||||
apiFetch<{ users: UserTraffic[] }>(`/api/traffic/users?range=${q}`),
|
||||
apiFetch<{ interfaces: BoundIfaceTraffic[] }>(`/api/traffic/bound-interfaces?range=${q}`),
|
||||
apiFetch<{ servers: LiveTrafficServer[]; peaks?: { rx: number | null; tx: number | null } }>(`/api/traffic/servers?range=${q}`, init),
|
||||
apiFetch<{ users: UserTraffic[] }>(`/api/traffic/users?range=${q}`, init),
|
||||
apiFetch<{ interfaces: BoundIfaceTraffic[] }>(`/api/traffic/bound-interfaces?range=${q}`, init),
|
||||
])
|
||||
if (cancelled) return
|
||||
if (controller.signal.aborted) return
|
||||
const liveIfaces = ifacesRes.interfaces.map(toLiveBound)
|
||||
const mapped: ServerTraffic[] = srvRes.servers.map((s) => {
|
||||
const base = toLiveServer(s)
|
||||
@@ -937,19 +991,21 @@ export default function TrafficPage() {
|
||||
setLiveServerOwner(JSON.stringify([isLive, backendUrl]))
|
||||
setLiveUsers(mappedUsers)
|
||||
setLiveBoundIfaces(liveIfaces)
|
||||
setTrafficState({ key, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
|
||||
setTrafficState({ key: trafficKey, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
|
||||
if (groupMode === "users") timer = setTimeout(() => { void refreshUsers() }, 15_000)
|
||||
setSelectedId((prev) => {
|
||||
if (groupMode === view && prev === linkedId) return prev
|
||||
if (groupMode === "users") return mappedUsers.some((x) => x.id === prev) ? prev : (mappedUsers[0]?.id ?? "")
|
||||
if (groupMode === "ifaces") return liveIfaces.some((x) => x.id === prev) ? prev : (liveIfaces[0]?.id ?? "")
|
||||
return mapped.some((x) => x.id === prev) ? prev : (mapped[0]?.id ?? "")
|
||||
})
|
||||
} catch (e) {
|
||||
if (!cancelled) setTrafficState({ key, status: "error", error: e instanceof Error ? e.message : "Не удалось загрузить трафик" })
|
||||
if (!controller.signal.aborted) setTrafficState({ key: trafficKey, status: "error", error: e instanceof Error ? e.message : "Не удалось загрузить трафик" })
|
||||
}
|
||||
}
|
||||
void loadLiveTraffic(range)
|
||||
return () => { cancelled = true }
|
||||
}, [apiFetch, isLive, groupMode, backendUrl, trafficRetry, range])
|
||||
void loadLiveTraffic()
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [apiFetch, isLive, groupMode, backendUrl, trafficKey, range, view, linkedId])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLive || groupMode !== "flows" || range === "30d") return
|
||||
@@ -979,8 +1035,9 @@ export default function TrafficPage() {
|
||||
if (range === "30d") {
|
||||
void listServers(backendUrl).then(servers => {
|
||||
if (cancelled) return
|
||||
setFlowResult({ key: flowKey, receivedAt: Date.now(), monthlyServers: servers })
|
||||
setSelectedId(prev => servers.some(server => String(server.id) === prev) ? prev : String(servers[0]?.id ?? ""))
|
||||
const available = mapExporters ? servers.filter(server => mapExporters.includes(String(server.id))) : servers
|
||||
setFlowResult({ key: flowKey, receivedAt: Date.now(), monthlyServers: available })
|
||||
setSelectedId(prev => available.some(server => String(server.id) === prev) ? prev : String(available[0]?.id ?? ""))
|
||||
}).catch(error => {
|
||||
if (!cancelled) setFlowResult({ key: flowKey, error: error instanceof Error ? error.message : "Не удалось загрузить каталог серверов" })
|
||||
})
|
||||
@@ -997,7 +1054,9 @@ export default function TrafficPage() {
|
||||
setFlowResult({ key: flowKey, receivedAt: Date.now(), stats, exporters: exporters.exporters, clients: clients.clients,
|
||||
cardWindow: flowScope === "users" ? clients.sourceWindow : exporters.sourceWindow })
|
||||
setSelectedId(prev => {
|
||||
const list = flowScope === "users" ? clients.clients : exporters.exporters
|
||||
const list = flowScope === "users" ? clients.clients : exporters.exporters.filter(card => !mapExporters || mapExporters.includes(card.id))
|
||||
if (flowScope === "servers" && (prev === ALL_EXPORTERS || mapExporters && !prev)) return prev
|
||||
if (flowScope === (user ? "users" : "servers") && prev === linkedId) return prev
|
||||
return list.some(x => x.id === prev) ? prev : (list[0]?.id ?? "")
|
||||
})
|
||||
}
|
||||
@@ -1005,7 +1064,7 @@ export default function TrafficPage() {
|
||||
if (!cancelled) setFlowResult({ key: flowKey, error: e instanceof Error ? e.message : "Не удалось загрузить потоки" })
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [isLive, effectiveMode, backendUrl, range, flowScope, flowKey])
|
||||
}, [isLive, effectiveMode, backendUrl, range, flowScope, flowKey, user, linkedId, mapExporters])
|
||||
|
||||
const analyticsKey = JSON.stringify([flowKey, selectedId, flowIface, flowDedup, flowExcludeMesh, flowExcludeOverlay, analyticsRetry, range === "30d" ? flowMonth : null])
|
||||
const currentAnalytics = analyticsResult?.key === analyticsKey ? analyticsResult : null
|
||||
@@ -1016,7 +1075,7 @@ export default function TrafficPage() {
|
||||
const request = range === "30d"
|
||||
? getFlowMonthly(backendUrl, { month: flowMonth, serverId: flowScope === "servers" ? selectedId : undefined }).then(monthly => ({ monthly }))
|
||||
: getFlowAnalytics(backendUrl, {
|
||||
range, serverId: flowScope === "servers" ? selectedId : undefined,
|
||||
range, serverId: flowScope === "servers" && !allExporters ? selectedId : undefined,
|
||||
userId: flowScope === "users" ? selectedId : undefined,
|
||||
iface: flowIface, dedup: flowDedup, excludeMesh: flowExcludeMesh, excludeOverlay: flowExcludeOverlay,
|
||||
}).then(data => ({ data }))
|
||||
@@ -1026,7 +1085,7 @@ export default function TrafficPage() {
|
||||
if (!cancelled) setAnalyticsResult({ key: analyticsKey, error: e instanceof Error ? e.message : "Не удалось загрузить аналитику" })
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [confirmedFlowSelection, isLive, effectiveMode, selectedId, range, flowScope, flowIface, flowDedup, flowExcludeMesh, flowExcludeOverlay, backendUrl, analyticsKey, flowMonth, flowMonthValid])
|
||||
}, [confirmedFlowSelection, isLive, effectiveMode, selectedId, range, flowScope, allExporters, flowIface, flowDedup, flowExcludeMesh, flowExcludeOverlay, backendUrl, analyticsKey, flowMonth, flowMonthValid])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLive) return
|
||||
@@ -1036,26 +1095,22 @@ export default function TrafficPage() {
|
||||
const activeServerTraffic = useMemo(() => isLive ? (trafficReady ? liveServers.map(s => ({ ...s, ...projectTrafficObservations(s, trafficClock) })) : []) : serverTraffic, [isLive, trafficReady, liveServers, trafficClock])
|
||||
const activeUserTraffic = useMemo(() => isLive ? (trafficReady ? liveUsers.map(u => ({ ...u, ...projectTrafficObservations(u, trafficClock), interfaces: u.interfaces.map(toLiveBound) })) : []) : userTraffic, [isLive, trafficReady, liveUsers, trafficClock])
|
||||
const activeBoundIfaces = useMemo(() => isLive ? (trafficReady ? liveBoundIfaces.map(c => ({ ...c, ...projectTrafficObservations(c, trafficClock), status: projectTrafficBindingStatus(c.status,c.statusObservedAt,c.statusExpiresAt,trafficClock) })) : []) : boundIfaces, [isLive, trafficReady, liveBoundIfaces, trafficClock])
|
||||
const visibleIfaces = useMemo(
|
||||
() => hideDisabledIfaces ? serverIfaces.filter((i) => !i.disabled && i.running) : serverIfaces,
|
||||
[serverIfaces, hideDisabledIfaces],
|
||||
)
|
||||
const ifaceCatalog = isLive ? serverIfaces : MOCK_IFACE_CATALOG[selectedId] ?? []
|
||||
const visibleIfaces = hideDisabledIfaces ? ifaceCatalog.filter(i => !i.disabled && i.running) : ifaceCatalog
|
||||
|
||||
useEffect(() => {
|
||||
if (!confirmedLiveServer || effectiveMode !== "servers") {
|
||||
if (!isLive || !confirmedLiveServer || effectiveMode !== "servers") {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setServerIfaces([])
|
||||
setSelectedIface("__all__")
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
setServerIfaces([])
|
||||
setSelectedIface("__all__")
|
||||
apiFetch<{ interfaces: LiveTrafficInterface[] }>(`/api/traffic/servers/${encodeURIComponent(selectedId)}/interfaces`)
|
||||
.then((res) => { if (!cancelled) setServerIfaces(res.interfaces) })
|
||||
.catch(() => { if (!cancelled) setServerIfaces([]) })
|
||||
return () => { cancelled = true }
|
||||
}, [confirmedLiveServer, selectedId, effectiveMode, apiFetch])
|
||||
}, [isLive, confirmedLiveServer, selectedId, effectiveMode, apiFetch])
|
||||
|
||||
useEffect(() => {
|
||||
if (!confirmedLiveServer || effectiveMode !== "servers") {
|
||||
@@ -1078,6 +1133,7 @@ export default function TrafficPage() {
|
||||
|
||||
const handleModeChange = (next: GroupMode) => {
|
||||
setGroupMode(next)
|
||||
setSelectedIface("__all__")
|
||||
if (next === "servers") {
|
||||
setSelectedId(activeServerTraffic[0]?.id ?? "srv1")
|
||||
if (range === "30d") setRange("1h")
|
||||
@@ -1165,12 +1221,15 @@ export default function TrafficPage() {
|
||||
const monthlyServer = monthlyServers.find(server => String(server.id) === selectedId)
|
||||
const selFlowCard = range === "30d"
|
||||
? (monthlyServer ? { id: String(monthlyServer.id), name: monthlyServer.name, country: monthlyServer.country, site: monthlyServer.site } : null)
|
||||
: flowCards.find((c) => c.id === selectedId) ?? null
|
||||
: allExporters ? { id: ALL_EXPORTERS, name: "Все экспортёры", country: "", site: "" } : flowCards.find((c) => c.id === selectedId) ?? null
|
||||
const displayedFlow = currentFlows && !liveError ? (flowLiveSample ?? currentAnalytics?.data ?? null) : null
|
||||
|
||||
const selServer = useMemo(() => activeServerTraffic.find(s => s.id === selectedId) ?? activeServerTraffic[0], [selectedId, activeServerTraffic])
|
||||
const detailServer = isLive ? (currentDetail?.server ? { ...currentDetail.server, ...projectTrafficObservations(currentDetail.server, trafficClock), boundIfaces: currentDetail.server.boundIfaces.map(toLiveBound) } : null) : selServer
|
||||
const selUser = useMemo(() => activeUserTraffic.find(u => u.id === selectedId) ?? activeUserTraffic[0], [selectedId, activeUserTraffic])
|
||||
const selServer = activeServerTraffic.find(s => s.id === selectedId) ?? (keptLink ? undefined : activeServerTraffic[0])
|
||||
const demoIfaceRows = !isLive && selectedIface !== "__all__" ? selServer?.boundIfaces.filter(row => row.interfaceName === selectedIface && !row.peerPublicKey) ?? [] : []
|
||||
const detailServer = isLive ? (currentDetail?.server ? { ...currentDetail.server, ...projectTrafficObservations(currentDetail.server, trafficClock), boundIfaces: currentDetail.server.boundIfaces.map(toLiveBound) } : null)
|
||||
: selServer && selectedIface !== "__all__" ? demoIfaceRows.length === 1 ? { ...selServer, ...demoIfaceRows[0], id: selServer.id, name: selServer.name, status: selServer.status, boundIfaces: [] } : null
|
||||
: selServer
|
||||
const selUser = activeUserTraffic.find(u => u.id === selectedId) ?? (keptLink ? undefined : activeUserTraffic[0])
|
||||
const selIface = useMemo(() => activeBoundIfaces.find(c => c.id === selectedId) ?? activeBoundIfaces[0], [selectedId, activeBoundIfaces])
|
||||
|
||||
const kpiSource = effectiveMode === "users"
|
||||
@@ -1270,7 +1329,7 @@ export default function TrafficPage() {
|
||||
ifaces: (isLive ? liveBoundIfaces : boundIfaces).length,
|
||||
flows: null,
|
||||
}
|
||||
const refreshBusy = isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)
|
||||
const refreshBusy = isLive && (effectiveMode === "flows" ? liveBusy || analyticsLoading : trafficLoading || detailBusy && confirmedLiveServer)
|
||||
const listTitle = effectiveMode === "servers" ? "Серверы" : effectiveMode === "users" ? "Клиенты" : "Интерфейсы"
|
||||
const listShown = effectiveMode === "servers" ? sortedServers.length : effectiveMode === "users" ? sortedUsers.length : sortedIfaces.length
|
||||
|
||||
@@ -1286,14 +1345,19 @@ export default function TrafficPage() {
|
||||
description="Счётчики интерфейсов и потоки IPFIX по серверам, клиентам и интерфейсам"
|
||||
actions={
|
||||
<>
|
||||
{returnHref && <Link className={buttonVariants({variant:"outline"})} href={returnHref}><MapIcon aria-hidden />Вернуться на карту</Link>}
|
||||
<Button type="button" variant="outline" onClick={() => { handleModeChange("flows"); setRange("30d") }}>Месячный отчёт</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (effectiveMode === "flows") setFlowRetry(value => value + 1)
|
||||
else setTrafficRetry(value => value + 1)
|
||||
else {
|
||||
setTrafficRetry(value => value + 1)
|
||||
if (effectiveMode === "servers") { setDetailRetry(value => value + 1); setLiveRetry(value => value + 1) }
|
||||
}
|
||||
}}
|
||||
disabled={refreshBusy}
|
||||
aria-busy={refreshBusy}
|
||||
>
|
||||
<RefreshCwIcon className={cn("size-4", refreshBusy && "animate-spin")} />Обновить
|
||||
</Button>
|
||||
@@ -1315,6 +1379,12 @@ export default function TrafficPage() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<details className="text-sm text-muted-foreground">
|
||||
<summary className="cursor-pointer font-medium text-foreground">Как читать трафик</summary>
|
||||
<p className="mt-2">Серверы, клиенты и интерфейсы показывают измеренные RX и TX. В «Потоках» скорость усреднена по доступному окну IPFIX. Месячный отчёт показывает накопленный объём.</p>
|
||||
</details>
|
||||
{keptLink && (effectiveMode === "flows" ? !liveBusy && !liveError && !selFlowCard : (trafficReady || !isLive) && (effectiveMode === "users" ? !selUser : !selServer)) &&
|
||||
<Alert><AlertTitle>Объект из ссылки недоступен</AlertTitle><AlertDescription>Выберите доступный объект в списке.</AlertDescription></Alert>}
|
||||
{!(effectiveMode === "flows" && range === "30d") && (!isLive || !(effectiveMode === "flows" ? liveError : trafficError)) && <KpiStatGrid
|
||||
isLoading={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)}
|
||||
aria-label="Сводка трафика"
|
||||
@@ -1362,6 +1432,7 @@ export default function TrafficPage() {
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={flowScope === "users"}
|
||||
disabled={Boolean(mapExporters)}
|
||||
onClick={() => { setFlowScope("users"); setFlowIface("__all__"); if (range === "30d") setRange("1h") }}
|
||||
className={cn(
|
||||
"text-xs px-2 py-0.5 rounded border transition-colors",
|
||||
@@ -1403,6 +1474,8 @@ export default function TrafficPage() {
|
||||
</div>
|
||||
{range === "30d" && <p className="text-xs text-muted-foreground">Серверы из каталога, включая неактивные. Удалённые серверы в список не входят.</p>}
|
||||
<div className="flex flex-col gap-2">
|
||||
{!mapExporters && flowScope === "servers" && range !== "30d" && <Button type="button" size="sm" variant={allExporters ? "secondary" : "outline"} aria-pressed={allExporters} onClick={() => setSelectedId(ALL_EXPORTERS)}>Все экспортёры</Button>}
|
||||
{mapExporters && flowScope === "servers" && range !== "30d" && !selectedId && <p className="text-xs text-muted-foreground">{mapExporters.length ? "Выберите экспортёра этого сервиса." : "Экспортёр этого сервиса не подтверждён."}</p>}
|
||||
{range === "30d" ? visibleMonthlyServers.map(server => <Button key={server.id} variant="outline" className="justify-start whitespace-normal break-all h-auto py-2" aria-pressed={String(server.id) === selectedId} onClick={() => setSelectedId(String(server.id))}>{server.name}</Button>) : sortedFlowCards.map((card) => (
|
||||
<FlowEntityCardView
|
||||
key={card.id}
|
||||
@@ -1442,6 +1515,9 @@ export default function TrafficPage() {
|
||||
excludeOverlay={flowExcludeOverlay}
|
||||
onExcludeOverlay={setFlowExcludeOverlay}
|
||||
liveHint={flowLiveHint}
|
||||
initialService={view === "flows" ? service : undefined}
|
||||
initialCountry={country}
|
||||
mapNodes={mapNodes}
|
||||
emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)}
|
||||
/>
|
||||
</FramePanel>
|
||||
@@ -1456,7 +1532,7 @@ export default function TrafficPage() {
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid min-w-0 grid-cols-1 xl:grid-cols-[300px_minmax(0,1fr)] gap-4 items-start">
|
||||
<div className="grid min-w-0 grid-cols-1 gap-3 items-start lg:grid-cols-[minmax(12rem,17rem)_minmax(0,1fr)]">
|
||||
{/* ── left panel ── */}
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<SectionFrame title={listTitle} description={`${listShown} из ${modeCount[effectiveMode] ?? listShown} · сортировка и поиск`} panelClassName="flex flex-col gap-3 p-2.5">
|
||||
@@ -1494,9 +1570,9 @@ export default function TrafficPage() {
|
||||
</p>
|
||||
)}
|
||||
{/* entity list */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex max-h-72 flex-col gap-2 overflow-y-auto p-0.5 lg:max-h-[26rem]">
|
||||
{effectiveMode === "servers" && sortedServers.map(s => (
|
||||
<ServerCard key={s.id} s={s} selected={s.id === selectedId} onClick={() => setSelectedId(s.id)} />
|
||||
<ServerCard key={s.id} s={s} selected={s.id === selectedId} onClick={() => { if (s.id !== selectedId) setSelectedIface("__all__"); setSelectedId(s.id) }} />
|
||||
))}
|
||||
{effectiveMode === "users" && sortedUsers.map(u => (
|
||||
<UserCard key={u.id} u={u} selected={u.id === selectedId} onClick={() => setSelectedId(u.id)} />
|
||||
@@ -1513,13 +1589,13 @@ export default function TrafficPage() {
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<SectionFrame bare className="w-full min-w-0">
|
||||
<FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
|
||||
{isLive && effectiveMode === "servers" && (
|
||||
<div className="mb-3 pb-3 border-b">
|
||||
{effectiveMode === "servers" && (
|
||||
<div role="group" aria-label="Интерфейсы выбранного сервера" className="mb-3 pb-3 border-b">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-xs text-muted-foreground mr-1">Интерфейс:</span>
|
||||
<button
|
||||
type="button" aria-pressed={hideDisabledIfaces}
|
||||
onClick={() => setHideDisabledIfaces((v) => !v)}
|
||||
onClick={() => { if (!hideDisabledIfaces && ifaceCatalog.some(iface => iface.name === selectedIface && (iface.disabled || !iface.running))) setSelectedIface("__all__"); setHideDisabledIfaces(value => !value) }}
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium transition-all",
|
||||
hideDisabledIfaces
|
||||
@@ -1565,6 +1641,7 @@ export default function TrafficPage() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!isLive && effectiveMode === "servers" && selectedIface !== "__all__" && !detailServer && <OfflinePlaceholder text="В демоснимке нет замеров этого интерфейса" />}
|
||||
{isLive && effectiveMode === "servers" && !detailServer && <>
|
||||
<DetailHeader range={range} setRange={setRange}><h2 className="text-base font-semibold">{selServer?.name ?? "Трафик сервера"}</h2></DetailHeader>
|
||||
{detailBusy && <p role="status" className="text-sm text-muted-foreground">Загрузка выбранного периода и интерфейса…</p>}
|
||||
@@ -1583,6 +1660,7 @@ export default function TrafficPage() {
|
||||
</>}
|
||||
{effectiveMode === "servers" && detailServer && (
|
||||
<ServerDetail
|
||||
key={selectedId + ":" + selectedIface}
|
||||
sel={detailServer}
|
||||
range={range}
|
||||
setRange={setRange}
|
||||
@@ -1594,8 +1672,8 @@ export default function TrafficPage() {
|
||||
: liveSample ? "live" : isLive ? "История · ожидание live" : undefined}
|
||||
/>
|
||||
)}
|
||||
{effectiveMode === "users" && selUser && <UserDetail sel={selUser} range={range} setRange={setRange} />}
|
||||
{effectiveMode === "ifaces" && selIface && <IfaceDetail sel={selIface} range={range} setRange={setRange} />}
|
||||
{effectiveMode === "users" && selUser && <UserDetail key={selUser.id} sel={selUser} range={range} setRange={setRange} />}
|
||||
{effectiveMode === "ifaces" && selIface && <IfaceDetail key={selIface.id} sel={selIface} range={range} setRange={setRange} />}
|
||||
</FramePanel>
|
||||
</SectionFrame>
|
||||
{effectiveMode === "servers" && detailServer && detailServer.boundIfaces.length > 0 ? <ServerIfacesFrame server={detailServer} /> : null}
|
||||
|
||||
@@ -81,7 +81,7 @@ export function registerFlowAnalyticsActions(register: typeof add) {
|
||||
source: "retained flow_buckets plus pending; same REST analytics engine with scoped topology",
|
||||
rowLimit: 20000, topRowsPerBucketLimit: Math.max(20, limits.topN), engineTopListLimit: Math.min(50, Math.max(10, limits.topN)),
|
||||
incomplete: true, coverageVerified: false, rowSumIsNetworkTotal: false, forwardingVerified: false,
|
||||
inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
inferredPathsVerified: false, historicalOwnershipVerified: false, attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
backgroundEnrichmentStarted: false, collectorStarted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ аналитики превышает 1 МиБ; уменьшите страницу", 409)
|
||||
return withCurrentFlowReadQuality(output,context)
|
||||
|
||||
@@ -72,7 +72,7 @@ export function registerFlowCatalogActions(register: typeof add) {
|
||||
for (const server of selected) await assertTrafficHistorySource(context, server)
|
||||
return withCurrentFlowReadQuality({ ...page, clients, total: data.total, nextOffset: offset + clients.length < data.total ? offset + clients.length : null,
|
||||
incomplete: !!data.sourceWindow || page.incomplete || clients.length < data.total || clients.some(row => !row.completeSourceSet || !row.completeAttribution),
|
||||
source: "retained ingress rows and current named whole-interface bindings", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
|
||||
source: "retained ingress rows and current exclusive interface bindings, including confirmed single-peer WireGuard", topRowsPerBucketLimit: data.window.topRowsPerBucketLimit,
|
||||
from: data.window.since, to: data.window.until, sourceWindow: data.sourceWindow, ...sourceSemantics },context)
|
||||
},
|
||||
})
|
||||
|
||||
@@ -59,7 +59,7 @@ export function registerFlowLiveActions(register: typeof add) {
|
||||
historicalOwnershipVerified: false, currentTrafficVerified: false,
|
||||
rateSemantics: "REST live rates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback",
|
||||
liveMeaning: "events[].data.live means listener bound; it does not prove exporter freshness or forwarding",
|
||||
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
collectorStarted: false, backgroundEnrichmentStarted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ live превышает 1 МиБ; уменьшите страницу или число samples", 409)
|
||||
await authorize()
|
||||
|
||||
@@ -49,11 +49,11 @@ export function registerFlowMapActions(register: typeof add) {
|
||||
await authorize()
|
||||
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow,
|
||||
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
|
||||
source: "closed minutes for all rates; retained flows for services, exit exporter or observed GRE peer/next hop for paths; interfaceTraffic includes private routed traffic before top-N",
|
||||
source: "closed minutes for all rates; retained flows for services and user breakdowns; paths use an exit exporter or observed GRE peer/next hop, otherwise identify the observing exporter; interfaceTraffic includes private routed traffic before top-N",
|
||||
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
|
||||
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
|
||||
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
|
||||
attribution: "current named whole-interface bindings; users with hidden bindings excluded",
|
||||
attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard; users with hidden bindings excluded",
|
||||
collectorStarted: false, backgroundEnrichmentStarted: false, tracerouteExecuted: false }
|
||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ карты превышает 1 МиБ; уменьшите страницы", 409)
|
||||
return withCurrentFlowReadQuality(output,context)
|
||||
|
||||
@@ -210,7 +210,9 @@ const trafficFlowRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
|
||||
app.get("/traffic/flow/map-hops", async (req, reply) => {
|
||||
const query = analyticsQuery(req)
|
||||
return reply.send(await readFlowWindow(query.minutes, minutes => buildFlowMapHops({ ...query, minutes }), mcpDatabaseRequestSignal()))
|
||||
const includeCurrentMinute = (req.query as { range?: string }).range?.toLowerCase() === "1m"
|
||||
const requestedMinutes = includeCurrentMinute ? 1 : query.minutes
|
||||
return reply.send(await readFlowWindow(requestedMinutes, minutes => buildFlowMapHops({ ...query, minutes, includeCurrentMinute }), mcpDatabaseRequestSignal()))
|
||||
})
|
||||
|
||||
app.get("/traffic/flow/monthly", async (req, reply) => {
|
||||
|
||||
@@ -13,12 +13,13 @@ import {
|
||||
} from "../services/traffic-collector.js"
|
||||
import { refreshScheduler } from "../services/scheduler.js"
|
||||
import { collectTrafficManually } from "../services/manual-traffic-collection.js"
|
||||
import { readTrafficLiveSample, TrafficLiveSourceChanged } from "../services/traffic-live.js"
|
||||
import { readTrafficLiveInterfaces, readTrafficLiveSample, TrafficLiveSourceChanged } from "../services/traffic-live.js"
|
||||
import { MikrotikClient, MikrotikError } from "../services/mikrotik.js"
|
||||
import { getEnabledServerById } from "../services/wireguard-live.js"
|
||||
import { readTrafficCollectionContext } from "../services/traffic-collection-state.js"
|
||||
import { readServerTrafficHistory, readServerTrafficHistoryWithSeries, readServerTrafficInterfaces } from "../services/traffic-history-read.js"
|
||||
import { mergeBuiltTraffic } from "../services/traffic-rate.js"
|
||||
import { getUserById } from "../modules/users/service/users-service.js"
|
||||
import {
|
||||
buildBoundInterfaceTraffic,
|
||||
buildUserTrafficList,
|
||||
@@ -106,9 +107,15 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
})
|
||||
app.get("/traffic/servers/:id/live", async (req, reply) => {
|
||||
const p = req.params as { id?: string | number }
|
||||
const q = req.query as { iface?: string; once?: string }
|
||||
if (q.once === "1" && (typeof q.iface !== "string" || !q.iface.trim() ||
|
||||
q.iface.length > 128 || q.iface === "__all__" || /[,\x00-\x1f\x7f]/.test(q.iface))) {
|
||||
const q = req.query as { iface?: string; ifaces?: string; once?: string }
|
||||
const validIface = (name: unknown): name is string => typeof name === "string" && Boolean(name.trim()) &&
|
||||
name.length <= 128 && name !== "__all__" && !/[,\x00-\x1f\x7f]/.test(name)
|
||||
const interfaces = typeof q.ifaces === "string" ? q.ifaces.split(",") : []
|
||||
if (q.ifaces !== undefined && (q.once !== "1" || q.iface !== undefined || !interfaces.length ||
|
||||
interfaces.length > 16 || new Set(interfaces).size !== interfaces.length || !interfaces.every(validIface))) {
|
||||
return reply.code(400).send({ error: "Укажите до 16 разных интерфейсов для live-измерения" })
|
||||
}
|
||||
if (q.once === "1" && !interfaces.length && !validIface(q.iface)) {
|
||||
return reply.code(400).send({ error: "Укажите один интерфейс для live-измерения" })
|
||||
}
|
||||
const readServer = (id: string | number, signal?: AbortSignal) => withDatabaseApiRequest(async () => {
|
||||
@@ -123,11 +130,12 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const onlyInterface = q.iface && q.iface !== "__all__" ? q.iface : undefined
|
||||
const client = MikrotikClient.fromServer(server)
|
||||
const cache = { names: onlyInterface ? [onlyInterface] : [] as string[], joinedFailed: false }
|
||||
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, async () => {
|
||||
const assertSource = async (signal: AbortSignal) => {
|
||||
const current = await readServer(server.id, signal)
|
||||
if (!current) throw new TrafficLiveSourceChanged("Устройство выключено или удалено. Переподключите live-поток")
|
||||
if (Date.parse(current.updatedAt) !== Date.parse(server.updatedAt)) throw new TrafficLiveSourceChanged("Конфигурация устройства изменилась. Переподключите live-поток")
|
||||
})
|
||||
}
|
||||
const readSample = (signal: AbortSignal) => readTrafficLiveSample(client, onlyInterface, cache, signal, () => assertSource(signal))
|
||||
const abort = new AbortController()
|
||||
const onClose = () => abort.abort()
|
||||
registerDatabaseStreamAbort(req, onClose)
|
||||
@@ -136,7 +144,9 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
if (q.once === "1") {
|
||||
reply.raw.once("close", onClose)
|
||||
try {
|
||||
const sample = await readSample(abort.signal)
|
||||
const sample = interfaces.length
|
||||
? { interfaces: await readTrafficLiveInterfaces(client, interfaces, abort.signal, () => assertSource(abort.signal)) }
|
||||
: await readSample(abort.signal)
|
||||
return reply.header("Cache-Control", "no-store").send(sample)
|
||||
} catch {
|
||||
if (!reply.raw.destroyed) return reply.code(503).send({ error: "Live-измерение интерфейса недоступно" })
|
||||
@@ -227,9 +237,9 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
||||
const minutes = rangeToMinutes(q.range)
|
||||
const rangeEndMs = Date.now()
|
||||
const rangeStartMs = rangeEndMs - minutes * 60_000
|
||||
const users = await buildUserTrafficList(rangeStartMs, rangeEndMs)
|
||||
const user = users.find((u) => u.id === id)
|
||||
if (!user) return reply.status(404).send({ error: "Пользователь не найден" })
|
||||
const source = await getUserById(id)
|
||||
if (!source) return reply.status(404).send({ error: "Пользователь не найден" })
|
||||
const [user] = await buildUserTrafficList(rangeStartMs, rangeEndMs, { users: [source] })
|
||||
return reply.send({ user })
|
||||
})
|
||||
|
||||
|
||||
@@ -37,7 +37,8 @@ import {
|
||||
getServerCatalog,
|
||||
latestWireBps,
|
||||
loadFlowTopology,
|
||||
resolveClient,
|
||||
flowClientInterfaces,
|
||||
resolveFlowClient,
|
||||
resolveEn,
|
||||
} from "./traffic-flow-topology.js"
|
||||
|
||||
@@ -95,18 +96,6 @@ function bump(
|
||||
map.set(id, prev)
|
||||
}
|
||||
|
||||
async function userIfaceAllow(userId: string): Promise<Map<number, Set<string>> | null> {
|
||||
if (!userId) return null
|
||||
const binds = await flowReadDbAll<{serverId:number;interfaceName:string}>('SELECT server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings WHERE user_id=?',[userId])
|
||||
const allow = new Map<number, Set<string>>()
|
||||
for (const b of binds) {
|
||||
const set = allow.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
allow.set(b.serverId, set)
|
||||
}
|
||||
return allow
|
||||
}
|
||||
|
||||
function seriesFromRows(rows: PendingFlowRow[], minutes: number, direction: (row: PendingFlowRow) => "rx" | "tx" | "both" | null, now = Date.now()) {
|
||||
const slots = Math.min(60, Math.max(5, minutes))
|
||||
const slotMs = (minutes * 60_000) / slots
|
||||
@@ -241,7 +230,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const excludeOverlay = q.excludeOverlay !== false
|
||||
await authorize()
|
||||
const topo = await loadFlowTopology(scope?.serverIds, authorize)
|
||||
const allow = q.userId ? scope ? new Map([...topo.clientByIface.values()].filter(b => b.userId === q.userId).map(b => [b.serverId, new Set([...topo.clientByIface.values()].filter(other => other.userId === q.userId && other.serverId === b.serverId).map(other => other.interfaceName))])) : await userIfaceAllow(q.userId) : null
|
||||
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
|
||||
if (scope && q.userId && !allow?.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
|
||||
if (!scope) refreshFlowCatalogInBackground()
|
||||
@@ -253,7 +242,8 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const ingress = matchesIngress(row), egress = matchesEgress(row)
|
||||
return ingress === egress ? null : ingress ? "rx" : "tx"
|
||||
}
|
||||
const selected = ifaceFilter || allow ? raw.filter(row => matchesIngress(row) || matchesEgress(row)) : raw
|
||||
const selected = ifaceFilter || allow ? raw.filter(row => (matchesIngress(row) || matchesEgress(row)) &&
|
||||
(!q.userId || resolveFlowClient(topo, row.serverId, resolveIfaceName(row.serverId, row.inIface).name, resolveIfaceName(row.serverId, row.outIface).name)?.userId === q.userId)) : raw
|
||||
const { rows, espDirections } = collapseGreEspRows(selected, ifaceFilter ? interfaceDirection : serverDirection)
|
||||
const previousMinute = new Date(Math.floor(now / 60_000) * 60_000 - 60_000).toISOString()
|
||||
const ifacesForWire = new Set<string>()
|
||||
@@ -370,7 +360,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
inIface: resolved.name,
|
||||
outIface: outResolved.name,
|
||||
}, topo.plane)
|
||||
const client = resolveClient(topo, r.serverId, resolved.name) ?? resolveClient(topo, r.serverId, outResolved.name)
|
||||
const client = resolveFlowClient(topo, r.serverId, resolved.name, outResolved.name)
|
||||
const en = resolveEn(topo, r.nextHop, outResolved.name)
|
||||
const outIface = outResolved.name === "—" ? "" : outResolved.name
|
||||
const pathKey = JSON.stringify([client?.userId ?? "unknown", r.serverId, en?.id ?? "", dst, resolved.name, outIface,
|
||||
@@ -546,7 +536,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
||||
const bpsNow = ring
|
||||
? (!fromBuckets.undirectedBytes && (ring.rxNow + ring.txNow) * 1_000_000) || (totalBytes * 8) / windowSec
|
||||
: (recentBytes * 8) / 60 || (totalBytes * 8) / windowSec
|
||||
const greNames = ringServer ? enGreIfaceNames(topo, ringServer, [...ifacesForWire]) : []
|
||||
const greNames = ringServer && !q.userId ? enGreIfaceNames(topo, ringServer, [...ifacesForWire]) : []
|
||||
await authorize()
|
||||
const wire = ringServer ? await latestWireBps(ringServer, greNames, Boolean(scope)) : { bps: 0, bytes: 0 }
|
||||
await authorize()
|
||||
@@ -660,32 +650,26 @@ export async function listFlowExporters(minutes: number): Promise<FlowExportersD
|
||||
}
|
||||
}
|
||||
|
||||
export async function listFlowClients(minutes: number): Promise<{ clients: { id: string; name: string; subtitle: string; site: string; country: string; status: "online" | "offline" | "degraded"; rxNow: number; txNow: number; sessions: number; rxSeries: number[]; txSeries: number[]; bytes: number; }[]; }> {
|
||||
const inputs = await readFlowClientInputs(minutes)
|
||||
const users = inputs.users
|
||||
const binds = users.flatMap(user => user.bindings.map(binding => ({ ...binding, userId: user.id })))
|
||||
const byUser = new Map<string, typeof binds>()
|
||||
for (const b of binds) {
|
||||
const list = byUser.get(b.userId) ?? []
|
||||
list.push(b)
|
||||
byUser.set(b.userId, list)
|
||||
export async function listFlowClients(minutes: number): Promise<{ clients: FlowEntityCard[] }> {
|
||||
const [inputs, topo] = await Promise.all([readFlowClientInputs(minutes), loadFlowTopology()])
|
||||
const byUser = new Map<string, PendingFlowRow[]>()
|
||||
for (const row of inputs.window.rows) {
|
||||
const inIface = resolveIfaceName(row.serverId, row.inIface).name
|
||||
const outIface = resolveIfaceName(row.serverId, row.outIface).name
|
||||
const client = resolveFlowClient(topo, row.serverId, inIface, outIface)
|
||||
if (!client || classifyFlowPlane({ ...row, inIface, outIface }, topo.plane) !== "payload") continue
|
||||
const rows = byUser.get(client.userId) ?? []
|
||||
rows.push(row)
|
||||
byUser.set(client.userId, rows)
|
||||
}
|
||||
const rows = inputs.window.rows
|
||||
const clients: FlowEntityCard[] = []
|
||||
for (const u of users) {
|
||||
const userBinds = byUser.get(u.id) ?? []
|
||||
if (userBinds.length === 0) continue
|
||||
const allow = new Map<number, Set<string>>()
|
||||
for (const b of userBinds) {
|
||||
const set = allow.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
allow.set(b.serverId, set)
|
||||
}
|
||||
for (const u of inputs.users) {
|
||||
const allow = flowClientInterfaces(topo, u.id)
|
||||
const namedBindings = u.bindings.filter(binding => allow.get(binding.serverId)?.has(binding.interfaceName)).length
|
||||
const bound = (id: number, iface: string) => {
|
||||
const names = allow.get(id)
|
||||
return names?.has(iface) || names?.has(resolveIfaceName(id, iface).name)
|
||||
return allow.get(id)?.has(resolveIfaceName(id, iface).name)
|
||||
}
|
||||
const matched = rows.filter(r => bound(r.serverId, r.inIface) || bound(r.serverId, r.outIface))
|
||||
const matched = dedupFlowRowsMaxBytes(byUser.get(u.id) ?? [])
|
||||
const rates = seriesFromRows(matched, minutes, r => {
|
||||
if (!bound(r.serverId, r.inIface)) return "rx"
|
||||
return bound(r.serverId, r.outIface) ? "both" : "tx"
|
||||
@@ -694,18 +678,18 @@ export async function listFlowClients(minutes: number): Promise<{ clients: { id:
|
||||
id: u.id,
|
||||
name: u.login,
|
||||
subtitle: u.name || u.login,
|
||||
site: `${userBinds.length} ifaces`,
|
||||
site: namedBindings < u.bindings.length ? `IPFIX: ${namedBindings}/${u.bindings.length} привязок` : `${namedBindings} инт.`,
|
||||
country: "UN",
|
||||
status: u.active ? "online" : "offline",
|
||||
rxNow: rates.rxNow,
|
||||
txNow: rates.txNow,
|
||||
rxNow: matched.length ? rates.rxNow : null,
|
||||
txNow: matched.length ? rates.txNow : null,
|
||||
sessions: matched.length,
|
||||
rxSeries: rates.rx,
|
||||
txSeries: rates.tx,
|
||||
rxSeries: matched.length ? rates.rx : [],
|
||||
txSeries: matched.length ? rates.tx : [],
|
||||
bytes: matched.reduce((sum, row) => sum + row.bytes, 0),
|
||||
})
|
||||
}
|
||||
clients.sort((a, b) => b.rxNow - a.rxNow)
|
||||
clients.sort((a, b) => (b.rxNow ?? -1) - (a.rxNow ?? -1))
|
||||
return { clients }
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ const WELL_KNOWN: Record<string, string> = {
|
||||
"17:853": "DNS",
|
||||
"6:853": "DNS",
|
||||
"17:51820": "WireGuard",
|
||||
"17:13231": "WireGuard",
|
||||
"17:13232": "WireGuard",
|
||||
"17:51821": "WireGuard",
|
||||
"17:4789": "VXLAN",
|
||||
@@ -63,6 +64,13 @@ export function applicationName(proto: number, dstPort: number, srcPort = 0): st
|
||||
return WELL_KNOWN[dstKey] ?? WELL_KNOWN[srcKey] ?? `${protoName(proto)}/${dstPort || srcPort || "—"}`
|
||||
}
|
||||
|
||||
/** Port hints keep a conventional service port separate from the observed transport. */
|
||||
export function flowPortApplication(proto: number, port: number): string | null {
|
||||
if (proto === 6 && port === 853) return "DNS over TLS"
|
||||
if (proto === 17 && port === 853) return "Защищённый DNS"
|
||||
return port > 0 ? WELL_KNOWN[`${proto}:${port}`] ?? null : null
|
||||
}
|
||||
|
||||
export interface FlowMatchQuery {
|
||||
serverId?: number
|
||||
userId?: string
|
||||
|
||||
@@ -46,6 +46,8 @@ assert.equal(isNamedInternetService("DNS", "DNS"), false)
|
||||
assert.equal(mapServiceNodeId("AWS"), "svc:aws")
|
||||
assert.equal(mapServiceNodeId("Cloudflare"), "svc:cloudflare")
|
||||
assert.equal(mapServiceNodeId("Прочее"), "svc:other")
|
||||
assert.notEqual(mapServiceNodeId("Видео"), mapServiceNodeId("Игры"))
|
||||
assert.notEqual(mapServiceNodeId("Microsoft Работа"), mapServiceNodeId("Microsoft Игры"))
|
||||
assert.equal(mapCountryNodeId("US"), "cc:us")
|
||||
assert.equal(mapCountryNodeId("nl"), "cc:nl")
|
||||
assert.equal(mapCountryNodeId(""), "cc:other")
|
||||
@@ -87,7 +89,12 @@ assert.equal(resolveFlowBrand("173.194.160.163", 15169, "GOOGLE", 6, 443, 51234)
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 17, 443, 50000)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 80, 50000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 53, 53000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 443, 50000)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860::8888", 15169, "GOOGLE", 17, 443, 50000)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2001:4860:4860:0:0:0:0:8844/128", 15169, "GOOGLE", 6, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("::ffff:8.8.4.4", 15169, "", 17, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("2607:f8b0::123", 15169, "", 17, 443)?.service, "YouTube")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 396982, "", 6, 443)?.service, "Google")
|
||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 50000, 443)?.service, "Google", "443 на стороне клиента")
|
||||
|
||||
assert.equal(brandByAsn(32934)?.service, "Meta")
|
||||
assert.equal(lookupBrand("157.240.12.52", 0)?.service, "Meta")
|
||||
@@ -98,12 +105,12 @@ assert.equal(isNamedInternetService("Instagram", "Видео / стриминг"
|
||||
assert.equal(
|
||||
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 443, 51234)?.service,
|
||||
"Instagram",
|
||||
"HTTPS на Meta front → Instagram, как YouTube на Google",
|
||||
"HTTPS в сети Meta",
|
||||
)
|
||||
assert.equal(
|
||||
resolveFlowBrand("57.144.22.192", 0, "", 17, 443, 50000)?.service,
|
||||
"Instagram",
|
||||
"cdninstagram CIDR :443 без ASN → Instagram",
|
||||
"QUIC в префиксе Meta без ASN",
|
||||
)
|
||||
assert.equal(
|
||||
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 80, 50000)?.service,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { ipInCidrV4, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
import { canonicalIp, ipInCidrV4, ipv6ToInt, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
|
||||
export const OTHER_SERVICE = "Прочее"
|
||||
|
||||
export interface BrandHit {
|
||||
service: string
|
||||
category: string
|
||||
operator?: string
|
||||
heuristic?: true
|
||||
}
|
||||
|
||||
const CDN = { category: "CDN" } as const
|
||||
@@ -12,6 +14,7 @@ const WEB = { category: "Веб" } as const
|
||||
const VIDEO = { category: "Видео / стриминг" } as const
|
||||
const GAMES = { category: "Игры" } as const
|
||||
const VOICE = { category: "Голос" } as const
|
||||
const MESSAGING = { category: "Мессенджеры" } as const
|
||||
const AI = { category: "ИИ" } as const
|
||||
const DNS = { category: "DNS" } as const
|
||||
|
||||
@@ -39,7 +42,7 @@ const TIMEWEB: BrandHit = { service: "Timeweb", ...CDN }
|
||||
const BEGET: BrandHit = { service: "Beget", ...CDN }
|
||||
const DDOS_GUARD: BrandHit = { service: "DDoS-Guard", ...CDN }
|
||||
const META: BrandHit = { service: "Meta", ...CDN }
|
||||
const INSTAGRAM: BrandHit = { service: "Instagram", ...VIDEO }
|
||||
const INSTAGRAM: BrandHit = { service: "Instagram", operator: META.service, ...VIDEO }
|
||||
|
||||
const GOOGLE: BrandHit = { service: "Google", ...WEB }
|
||||
const GITHUB: BrandHit = { service: "GitHub", ...WEB }
|
||||
@@ -54,7 +57,9 @@ const WIKIPEDIA: BrandHit = { service: "Wikipedia", ...WEB }
|
||||
const PAYPAL: BrandHit = { service: "PayPal", ...WEB }
|
||||
const SALESFORCE: BrandHit = { service: "Salesforce", ...WEB }
|
||||
|
||||
const YOUTUBE: BrandHit = { service: "YouTube", ...VIDEO }
|
||||
const YOUTUBE: BrandHit = { service: "YouTube", operator: GOOGLE.service, ...VIDEO }
|
||||
const LIKELY_YOUTUBE: BrandHit = { ...YOUTUBE, heuristic: true }
|
||||
const LIKELY_INSTAGRAM: BrandHit = { ...INSTAGRAM, heuristic: true }
|
||||
const NETFLIX: BrandHit = { service: "Netflix", ...VIDEO }
|
||||
const TWITCH: BrandHit = { service: "Twitch", ...VIDEO }
|
||||
const TIKTOK: BrandHit = { service: "TikTok", ...VIDEO }
|
||||
@@ -69,7 +74,7 @@ const ROBLOX: BrandHit = { service: "Roblox", ...GAMES }
|
||||
const UBISOFT: BrandHit = { service: "Ubisoft", ...GAMES }
|
||||
|
||||
const DISCORD: BrandHit = { service: "Discord", ...VOICE }
|
||||
const TELEGRAM: BrandHit = { service: "Telegram", ...VOICE }
|
||||
const TELEGRAM: BrandHit = { service: "Telegram", ...MESSAGING }
|
||||
const ZOOM: BrandHit = { service: "Zoom", ...VOICE }
|
||||
|
||||
const CHATGPT: BrandHit = { service: "ChatGPT", ...AI }
|
||||
@@ -222,18 +227,13 @@ const HOLDER_BRANDS: Array<{ re: RegExp; hit: BrandHit }> = [
|
||||
const NON_ISO = new Set(["EU", "AP", "ZZ", "XX", "A1", "A2", "O1"])
|
||||
|
||||
const STEAM_ASN = 32590
|
||||
const GOOGLE_FRONT_ASN = new Set([15169, 396982])
|
||||
/** AS32934 / AS63293 — Meta front (Facebook + Instagram CDN). AS54115 — WhatsApp, не Instagram. */
|
||||
const META_FRONT_ASN = new Set([32934, 63293])
|
||||
const WHATSAPP_ASN = 54115
|
||||
const GOOGLE_DNS_V6 = new Set([ipv6ToInt("2001:4860:4860::8888")!, ipv6ToInt("2001:4860:4860::8844")!])
|
||||
|
||||
function isGooglePublicDns(ip: string): boolean {
|
||||
return ipInCidrV4(ip, "8.8.8.0/24") || ipInCidrV4(ip, "8.8.4.0/24")
|
||||
}
|
||||
|
||||
function isHttpsOrQuic(proto: number, dstPort: number, srcPort: number): boolean {
|
||||
if (proto !== 6 && proto !== 17) return false
|
||||
return dstPort === 443 || srcPort === 443
|
||||
const host = canonicalIp(ip)
|
||||
if (host === "8.8.8.8" || host === "8.8.4.4") return true
|
||||
const ipv6 = host.includes(":") ? ipv6ToInt(host) : null
|
||||
return ipv6 !== null && GOOGLE_DNS_V6.has(ipv6)
|
||||
}
|
||||
|
||||
export function isIsoCountry(code: string): boolean {
|
||||
@@ -295,19 +295,10 @@ export function lookupBrand(ip: string, asn: number): BrandHit | null {
|
||||
return brandByCidr(ip) || brandByAsn(asn)
|
||||
}
|
||||
|
||||
function isGoogleFront(asn: number, cidrBrand: BrandHit | null, asnBrand: BrandHit | null): boolean {
|
||||
return GOOGLE_FRONT_ASN.has(asn) || cidrBrand?.service === "Google" || asnBrand?.service === "Google"
|
||||
}
|
||||
|
||||
function isInstagramFront(asn: number, cidrBrand: BrandHit | null, asnBrand: BrandHit | null): boolean {
|
||||
if (asn === WHATSAPP_ASN) return false
|
||||
return META_FRONT_ASN.has(asn) || cidrBrand?.service === "Meta" || asnBrand?.service === "Meta"
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloudflare CIDR бьёт holder (витрина на CF не становится Steam).
|
||||
* Holder (YouTube / Instagram и др.) бьёт остальные CIDR/ASN.
|
||||
* HTTPS/QUIC на Google front → YouTube (кроме 8.8.8.8); на Meta front → Instagram (кроме WhatsApp ASN).
|
||||
* На порту 443 интернет-узла общие сети Google и Meta дают вероятную атрибуцию.
|
||||
* Порты Steam — только AS32590 и не выше Cloudflare CIDR.
|
||||
*/
|
||||
export function resolveFlowBrand(
|
||||
@@ -323,13 +314,12 @@ export function resolveFlowBrand(
|
||||
const holderBrand = brandByHolder(holder)
|
||||
if (holderBrand) return holderBrand
|
||||
const asnBrand = brandByAsn(asn)
|
||||
if (!isGooglePublicDns(ip) && isHttpsOrQuic(proto, dstPort, srcPort) && isGoogleFront(asn, cidrBrand, asnBrand)) {
|
||||
return YOUTUBE
|
||||
}
|
||||
if (isHttpsOrQuic(proto, dstPort, srcPort) && isInstagramFront(asn, cidrBrand, asnBrand)) {
|
||||
return INSTAGRAM
|
||||
}
|
||||
const fromLookup = cidrBrand || asnBrand
|
||||
if (asnBrand === YOUTUBE && cidrBrand === GOOGLE) return YOUTUBE
|
||||
if ((proto === 6 || proto === 17) && dstPort === 443) {
|
||||
if (fromLookup === GOOGLE && (!asn || asn === 15169) && !isGooglePublicDns(ip)) return LIKELY_YOUTUBE
|
||||
if (fromLookup === META && (!asn || asn === 32934 || asn === 63293)) return LIKELY_INSTAGRAM
|
||||
}
|
||||
if (fromLookup) return fromLookup
|
||||
if (asn === STEAM_ASN && isSteamGamePort(proto, dstPort, srcPort)) return STEAM
|
||||
return null
|
||||
@@ -358,6 +348,7 @@ export function isNamedInternetService(service: string, category: string): boole
|
||||
export function mapServiceNodeId(label: string): string {
|
||||
const raw = label.trim()
|
||||
if (raw === OTHER_SERVICE) return "svc:other"
|
||||
if (/[^\x00-\x7f]/.test(raw)) return `svc:label:${encodeURIComponent(raw.normalize("NFC").toLowerCase())}`
|
||||
const slug = raw
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
|
||||
@@ -8,14 +8,18 @@ for (const value of [-1, NaN, Infinity, "bad", "1.5", "9007199254740992", null,
|
||||
assert.equal(flowCounter("0"), 0); assert.equal(flowCounterSum([0, 5, 10]), 15)
|
||||
assert.throws(() => flowCounterSum([Number.MAX_SAFE_INTEGER, 1]))
|
||||
const row = { serverId: 1, bytes: 1000, packets: 10, inIface: "client-vlan", bucketAt: "2026-10-19T00:00:00Z" } as PendingFlowRow
|
||||
const user: FlowClientInput = { id: "u", login: "user", name: "Name", active: true, bindingCount: 2, selectedBindingCount: 1, bindings: [{ serverId: 1, interfaceName: "client-vlan", peerSpecific: false }] }
|
||||
const user: FlowClientInput = { id: "u", login: "user", name: "Name", active: true, bindingCount: 2, selectedBindingCount: 1, bindings: [{ serverId: 1, interfaceName: "client-vlan", peerSpecific: false, attributable: true }] }
|
||||
const observed = observeFlowClient(user, [row, { ...row, inIface: "2", bytes: 9999 }, { ...row, serverId: 2, bytes: 8888 }], 5)
|
||||
assert.equal(observed.ingressNamedRowsBytes, 1000); assert.equal(observed.ingressNamedRowCount, 1)
|
||||
assert.equal(observed.ifIndexRowsNotAttributed, 1); assert.equal(observed.completeSourceSet, false); assert.equal(observed.completeAttribution, false)
|
||||
assert.equal(observed.availability, "unknown"); assert.equal(observed.rxMbps, null); assert.equal(observed.txMbps, null); assert.equal(observed.historicalOwnershipVerified, false)
|
||||
assert.equal(observeFlowClient(user, [row], 5).completeAttribution, false)
|
||||
const peer = observeFlowClient({ ...user, bindings: [{ ...user.bindings[0], peerSpecific: true }] }, [row], 5)
|
||||
const peer = observeFlowClient({ ...user, bindings: [{ ...user.bindings[0], peerSpecific: true, attributable: false }] }, [row], 5)
|
||||
assert.equal(peer.ingressNamedRowsBytes, null); assert.equal(peer.peerBindingsNotAttributed, 1)
|
||||
const exclusivePeer = observeFlowClient({ ...user, bindingCount: 1, bindings: [{ ...user.bindings[0], peerSpecific: true }] }, [row], 5)
|
||||
assert.equal(exclusivePeer.ingressNamedRowsBytes, 1000)
|
||||
assert.equal(exclusivePeer.peerBindingsNotAttributed, 0)
|
||||
assert.equal(exclusivePeer.completeAttribution, true)
|
||||
assert.equal(observeFlowClient({ ...user, active: false }, [], 5).availability, "unknown")
|
||||
const source = { id: 1, name: "R", site: "site", country: "RU", host: "192.0.2.1", type: "home-router", enabled: false }
|
||||
const exporter = observeFlowExporter({ catalog: { list: [source], byId: new Map([[1, source]]) }, configuredIds: new Set([1]), configurationMembershipVerified: true, window: { rows: [row], since: "", until: "", topRowsPerBucketLimit: 20 } }, 1, 5)
|
||||
|
||||
@@ -3,7 +3,7 @@ import { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
|
||||
export { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
|
||||
import { listStoredFlowRows, type PendingFlowRow } from "./traffic-flow-ingest.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { getServerCatalog } from "./traffic-flow-topology.js"
|
||||
import { flowBindingAttributionSql, getServerCatalog } from "./traffic-flow-topology.js"
|
||||
import { observeFlowRing } from "./traffic-flow-engine.js"
|
||||
|
||||
const fail = (message: string) => Object.assign(new Error(message), { statusCode: 502 })
|
||||
@@ -39,7 +39,7 @@ export async function readFlowExporterInputs(minutes: number, serverIds?: readon
|
||||
}
|
||||
export interface FlowClientInput {
|
||||
id: string; login: string; name: string; active: boolean; bindingCount: number; selectedBindingCount: number;
|
||||
bindings: { serverId: number; interfaceName: string; peerSpecific: boolean }[];
|
||||
bindings: { serverId: number; interfaceName: string; peerSpecific: boolean; attributable: boolean }[];
|
||||
}
|
||||
/** Eligibility, hidden-binding exclusion, paging and selected bindings use one
|
||||
* SQL statement/snapshot. No hidden user or binding is deserialized in Node. */
|
||||
@@ -57,7 +57,8 @@ export async function readFlowClientInputs(minutes: number, options?: { serverId
|
||||
SELECT p.*,
|
||||
(SELECT count(*) FROM user_interface_bindings b WHERE b.user_id=p.id) AS "bindingCount",
|
||||
(SELECT count(*) FROM user_interface_bindings b WHERE b.user_id=p.id AND ($1::bigint[] IS NULL OR b.server_id=ANY($1))) AS "selectedBindingCount",
|
||||
COALESCE((SELECT jsonb_agg(jsonb_build_object('serverId',b.server_id,'interfaceName',b.interface_name,'peerSpecific',b.peer_public_key<>''))
|
||||
COALESCE((SELECT jsonb_agg(jsonb_build_object('serverId',b.server_id,'interfaceName',b.interface_name,
|
||||
'peerSpecific',b.peer_public_key<>'','attributable',(${flowBindingAttributionSql})))
|
||||
FROM (SELECT b.* FROM user_interface_bindings b WHERE b.user_id=p.id AND ($1::bigint[] IS NULL OR b.server_id=ANY($1)) ORDER BY b.id LIMIT $5) b),'[]'::jsonb) AS bindings
|
||||
FROM page p
|
||||
) SELECT (SELECT count(*) FROM eligible) AS total,COALESCE(jsonb_agg(to_jsonb(projected)),'[]'::jsonb) AS users FROM projected
|
||||
@@ -68,7 +69,7 @@ export async function readFlowClientInputs(minutes: number, options?: { serverId
|
||||
if (!user || typeof user.id !== "string" || typeof user.login !== "string" || typeof user.name !== "string" || typeof user.active !== "boolean" || !Array.isArray(user.bindings)) throw fail("Некорректный клиент NetFlow")
|
||||
const bindingCount = flowCounter(user.bindingCount), selectedBindingCount = flowCounter(user.selectedBindingCount)
|
||||
if (options && user.bindings.length > 1000 || user.bindings.length !== selectedBindingCount) throw fail("Превышен предел привязок клиента NetFlow")
|
||||
if (user.bindings.some((binding: FlowClientInput["bindings"][number]) => !Number.isSafeInteger(binding.serverId) || typeof binding.interfaceName !== "string" || typeof binding.peerSpecific !== "boolean" || selected && !selected.includes(binding.serverId))) throw fail("Некорректная привязка клиента NetFlow")
|
||||
if (user.bindings.some((binding: FlowClientInput["bindings"][number]) => !Number.isSafeInteger(binding.serverId) || typeof binding.interfaceName !== "string" || typeof binding.peerSpecific !== "boolean" || typeof binding.attributable !== "boolean" || selected && !selected.includes(binding.serverId))) throw fail("Некорректная привязка клиента NetFlow")
|
||||
return { id: user.id, login: user.login, name: user.name, active: user.active, bindingCount, selectedBindingCount, bindings: user.bindings }
|
||||
})
|
||||
return { users, total, window: await readFlowCatalogWindow(minutes, selected) }
|
||||
@@ -84,16 +85,16 @@ export function observeFlowExporter(input: Awaited<ReturnType<typeof readFlowExp
|
||||
}
|
||||
export function observeFlowClient(user: FlowClientInput, rows: PendingFlowRow[], minutes: number) {
|
||||
const interfaces = new Map<number, Set<string>>()
|
||||
for (const binding of user.bindings) if (!binding.peerSpecific) {
|
||||
for (const binding of user.bindings) if (binding.attributable) {
|
||||
const names = interfaces.get(binding.serverId) ?? new Set<string>(); names.add(binding.interfaceName); interfaces.set(binding.serverId, names)
|
||||
}
|
||||
const ifIndexRowsNotAttributed = rows.filter(row => interfaces.has(row.serverId) && /^#?\d+$/.test(row.inIface)).length
|
||||
const matched = rows.filter(row => !/^#?\d+$/.test(row.inIface) && interfaces.get(row.serverId)?.has(row.inIface))
|
||||
const attributable = user.bindings.some(binding => !binding.peerSpecific), bytes = attributable ? flowCounterSum(matched.map(row => row.bytes)) : null
|
||||
const attributable = interfaces.size > 0, bytes = attributable ? flowCounterSum(matched.map(row => row.bytes)) : null
|
||||
return { id: user.id, name: user.login, displayName: user.name, accountEnabled: user.active, availability: "unknown",
|
||||
scopedBindingCount: user.bindingCount, selectedBindingCount: user.selectedBindingCount, peerBindingsNotAttributed: user.bindings.filter(binding => binding.peerSpecific).length,
|
||||
completeSourceSet: user.bindingCount === user.selectedBindingCount, completeAttribution: user.bindingCount === user.selectedBindingCount && user.bindings.every(binding => !binding.peerSpecific) && ifIndexRowsNotAttributed === 0,
|
||||
ifIndexRowsNotAttributed, historicalOwnershipVerified: false, attribution: "current-named-whole-interface-bindings",
|
||||
scopedBindingCount: user.bindingCount, selectedBindingCount: user.selectedBindingCount, peerBindingsNotAttributed: user.bindings.filter(binding => binding.peerSpecific && !binding.attributable).length,
|
||||
completeSourceSet: user.bindingCount === user.selectedBindingCount, completeAttribution: user.bindingCount === user.selectedBindingCount && user.bindings.every(binding => binding.attributable) && ifIndexRowsNotAttributed === 0,
|
||||
ifIndexRowsNotAttributed, historicalOwnershipVerified: false, attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard",
|
||||
ingressNamedRowsBytes: bytes, ingressNamedRowCount: attributable ? matched.length : null,
|
||||
ingressNamedRowsMeanMbps: bytes === null ? null : bytes * 8 / (minutes * 60) / 1000000,
|
||||
serverContextFlowRing: user.bindings.length ? { serverId: user.bindings[0].serverId, scope: "server-payload; not per-client", ...observeFlowRing(user.bindings[0].serverId) } : null,
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { applicationName } from "./traffic-flow-apps.js"
|
||||
import { applicationName, flowPortApplication } from "./traffic-flow-apps.js"
|
||||
import { classifyFlowDst, disableCatalogFetchForTests, resetFlowCatalogForTests, seedFlowCatalogForTests } from "./traffic-flow-classify.js"
|
||||
|
||||
disableCatalogFetchForTests()
|
||||
resetFlowCatalogForTests()
|
||||
seedFlowCatalogForTests({
|
||||
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" }],
|
||||
cidrs: [{ cidr: "192.0.2.0/24", purpose: "steam-gaming" },
|
||||
{ cidr: "198.51.100.0/25", purpose: "Игры" },
|
||||
{ cidr: "198.51.100.128/25", purpose: "Видео / стриминг" },
|
||||
{ cidr: "173.194.0.0/16", purpose: "GOOGLE" },
|
||||
{ cidr: "173.194.1.0/24", purpose: "Work" },
|
||||
{ cidr: "57.144.0.0/16", purpose: "Meta" },
|
||||
{ cidr: "203.0.113.128/25", purpose: "main" }],
|
||||
})
|
||||
|
||||
const hit = classifyFlowDst("192.0.2.10", 6, 443, 50000, null)
|
||||
assert.equal(hit.category, "Игры")
|
||||
assert.equal(hit.service, "steam-gaming")
|
||||
assert.equal(hit.basis, "catalog")
|
||||
assert.equal(classifyFlowDst("198.51.100.10", 6, 443, 50000, null).category, "Игры")
|
||||
assert.equal(classifyFlowDst("198.51.100.150", 6, 443, 50000, null).category, "Видео / стриминг")
|
||||
|
||||
const miss = classifyFlowDst("203.0.113.9", 17, 53, 53000, null)
|
||||
assert.equal(miss.category, "DNS")
|
||||
@@ -33,11 +42,11 @@ const google = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(google.service, "YouTube")
|
||||
assert.equal(google.category, "Видео / стриминг")
|
||||
assert.deepEqual(google, { service: "YouTube", category: "Видео / стриминг", basis: "heuristic" })
|
||||
assert.equal(classifyFlowDst("173.194.1.1", 17, 443, 50000, null).service, "Work")
|
||||
|
||||
const googleCidr = classifyFlowDst("173.194.151.65", 6, 80, 50000, null)
|
||||
assert.equal(googleCidr.service, "Google")
|
||||
assert.equal(googleCidr.service, "GOOGLE")
|
||||
assert.equal(googleCidr.category, "Веб")
|
||||
|
||||
const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
@@ -52,6 +61,8 @@ const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||
})
|
||||
assert.equal(youtube.service, "YouTube")
|
||||
assert.equal(youtube.category, "Видео / стриминг")
|
||||
assert.equal(youtube.basis, "network")
|
||||
assert.equal(classifyFlowDst("208.65.153.1", 17, 443, 50000, null).basis, "network")
|
||||
|
||||
const valve = classifyFlowDst("203.0.113.40", 17, 27015, 50000, {
|
||||
prefix: "203.0.113.0/24",
|
||||
@@ -115,8 +126,8 @@ const googleCloud = classifyFlowDst("203.0.113.43", 6, 443, 1, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(googleCloud.service, "YouTube")
|
||||
assert.equal(googleCloud.category, "Видео / стриминг")
|
||||
assert.equal(googleCloud.service, "Google")
|
||||
assert.equal(googleCloud.category, "Веб")
|
||||
|
||||
const gre = classifyFlowDst("198.51.100.1", 47, 0, 0, null)
|
||||
assert.equal(gre.service, "GRE")
|
||||
@@ -142,8 +153,10 @@ const dnsGoogle = classifyFlowDst("8.8.8.8", 17, 53, 53000, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(dnsGoogle.service, "Google")
|
||||
assert.notEqual(dnsGoogle.service, "Прочее")
|
||||
assert.equal(dnsGoogle.service, "DNS")
|
||||
assert.deepEqual(classifyFlowDst("104.18.35.51", 6, 853, 53000, null), {service: "DNS", category: "DNS", basis: "port"})
|
||||
assert.deepEqual(classifyFlowDst("203.0.113.10", 17, 13231, 53000, null), {service: "WireGuard", category: "Туннель", basis: "port"})
|
||||
assert.deepEqual(classifyFlowDst("203.0.113.132", 6, 443, 53000, null), {service: "Прочее", category: "Прочее", basis: "unknown"})
|
||||
const ipv6Yt = classifyFlowDst("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
prefix: "2001:4860:4860::8888/128",
|
||||
asn: 15169,
|
||||
@@ -154,7 +167,7 @@ const ipv6Yt = classifyFlowDst("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(ipv6Yt.service, "YouTube")
|
||||
assert.equal(ipv6Yt.service, "Google")
|
||||
|
||||
const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
|
||||
prefix: "157.240.0.0/16",
|
||||
@@ -166,9 +179,7 @@ const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(instagram.service, "Instagram")
|
||||
assert.equal(instagram.category, "Видео / стриминг")
|
||||
assert.notEqual(instagram.service, "Meta")
|
||||
assert.deepEqual(instagram, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
|
||||
|
||||
const metaHttp = classifyFlowDst("157.240.12.52", 6, 80, 50000, {
|
||||
prefix: "157.240.0.0/16",
|
||||
@@ -194,14 +205,17 @@ const igHolder = classifyFlowDst("203.0.113.80", 6, 443, 1, {
|
||||
fetchedAt: Date.now(),
|
||||
})
|
||||
assert.equal(igHolder.service, "Instagram")
|
||||
assert.equal(igHolder.basis, "network")
|
||||
|
||||
const igCidr = classifyFlowDst("57.144.22.192", 17, 443, 50000, null)
|
||||
assert.equal(igCidr.service, "Instagram")
|
||||
assert.equal(igCidr.category, "Видео / стриминг")
|
||||
assert.deepEqual(igCidr, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
|
||||
|
||||
const esp = classifyFlowDst("198.51.100.1", 50, 0, 0, null)
|
||||
assert.equal(esp.category, "Туннель")
|
||||
assert.equal(applicationName(17, 443, 50000), "QUIC")
|
||||
assert.equal(applicationName(17, 853, 50000), "DNS")
|
||||
assert.equal(flowPortApplication(6, 853), "DNS over TLS")
|
||||
assert.equal(flowPortApplication(17, 853), "Защищённый DNS")
|
||||
assert.equal(flowPortApplication(17, 50505), null)
|
||||
|
||||
console.log("traffic-flow-classify.test.ts: ok")
|
||||
@@ -6,10 +6,12 @@ import { withActiveDatabaseRequest } from "../modules/mcp/database-request-lease
|
||||
import { ipInCidrV4, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
|
||||
import { applicationName } from "./traffic-flow-apps.js"
|
||||
import type { FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
|
||||
|
||||
export interface FlowClassification {
|
||||
service: string
|
||||
category: string
|
||||
basis: FlowServiceBasis
|
||||
}
|
||||
|
||||
interface CatalogCidr {
|
||||
@@ -50,12 +52,13 @@ export function seedFlowCatalogForTests(input: {
|
||||
}
|
||||
|
||||
export function categoryFromPurpose(purpose: string, proto: number, dstPort: number, srcPort: number): string {
|
||||
const p = purpose.toLowerCase()
|
||||
if (/gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры"
|
||||
if (/streaming|youtube|netflix|twitch|video|spotify|instagram/.test(p)) return "Видео / стриминг"
|
||||
const p = purpose.trim().toLowerCase()
|
||||
if (/игры|gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры"
|
||||
if (/видео|стриминг|streaming|youtube|netflix|twitch|video|spotify|instagram/.test(p)) return "Видео / стриминг"
|
||||
if (/cdn|cloudflare|akamai|fastly|hetzner|ovh|apple/.test(p)) return "CDN"
|
||||
if (/voip|discord|zoom/.test(p)) return "Голос"
|
||||
if (/openai|chatgpt|\bai\b/.test(p)) return "ИИ"
|
||||
if (/мессенджер|telegram/.test(p)) return "Мессенджеры"
|
||||
if (/голос|voip|discord|zoom/.test(p)) return "Голос"
|
||||
if (p === "ии" || /openai|chatgpt|\bai\b/.test(p)) return "ИИ"
|
||||
if (/quad9|opendns/.test(p)) return "DNS"
|
||||
if (/веб|web|google|github|paypal|vk|linkedin/.test(p)) return "Веб"
|
||||
const app = applicationName(proto, dstPort, srcPort)
|
||||
@@ -71,6 +74,11 @@ function matchCidr(ip: string,rows=cidrs): CatalogCidr | null {
|
||||
return null
|
||||
}
|
||||
|
||||
function servicePurpose(value: string | undefined): string | undefined {
|
||||
const purpose = value?.trim()
|
||||
return purpose && !/^(main|default|other|прочее)$/i.test(purpose) ? purpose : undefined
|
||||
}
|
||||
|
||||
export function classifyFlowDst(
|
||||
dst: string,
|
||||
proto: number,
|
||||
@@ -80,20 +88,23 @@ export function classifyFlowDst(
|
||||
opts?: { ignoreTunnelProto?: boolean;catalog?:{cidrs:CatalogCidr[];asnPurpose:Map<number,string>} },
|
||||
): FlowClassification {
|
||||
if (!opts?.ignoreTunnelProto) {
|
||||
if (proto === 47) return { service: "GRE", category: "Туннель" }
|
||||
if (proto === 50) return { service: "ESP", category: "Туннель" }
|
||||
if (proto === 47) return { service: "GRE", category: "Туннель", basis: "port" }
|
||||
if (proto === 50) return { service: "ESP", category: "Туннель", basis: "port" }
|
||||
}
|
||||
const app = applicationName(proto, dstPort, srcPort)
|
||||
if (app === "WireGuard") return { service: "WireGuard", category: "Туннель" }
|
||||
const hit = matchCidr(dst,opts?.catalog?.cidrs)
|
||||
if ((proto === 6 || proto === 17) && (dstPort === 53 || dstPort === 853)) return { service: "DNS", category: "DNS", basis: "port" }
|
||||
if (app === "WireGuard") return { service: "WireGuard", category: "Туннель", basis: "port" }
|
||||
const prefixPurpose = servicePurpose(matchCidr(dst,opts?.catalog?.cidrs)?.purpose)
|
||||
const holder = ripe?.holder ?? ""
|
||||
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, holder, proto, dstPort, srcPort)
|
||||
const asnName = ripe?.asn ? (opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn) : undefined
|
||||
const service = (hit?.purpose || brand?.service || asnName || OTHER_SERVICE).trim() || OTHER_SERVICE
|
||||
const category = hit
|
||||
? categoryFromPurpose(hit.purpose, proto, dstPort, srcPort)
|
||||
: (brand?.category || categoryFromPurpose(asnName || "", proto, dstPort, srcPort))
|
||||
return { service, category }
|
||||
if (prefixPurpose && prefixPurpose.toLowerCase() !== brand?.operator?.toLowerCase()) {
|
||||
return { service: prefixPurpose, category: categoryFromPurpose(prefixPurpose, proto, dstPort, srcPort), basis: "catalog" }
|
||||
}
|
||||
if (brand) return { service: brand.service, category: brand.category, basis: brand.heuristic ? "heuristic" : "network" }
|
||||
const asnName = ripe?.asn ? servicePurpose((opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn)) : undefined
|
||||
const category = categoryFromPurpose(asnName || "", proto, dstPort, srcPort)
|
||||
const basis = asnName ? "catalog" : category !== OTHER_SERVICE ? "port" : "unknown"
|
||||
return { service: asnName || OTHER_SERVICE, category, basis }
|
||||
}
|
||||
|
||||
/** Copies already-observed data only; never fetches the EvoBGP catalog. */
|
||||
|
||||
@@ -142,6 +142,7 @@ assert.equal(classifyInternetBrand("8.8.8.8", 6, 443, 51234, {
|
||||
fetchedAt: Date.now(),
|
||||
})?.service, "Google")
|
||||
assert.equal(mapInternetBrand("203.0.113.50", 6, 443, 51234, null).service, "Прочее")
|
||||
assert.deepEqual(mapInternetBrand("185.246.117.91", 17, 53, 53000, null), { service: "DNS", category: "DNS", basis: "port" })
|
||||
assert.equal(mapInternetBrand("8.8.8.8", 47, 0, 0, null).service, "Прочее")
|
||||
assert.equal(mapInternetBrand("8.8.8.8", 6, 443, 51234, {
|
||||
prefix: "8.8.8.0/24",
|
||||
@@ -173,7 +174,7 @@ assert.equal(mapInternetBrand("8.8.8.8", 17, 53, 53000, {
|
||||
holder: "GOOGLE",
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
}).service, "Google")
|
||||
}).service, "DNS")
|
||||
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
prefix: "2001:4860:4860::8888/128",
|
||||
asn: 15169,
|
||||
@@ -183,7 +184,7 @@ assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
|
||||
holder: "GOOGLE",
|
||||
ok: true,
|
||||
fetchedAt: Date.now(),
|
||||
}).service, "YouTube")
|
||||
}).service, "Google")
|
||||
assert.equal(mapInternetBrand("64.233.161.1", 17, 443, 50000, null).service, "YouTube")
|
||||
assert.equal(mapInternetBrand("142.250.1.10", 6, 443, 1, null).service, "YouTube")
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ export function destCtxForIface(
|
||||
}
|
||||
}
|
||||
|
||||
const OTHER_BRAND: FlowClassification = { service: OTHER_SERVICE, category: OTHER_SERVICE }
|
||||
export const OTHER_BRAND: FlowClassification = { service: OTHER_SERVICE, category: OTHER_SERVICE, basis: "unknown" }
|
||||
|
||||
function isTunnelProto(proto: number, dstPort: number, srcPort: number): boolean {
|
||||
if (proto === 47 || proto === 50) return true
|
||||
@@ -85,7 +85,7 @@ export function classifyInternetBrand(
|
||||
dstPort: number,
|
||||
srcPort: number,
|
||||
ripe: FlowIpMeta | null,
|
||||
): FlowClassification | null {
|
||||
): Pick<FlowClassification, "service" | "category"> | null {
|
||||
if (isTunnelProto(proto, dstPort, srcPort)) return null
|
||||
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, ripe?.holder ?? "", proto, dstPort, srcPort)
|
||||
if (brand && isNamedInternetService(brand.service, brand.category)) return brand
|
||||
@@ -105,7 +105,7 @@ export function mapInternetBrand(
|
||||
if (isTunnelProto(proto, dstPort, srcPort)) return OTHER_BRAND
|
||||
const classified = classifyFlowDst(dst, proto, dstPort, srcPort, ripe, { ignoreTunnelProto: true })
|
||||
if (isNamedInternetService(classified.service, classified.category)) return classified
|
||||
return OTHER_BRAND
|
||||
return { ...classified, service: classified.category }
|
||||
}
|
||||
|
||||
export function resolveInternetDest(opts: {
|
||||
|
||||
@@ -114,7 +114,7 @@ setGeoipReadersForTests({
|
||||
})
|
||||
const v6meta = resolveFlowIp("2001:4860:4860::8888")
|
||||
assert.equal(v6meta?.asn, 15169)
|
||||
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "YouTube")
|
||||
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Google")
|
||||
assert.notEqual(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, v6meta).service, "Прочее")
|
||||
const cidrYt = mapInternetBrand("64.233.161.1", 17, 443, 50000, resolveFlowIp("64.233.161.1"))
|
||||
assert.equal(cidrYt.service, "YouTube")
|
||||
|
||||
@@ -3,6 +3,8 @@ import { mock } from "node:test"
|
||||
import { dbQuery } from "../db/index.js"
|
||||
import { configureEngine, flushEngineNow } from "./traffic-flow-engine.js"
|
||||
import { parseFlowPacket } from "./traffic-flow-parse.js"
|
||||
import { buildFlowAnalytics } from "./traffic-flow-analytics.js"
|
||||
import { readFlowClientInputs } from "./traffic-flow-catalog-read.js"
|
||||
import { rememberServerIfaces, resetIfaceCacheForTests } from "./traffic-flow-ifindex.js"
|
||||
import {
|
||||
ingestParsedFlowsForServerForTests,
|
||||
@@ -18,7 +20,7 @@ import {
|
||||
resetFlowMapHopsCacheForTests,
|
||||
} from "./traffic-flow-map-hops.js"
|
||||
import { withPgOrSkip } from "../test/pg.js"
|
||||
import { seedFlowTopologyForTests, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { loadFlowTopology, resolveClient, seedFlowTopologyForTests, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { disableCatalogFetchForTests, resetFlowCatalogForTests } from "./traffic-flow-classify.js"
|
||||
import {
|
||||
disableRipeEnqueueForTests,
|
||||
@@ -460,13 +462,13 @@ try {
|
||||
assert.equal(leak.totalBytes, 30_000)
|
||||
assert.equal(leak.namedBytes, 10_000)
|
||||
assert.equal(leak.unclassifiedBytes, 20_000)
|
||||
const yt = leak.services?.find((s) => s.id === "svc:youtube")
|
||||
const youtube = leak.services?.find((s) => s.id === "svc:youtube")
|
||||
const other = leak.services?.find((s) => s.id === "svc:other")
|
||||
assert.ok(yt, "64.233:443 без RIPE → YouTube")
|
||||
assert.ok(youtube, "YouTube по общему диапазону Google без RIPE")
|
||||
assert.ok(other, "dest без бренда → Прочее")
|
||||
assert.equal(yt.bytes, 10_000)
|
||||
assert.equal(youtube.bytes, 10_000)
|
||||
assert.equal(other.bytes, 20_000)
|
||||
assert.ok(Math.abs(yt.share - 10 / 30) < 0.01)
|
||||
assert.ok(Math.abs(youtube.share - 10 / 30) < 0.01)
|
||||
assert.ok(Math.abs(other.share - 20 / 30) < 0.01)
|
||||
assert.equal((leak.serviceEdges ?? []).reduce((n, e) => n + e.bytes, 0), hop.bytes)
|
||||
} finally {
|
||||
@@ -656,7 +658,7 @@ ingestClosed(7, [
|
||||
try {
|
||||
resetFlowMapHopsCacheForTests()
|
||||
const rev = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:youtube"), "реверс googlevideo:443 → YouTube")
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:youtube"), "Ответный поток с порта 443 сети Google учитывается как YouTube")
|
||||
assert.ok(rev.services?.some((s) => s.id === "svc:cloudflare"), "реверс Cloudflare:443 → 10.x")
|
||||
assert.ok(rev.serviceEdges?.some((e) => e.toId === "svc:youtube" && e.fromId === "9"))
|
||||
} finally {
|
||||
@@ -698,7 +700,7 @@ try {
|
||||
const googleEdge = wan.serviceEdges?.find((e) => e.toId === "svc:google")
|
||||
assert.ok(googleEdge, "Google с WAN JH")
|
||||
assert.equal(googleEdge.fromId, "9", "якорь на EN, не на JH")
|
||||
assert.ok(!(wan.serviceEdges ?? []).some((e) => e.fromId === "7"), "нет пунктира с JH")
|
||||
assert.ok(!(wan.serviceEdges ?? []).some((e) => e.fromId === "7"), "исторический снимок сопоставил GRE с Exit")
|
||||
const viaGre = wan.serviceEdges?.find((e) => e.toId === "svc:google")
|
||||
assert.ok(viaGre?.clients?.some((c) => c.name === "Alice") || viaGre?.clientName === "Alice")
|
||||
} finally {
|
||||
@@ -730,15 +732,26 @@ ingestClosed(7, [
|
||||
outIface: "1",
|
||||
nextHop: "",
|
||||
},
|
||||
{ ...payloadFlow("1.2.3.4", 6000), proto: 17, dstPort: 53, inIface: "gre-client", outIface: "ether1", nextHop: "" },
|
||||
])
|
||||
try {
|
||||
resetFlowMapHopsCacheForTests()
|
||||
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||
assert.equal(wanOnly.services?.find(s => s.id === "svc:youtube")?.bytes, 9000)
|
||||
assert.deepEqual(wanOnly.serviceEdges, [])
|
||||
assert.deepEqual(wanOnly.servicePaths, [])
|
||||
assert.deepEqual(wanOnly.countryEdges, [])
|
||||
assert.ok(wanOnly.countryServiceGroups?.every(group => !group.edges.length && !group.paths.length))
|
||||
const youtube = wanOnly.services?.find(s => s.id === "svc:youtube")
|
||||
assert.equal(youtube?.bytes, 9000)
|
||||
assert.deepEqual(youtube.serviceEvidence, [{basis: "heuristic", bytes: 9000}])
|
||||
assert.deepEqual(youtube.trafficTypes, [{transport: "TCP", application: "HTTPS", bytes: 9000}])
|
||||
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.trafficTypes,
|
||||
[{transport: "UDP", application: "DNS", bytes: 6000}])
|
||||
assert.deepEqual(wanOnly.services?.find(s => s.id === "svc:dns")?.serviceEvidence, [{basis: "port", bytes: 6000}])
|
||||
const dns = wanOnly.serviceEdges?.find(e => e.toId === "svc:dns")
|
||||
assert.deepEqual(dns && [dns.fromId, dns.observedOnly, dns.bytes], ["7", true, 6000])
|
||||
const dnsPath = wanOnly.servicePaths?.find(p => p.serviceId === "svc:dns")
|
||||
assert.deepEqual(dnsPath && [dnsPath.viaId, dnsPath.viaIface, dnsPath.enId, dnsPath.clientName], ["7", "ether1", "", "Alice"])
|
||||
assert.ok(wanOnly.countryEdges?.every(e => e.observedOnly && e.fromId === "7"))
|
||||
assert.ok(wanOnly.countryServiceGroups?.some(group => group.edges.some(e => e.toId.endsWith("|svc:dns"))))
|
||||
assert.deepEqual(wanOnly.nodeUsers?.["7"]?.map(u => [u.clientName, u.bytes]), [["—", 9000], ["Alice", 6000]])
|
||||
assert.equal(wanOnly.nodeUsers?.["9"], undefined)
|
||||
|
||||
} finally {
|
||||
seedFlowTopologyForTests(null)
|
||||
@@ -768,7 +781,7 @@ ingestClosed(9, [{
|
||||
proto: 6,
|
||||
srcPort: 51234,
|
||||
dstPort: 443,
|
||||
bytes: 12_000,
|
||||
bytes: 120_000,
|
||||
packets: 10,
|
||||
inIface: "1",
|
||||
outIface: "1",
|
||||
@@ -786,7 +799,10 @@ try {
|
||||
assert.equal(googlePaths[0]?.viaId, "7")
|
||||
const googleEdge = dual.serviceEdges?.find((e) => e.toId === "svc:google" && e.fromId === "9")
|
||||
assert.ok(googleEdge)
|
||||
assert.equal(googleEdge.bytes, 12_000)
|
||||
assert.equal(googleEdge.bytes, 120_000)
|
||||
assert.equal(dual.totalBytes, 120_000, "объём крупнейшей копии с атрибуцией маршрута JH")
|
||||
assert.equal(dual.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12_000)
|
||||
assert.equal(dual.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 120_000)
|
||||
assert.equal(googleEdge.bps, googlePaths[0]?.bps)
|
||||
} finally {
|
||||
seedFlowTopologyForTests(null)
|
||||
@@ -1031,12 +1047,30 @@ try {
|
||||
{ ...flow, src: "10.0.0.2", bytes: 2000, outIface: "gre-second" },
|
||||
{ ...flow, src: "10.0.0.3", bytes: 9000, outIface: "ether1" },
|
||||
])
|
||||
// This open minute must affect neither the service nor the link rate.
|
||||
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 90000, outIface: "SWE-VEESP" }])
|
||||
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
|
||||
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
|
||||
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes]), [["10", 2000], ["9", 1000]])
|
||||
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 3000)
|
||||
ingestClosed(7, [{ ...flow, bytes: 900_000_000, outIface: "SWE-VEESP" }], bucket + 90_000)
|
||||
const clock = mock.method(Date, "now", () => bucket + 90_000)
|
||||
try {
|
||||
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
|
||||
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
|
||||
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, new Date(bucket).toISOString())
|
||||
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes, Boolean(e.observedOnly)]), [["7", 9000, true], ["10", 2000, false], ["9", 1000, false]])
|
||||
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 12000)
|
||||
assert.equal(map.nodeUsers?.["7"]?.find(u => u.clientName === "Alice")?.bytes, 12000)
|
||||
assert.equal(map.nodeUsers?.["9"]?.find(u => u.clientName === "Alice")?.bytes, 1000)
|
||||
|
||||
const recent = await buildFlowMapHops({ serverId: 7, minutes: 1, includeCurrentMinute: true, minSharePct: 0 })
|
||||
assert.equal(recent.windowSec, 90)
|
||||
const lastMinute = new Date(bucket + 60_000).toISOString()
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
|
||||
assert.equal(recent.countryServiceGroups?.flatMap(g => g.services).find(s => s.label === "YouTube")?.lastBucketAt, lastMinute)
|
||||
assert.equal(recent.services?.find(s => s.id === "svc:youtube")?.bps, 900_012_000 * 8 / 90)
|
||||
assert.equal(recent.serviceEdges?.find(edge => edge.fromId === "9")?.bps, 900_001_000 * 8 / 90)
|
||||
const later = bucket + 150_000
|
||||
clock.mock.mockImplementation(() => later)
|
||||
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 0, packets: 1, outIface: "ether1" }])
|
||||
const idle = await buildFlowMapHops({ serverId: 7, minutes: 3, includeCurrentMinute: true, minSharePct: 0 })
|
||||
assert.equal(idle.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, lastMinute)
|
||||
} finally { clock.mock.restore() }
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
|
||||
resetFlowRingsForTests()
|
||||
@@ -1096,12 +1130,58 @@ try {
|
||||
ingestClosed(sid, [split], bucket - 60000)
|
||||
const mixed = await buildFlowMapHops({serverId: sid, minutes: 5, iface: "mixed-lan"})
|
||||
assert.equal(mixed.totalBytes, 6000)
|
||||
assert.deepEqual(mixed.serviceEdges, [])
|
||||
assert.ok(mixed.serviceEdges?.every(e => e.observedOnly && e.fromId === String(sid)))
|
||||
assert.ok(mixed.servicePaths?.every(p => !p.enId))
|
||||
await flushEngineNow({ prune: false })
|
||||
assert.deepEqual((await dbQuery("SELECT out_iface,next_hop FROM flow_buckets WHERE server_id=? AND in_iface='mixed-lan'", [sid])).rows,
|
||||
[{out_iface: "", next_hop: null}, {out_iface: "", next_hop: null}])
|
||||
const user = await buildFlowMapHops({serverId: sid, minutes: 5, userId: "no-interface-binding"})
|
||||
assert.equal(user.interfaceTraffic, undefined)
|
||||
const alice = `map-alice-${sid}`, bob = `map-bob-${sid}`
|
||||
try {
|
||||
await dbQuery("INSERT INTO app_users(id,login,name) VALUES (?,?,'Alice'),(?,?,'Bob')", [alice, alice, bob, bob])
|
||||
await dbQuery(`
|
||||
INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,interface_type,peer_public_key)
|
||||
VALUES (?, ?, ?, 'wg-shared', 'wg', 'alice-key'), (?, ?, ?, 'wg-shared', 'wg', 'bob-key'), (?, ?, ?, 'gre-owner', 'gre', '')
|
||||
`, [alice + "-wg", alice, sid, bob + "-wg", bob, sid, alice + "-gre", alice, sid])
|
||||
seedFlowTopologyForTests(null)
|
||||
for (const topology of [await loadFlowTopology(), await loadFlowTopology([sid])]) {
|
||||
assert.equal(resolveClient(topology, sid, "wg-shared"), null, "общий WG не присваивается одному пользователю")
|
||||
assert.equal(resolveClient(topology, sid, "gre-owner")?.userId, alice)
|
||||
}
|
||||
const flow = { ...payloadFlow("8.8.8.8", 1000), inIface: "gre-owner", outIface: "uplink-a" }
|
||||
ingestClosed(sid, [flow, { ...flow, inIface: "wg-shared", srcPort: 49151 }], bucket - 60_000)
|
||||
const aliceMap = await buildFlowMapHops({serverId: sid, minutes: 5, userId: alice})
|
||||
const aliceTraffic = await buildFlowAnalytics({serverId: sid, minutes: 5, userId: alice})
|
||||
const bobTraffic = await buildFlowAnalytics({serverId: sid, minutes: 5, userId: bob})
|
||||
assert.equal(aliceMap.totalBytes, 1000)
|
||||
assert.equal(aliceTraffic.bytes, aliceMap.totalBytes)
|
||||
assert.equal(bobTraffic.bytes, 0)
|
||||
|
||||
await dbQuery(`INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,interface_type,peer_public_key)
|
||||
VALUES (?, ?, ?, 'wg-exclusive', 'wg', 'alice-exclusive')`, [alice + "-exclusive", alice, sid])
|
||||
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive"), null)
|
||||
await dbQuery("UPDATE servers SET enabled=true WHERE id=?", [sid])
|
||||
const sampledAt = new Date().toISOString()
|
||||
await dbQuery(`INSERT INTO traffic_samples(server_id,interface_name,peer_public_key,sampled_at)
|
||||
VALUES (?, 'wg-exclusive', 'alice-exclusive', ?)`, [sid, sampledAt])
|
||||
await dbQuery(`INSERT INTO traffic_collection_state(server_id,server_updated_at,last_attempt_at,last_succeeded_at,status)
|
||||
SELECT id,updated_at,?,?,'ok' FROM servers WHERE id=?`, [sampledAt, sampledAt, sid])
|
||||
seedFlowTopologyForTests(null)
|
||||
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive")?.userId, alice)
|
||||
const {users} = await readFlowClientInputs(5, {serverIds: [sid], allowedServerIds: [sid], offset: 0, limit: 10})
|
||||
assert.equal(users.find(u => u.id === alice)?.bindings.find(b => b.interfaceName === "wg-exclusive")?.attributable, true)
|
||||
ingestClosed(sid, [{ ...flow, inIface: "wg-exclusive", bytes: 2000, srcPort: 49155 }], bucket - 60_000)
|
||||
resetFlowMapHopsCacheForTests()
|
||||
assert.equal((await buildFlowMapHops({serverId: sid, minutes: 5, userId: alice})).totalBytes, 3000)
|
||||
assert.equal((await buildFlowAnalytics({serverId: sid, minutes: 5, userId: alice})).bytes, 3000)
|
||||
await dbQuery(`INSERT INTO traffic_samples(server_id,interface_name,peer_public_key,sampled_at)
|
||||
VALUES (?, 'wg-exclusive', 'unbound-peer', ?)`, [sid, sampledAt])
|
||||
seedFlowTopologyForTests(null)
|
||||
assert.equal(resolveClient(await loadFlowTopology([sid]), sid, "wg-exclusive"), null, "второй peer виден даже без привязки в приложении")
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM app_users WHERE id IN (?,?)", [alice, bob])
|
||||
}
|
||||
console.log("CHR NetFlow v5 through PostgreSQL and map: GRE A RX / GRE B TX both 192 B, 3 packets; Top-200 and GRE encapsulation verified")
|
||||
} finally {
|
||||
await dbQuery("DELETE FROM servers WHERE id=?", [sid])
|
||||
|
||||
@@ -2,10 +2,10 @@ import { flowReadDbAll } from "./traffic-flow-read-policy.js"
|
||||
import { isDeepStrictEqual } from "node:util"
|
||||
import { readFlowMapSourceLimits } from "./traffic-flow-source-limits.js"
|
||||
import { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
|
||||
import type { FlowMapInterfaceTraffic } from "@mmapp/contracts/traffic-flow"
|
||||
import type { FlowMapInterfaceTraffic, FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
|
||||
import type { ScopedFlowAnalyticsRead } from "./traffic-flow-analytics.js"
|
||||
import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapHopsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import { flowRowMatchesFilter } from "./traffic-flow-apps.js"
|
||||
import { flowPortApplication, flowRowMatchesFilter } from "./traffic-flow-apps.js"
|
||||
import { OTHER_SERVICE, isNamedInternetService, mapCountryNodeId, mapCountryServiceNodeId, mapServiceNodeId, resolveRipeCountry } from "./traffic-flow-brands.js"
|
||||
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
|
||||
import { refreshFlowCatalogInBackground } from "./traffic-flow-classify.js"
|
||||
@@ -13,12 +13,13 @@ import { collapseGreEspRows, dedupFlowRowsAcrossExporters, dedupFlowRowsMaxBytes
|
||||
import { getFlowListenerState, listStoredFlowRows } from "./traffic-flow-ingest.js"
|
||||
import { resolveIfaceName } from "./traffic-flow-ifaces.js"
|
||||
import { classifyFlowPlane, shouldKeepPlane } from "./traffic-flow-planes.js"
|
||||
import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-flow-dest.js"
|
||||
import { destCtxForIface, flowRateDirection, mapInternetBrand, OTHER_BRAND } from "./traffic-flow-dest.js"
|
||||
import { protoName } from "./traffic-flow-parse.js"
|
||||
import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
|
||||
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
|
||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
|
||||
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.js"
|
||||
import { loadFlowTopology, resolveFlowClient, flowClientInterfaces, getServerCatalog, type FlowClientBinding } from "./traffic-flow-topology.js"
|
||||
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM, minuteBucketIso } from "./traffic-flow-engine.js"
|
||||
|
||||
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
|
||||
export const MAP_SERVICE_NODE_CAP = 20
|
||||
@@ -33,6 +34,7 @@ const HOPS_CACHE_TTL_MS = 2000
|
||||
|
||||
export interface FlowMapHopsQuery {
|
||||
minutes: number
|
||||
includeCurrentMinute?: boolean
|
||||
serverId?: number
|
||||
userId?: string
|
||||
iface?: string
|
||||
@@ -63,6 +65,7 @@ interface ClientAcc {
|
||||
interface FromAcc {
|
||||
exporterId: string
|
||||
enId: string
|
||||
viaIface?: string
|
||||
reverseBytes: number
|
||||
bytes: number
|
||||
clients: Map<string, ClientAcc>
|
||||
@@ -71,9 +74,11 @@ interface FromAcc {
|
||||
interface DstAcc {
|
||||
dst: string
|
||||
bytes: number
|
||||
lastBucketAt: string
|
||||
proto: number
|
||||
dstPort: number
|
||||
srcPort: number
|
||||
application: string | null
|
||||
fromBytes: Map<string, FromAcc>
|
||||
}
|
||||
|
||||
@@ -81,6 +86,9 @@ interface DestTotal {
|
||||
label: string
|
||||
category: string
|
||||
bytes: number
|
||||
lastBucketAt: string
|
||||
trafficTypes?: Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>
|
||||
serviceEvidence?: Map<FlowServiceBasis, number>
|
||||
}
|
||||
|
||||
interface DestEdgeAcc {
|
||||
@@ -90,6 +98,7 @@ interface DestEdgeAcc {
|
||||
bytesFwd: number
|
||||
bytesRev: number
|
||||
clients: Map<string, string>
|
||||
observedOnly?: true
|
||||
}
|
||||
|
||||
interface DestPathAcc {
|
||||
@@ -97,6 +106,7 @@ interface DestPathAcc {
|
||||
clientName: string
|
||||
viaId: string
|
||||
viaName: string
|
||||
viaIface?: string
|
||||
enId: string
|
||||
enName: string
|
||||
serviceId: string
|
||||
@@ -114,12 +124,12 @@ function bumpClient(clients: Map<string, ClientAcc>, bytes: number, client: { us
|
||||
clients.set(id, { name, bytes })
|
||||
}
|
||||
|
||||
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, bytes: number, reverse: boolean, client: { userId: string; name: string } | null): void {
|
||||
const key = exporterId + "|" + enId
|
||||
const from = acc.fromBytes.get(key) ?? { exporterId, enId, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
|
||||
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, viaIface: string | undefined, bytes: number, reverse: boolean, client: FlowClientBinding | null | undefined): void {
|
||||
const key = JSON.stringify([exporterId, enId, viaIface])
|
||||
const from = acc.fromBytes.get(key) ?? { exporterId, enId, viaIface, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
|
||||
from.bytes += bytes
|
||||
if (reverse) from.reverseBytes += bytes
|
||||
bumpClient(from.clients, bytes, client)
|
||||
bumpClient(from.clients, bytes, client ?? null)
|
||||
acc.fromBytes.set(key, from)
|
||||
}
|
||||
|
||||
@@ -151,13 +161,22 @@ export function pickMapServices(
|
||||
.slice(0, cap)
|
||||
}
|
||||
|
||||
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number): void {
|
||||
const prev = totals.get(id)
|
||||
if (prev) {
|
||||
prev.bytes += bytes
|
||||
return
|
||||
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number, lastBucketAt: string,
|
||||
detail?: { transport: string; application: string | null; basis: FlowServiceBasis }): void {
|
||||
const total = totals.get(id) ?? { label, category, bytes: 0, lastBucketAt }
|
||||
total.bytes += bytes
|
||||
if (lastBucketAt > total.lastBucketAt) total.lastBucketAt = lastBucketAt
|
||||
if (detail && bytes > 0) {
|
||||
const { transport, application, basis } = detail
|
||||
const types = total.trafficTypes ??= new Map()
|
||||
const key = JSON.stringify([transport, application])
|
||||
const type = types.get(key) ?? { transport, application, bytes: 0 }
|
||||
type.bytes += bytes
|
||||
types.set(key, type)
|
||||
const evidence = total.serviceEvidence ??= new Map()
|
||||
evidence.set(basis, (evidence.get(basis) ?? 0) + bytes)
|
||||
}
|
||||
totals.set(id, { label, category, bytes })
|
||||
totals.set(id, total)
|
||||
}
|
||||
|
||||
function bumpDestFrom(
|
||||
@@ -170,7 +189,7 @@ function bumpDestFrom(
|
||||
enName: string,
|
||||
viaName: string,
|
||||
/** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */
|
||||
edgeFromId: string = fromId,
|
||||
edgeFromId: string = fromId || exporterId,
|
||||
): void {
|
||||
const edgeKey = `${edgeFromId}|${toId}`
|
||||
const prevEdge = edges.get(edgeKey)
|
||||
@@ -191,10 +210,11 @@ function bumpDestFrom(
|
||||
bytesFwd: from.bytes - from.reverseBytes,
|
||||
bytesRev: from.reverseBytes,
|
||||
clients: namedClients,
|
||||
...(!fromId && edgeFromId === exporterId ? { observedOnly: true as const } : {}),
|
||||
})
|
||||
}
|
||||
for (const [clientId, c] of from.clients) {
|
||||
const pathKey = `${clientId}|${exporterId}|${fromId}|${toId}`
|
||||
const pathKey = JSON.stringify([clientId, exporterId, fromId, toId, from.viaIface])
|
||||
const prevPath = paths.get(pathKey)
|
||||
if (prevPath) {
|
||||
prevPath.bytes += c.bytes
|
||||
@@ -205,6 +225,7 @@ function bumpDestFrom(
|
||||
clientName: c.name,
|
||||
viaId: exporterId,
|
||||
viaName,
|
||||
...(from.viaIface ? { viaIface: from.viaIface } : {}),
|
||||
enId: fromId,
|
||||
enName,
|
||||
serviceId: toId,
|
||||
@@ -231,8 +252,11 @@ function finalizeDestLayer(
|
||||
label: s.label,
|
||||
category: s.category,
|
||||
bytes: s.bytes,
|
||||
...(s.lastBucketAt ? { lastBucketAt: minuteBucketIso(Date.parse(s.lastBucketAt)) } : {}),
|
||||
bps: (s.bytes * 8) / windowSec,
|
||||
share: shareBase > 0 ? s.bytes / shareBase : 0,
|
||||
...(s.trafficTypes ? { trafficTypes: [...s.trafficTypes.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5) } : {}),
|
||||
...(s.serviceEvidence ? { serviceEvidence: [...s.serviceEvidence].map(([basis, bytes]) => ({ basis, bytes })).sort((a, b) => b.bytes - a.bytes) } : {}),
|
||||
}))
|
||||
.sort((a, b) => b.bytes - a.bytes),
|
||||
minSharePct,
|
||||
@@ -252,6 +276,7 @@ function finalizeDestLayer(
|
||||
bps: (e.bytes * 8) / windowSec,
|
||||
bpsFwd: (e.bytesFwd * 8) / windowSec,
|
||||
bpsRev: (e.bytesRev * 8) / windowSec,
|
||||
...(e.observedOnly ? { observedOnly: e.observedOnly } : {}),
|
||||
...(first ? { clientId: first.id, clientName: first.name } : {}),
|
||||
...(clients.length ? { clients } : {}),
|
||||
}
|
||||
@@ -264,6 +289,7 @@ function finalizeDestLayer(
|
||||
clientName: p.clientName,
|
||||
viaId: p.viaId,
|
||||
viaName: p.viaName,
|
||||
...(p.viaIface ? { viaIface: p.viaIface } : {}),
|
||||
enId: p.enId,
|
||||
enName: p.enName,
|
||||
serviceId: p.serviceId,
|
||||
@@ -329,6 +355,7 @@ function hopsQueryKey(q: FlowMapHopsQuery, minSharePct: number): string {
|
||||
return JSON.stringify({
|
||||
epoch: flowDataEpoch(),
|
||||
minutes: q.minutes,
|
||||
includeCurrentMinute: q.includeCurrentMinute === true,
|
||||
serverId: q.serverId ?? null,
|
||||
userId: q.userId ?? null,
|
||||
iface: q.iface ?? null,
|
||||
@@ -339,32 +366,10 @@ function hopsQueryKey(q: FlowMapHopsQuery, minSharePct: number): string {
|
||||
})
|
||||
}
|
||||
|
||||
async function userIfaceAllow(userId: string): Promise<Map<number, Set<string>> | null> {
|
||||
if (!userId) return null
|
||||
const binds = await flowReadDbAll<{serverId:number;interfaceName:string}>('SELECT server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings WHERE user_id=?',[userId])
|
||||
const allow = new Map<number, Set<string>>()
|
||||
for (const b of binds) {
|
||||
const set = allow.get(b.serverId) ?? new Set<string>()
|
||||
set.add(b.interfaceName)
|
||||
allow.set(b.serverId, set)
|
||||
}
|
||||
return allow
|
||||
}
|
||||
|
||||
function ifaceUsable(name: string): boolean {
|
||||
return Boolean(name) && name !== "—"
|
||||
}
|
||||
|
||||
function resolveMapClient(
|
||||
topo: FlowTopology,
|
||||
serverId: number,
|
||||
inName: string,
|
||||
outName: string,
|
||||
) {
|
||||
return resolveClient(topo, serverId, inName)
|
||||
?? (ifaceUsable(outName) ? resolveClient(topo, serverId, outName) : null)
|
||||
}
|
||||
|
||||
function bump(acc: Map<string, HopAcc>, key: string, seed: Omit<HopAcc, "bytes" | "bytesFwd" | "bytesRev">, bytes: number, dir: "fwd" | "rev" | "both"): void {
|
||||
const prev = acc.get(key)
|
||||
const addFwd = dir === "fwd" || dir === "both" ? bytes : 0
|
||||
@@ -409,21 +414,19 @@ async function resolveMinSharePct(q: FlowMapHopsQuery): Promise<number> {
|
||||
}
|
||||
}
|
||||
|
||||
// Closed minute buckets from every admitted export. Keep an hour of last-seen context for idle links.
|
||||
async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowMapHopsQuery, end: number): Promise<FlowMapInterfaceTraffic[]> {
|
||||
// Keep an hour of last-seen context for idle links.
|
||||
async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowMapHopsQuery, start: string, end: number): Promise<FlowMapInterfaceTraffic[]> {
|
||||
if (!serverIds.length) return []
|
||||
const { minutes } = q
|
||||
// Private site-to-site flows are traffic on the link even when the destination graph hides mesh paths.
|
||||
const planes = q.excludeOverlay === false ? ["payload", "client_mesh", "overlay"] : ["payload", "client_mesh"]
|
||||
const dimensions = planes.flatMap(plane => [FLOW_IFACE_RX_DIM + ":" + plane, FLOW_IFACE_TX_DIM + ":" + plane])
|
||||
const start = new Date(end - minutes * 60000).toISOString()
|
||||
const rows = await flowReadDbAll<{server_id: number; key: string; dim: string; bytes: string; packets: string; last_at: Date | string}>(`
|
||||
SELECT server_id, key, dim, COALESCE(SUM(bytes) FILTER (WHERE bucket_at >= ?), 0) AS bytes,
|
||||
COALESCE(SUM(packets) FILTER (WHERE bucket_at >= ?), 0) AS packets, MAX(bucket_at) AS last_at
|
||||
FROM flow_minute_dims
|
||||
WHERE server_id = ANY(?::bigint[]) AND bucket_at >= ? AND bucket_at < ? AND dim = ANY(?::text[])
|
||||
GROUP BY server_id, key, dim
|
||||
`, [start, start, serverIds, new Date(end - Math.max(minutes, 60) * 60000).toISOString(),
|
||||
`, [start, start, serverIds, new Date(Math.min(Date.parse(start), end - 60 * 60_000)).toISOString(),
|
||||
new Date(end).toISOString(), dimensions])
|
||||
const totals = new Map<string, FlowMapInterfaceTraffic>()
|
||||
for (const row of rows) {
|
||||
@@ -481,10 +484,13 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
if (!scope) refreshFlowCatalogInBackground()
|
||||
await authorize()
|
||||
const limits = scope ? await readFlowMapSourceLimits() : undefined
|
||||
const windowSec = Math.max(60, q.minutes * 60)
|
||||
const now = Date.now()
|
||||
const completeUntil = Math.floor(now / 60_000) * 60_000
|
||||
const startMs = completeUntil - Math.max(1, q.minutes) * 60_000
|
||||
const end = q.includeCurrentMinute ? now : completeUntil
|
||||
const windowSec = (end - startMs) / 1000
|
||||
await authorize()
|
||||
const end = Math.floor(Date.now() / 60000) * 60000
|
||||
const start = new Date(end - windowSec * 1000).toISOString()
|
||||
const start = new Date(startMs).toISOString()
|
||||
const raw = await listStoredFlowRows(start, q.serverId, { ...(scope ? { maxRows: scope.maxRows } : {}), untilIso: new Date(end - 1).toISOString() })
|
||||
if (scope && raw.some(row => row.serverId !== q.serverId)) throw new Error("Строка карты вне выбранного сервера")
|
||||
await authorize()
|
||||
@@ -496,21 +502,17 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const excludeOverlay = q.excludeOverlay !== false
|
||||
await authorize()
|
||||
const topo = await loadFlowTopology(scope?.serverIds, authorize)
|
||||
let allow: Map<number, Set<string>> | null = null
|
||||
if (q.userId) {
|
||||
if (!scope) allow = await userIfaceAllow(q.userId)
|
||||
else {
|
||||
allow = new Map()
|
||||
for (const binding of topo.clientByIface.values()) if (binding.userId === q.userId) {
|
||||
const names = allow.get(binding.serverId) ?? new Set<string>(); names.add(binding.interfaceName); allow.set(binding.serverId, names)
|
||||
}
|
||||
if (!allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
}
|
||||
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
|
||||
if (scope && allow && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||
|
||||
function rowClient(r: (typeof raw)[number]) {
|
||||
return resolveFlowClient(topo, r.serverId, resolveIfaceName(r.serverId, r.inIface).name, resolveIfaceName(r.serverId, r.outIface).name)
|
||||
}
|
||||
|
||||
const matches = (serverId: number, iface: string) =>
|
||||
flowRowMatchesFilter({ serverId, inIface: iface }, resolveIfaceName(serverId, iface).name, q, allow)
|
||||
const selected = raw.filter(r => matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface))
|
||||
const selected = raw.filter(r => (!q.userId || rowClient(r)?.userId === q.userId) &&
|
||||
(matches(r.serverId, r.inIface) || matches(r.serverId, r.outIface)))
|
||||
const { rows } = collapseGreEspRows(selected, r => {
|
||||
if (ifaceFilter) {
|
||||
const ingress = matches(r.serverId, r.inIface), egress = matches(r.serverId, r.outIface)
|
||||
@@ -548,16 +550,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
}
|
||||
await authorize()
|
||||
const peers = await readMapGrePeers(working)
|
||||
const observed = new Map<(typeof working)[number], { endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; reverse: boolean }>()
|
||||
const observed = new Map<(typeof working)[number], {
|
||||
endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; viaIface?: string; reverse: boolean
|
||||
client: ReturnType<typeof rowClient>; nodeBytes: Map<number, number>
|
||||
}>()
|
||||
const nodeUsers = new Map<number, Map<string, ClientAcc>>()
|
||||
const enIds = new Set(topo.enNodes.map((n) => n.id))
|
||||
let totalBytes = 0
|
||||
|
||||
function rowClient(r: (typeof working)[number]) {
|
||||
const inName = resolveIfaceName(r.serverId, r.inIface).name
|
||||
const outName = resolveIfaceName(r.serverId, r.outIface).name
|
||||
return resolveMapClient(topo, r.serverId, inName, outName)
|
||||
}
|
||||
|
||||
for (const r of working) {
|
||||
const inRes = resolveIfaceName(r.serverId, r.inIface)
|
||||
const outRes = resolveIfaceName(r.serverId, r.outIface)
|
||||
@@ -623,7 +623,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const reverse = !!endpoints.internetPeer && (endpoints.internetPeer === endpoints.packetSrc || endpoints.internetPeer === r.natSrc)
|
||||
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : peerId
|
||||
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
|
||||
observed.set(r, { endpoints, exitId, reverse })
|
||||
const serviceIface = reverse ? inName : outName
|
||||
const otherIface = reverse ? outName : inName
|
||||
const viaIface = exitId === undefined
|
||||
? ifaceUsable(serviceIface) ? serviceIface : ifaceUsable(otherIface) ? otherIface : undefined
|
||||
: undefined
|
||||
const nodeBytes = new Map([[r.serverId, r.bytes]])
|
||||
if (exitId !== undefined) nodeBytes.set(exitId, r.bytes)
|
||||
observed.set(r, { endpoints, exitId, viaIface, reverse, client: resolveFlowClient(topo, r.serverId, inName, outName), nodeBytes })
|
||||
if (peerId && peerId !== r.serverId) {
|
||||
const toId = String(peerId)
|
||||
const dir = outId === peerId ? "fwd" : "rev"
|
||||
@@ -662,31 +669,49 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
}
|
||||
}
|
||||
|
||||
const payloadBytes = new Map<(typeof working)[number], number>()
|
||||
const payloadRows = wantDedup
|
||||
? dedupFlowRowsAcrossExporters(working, (a, b) => {
|
||||
const aRouted = observed.get(a)?.exitId !== undefined
|
||||
const bRouted = observed.get(b)?.exitId !== undefined
|
||||
if (aRouted !== bRouted) return aRouted ? a : b
|
||||
const aCli = Boolean(rowClient(a))
|
||||
const bCli = Boolean(rowClient(b))
|
||||
if (aCli !== bCli) return aCli ? a : b
|
||||
return a.bytes >= b.bytes ? a : b
|
||||
const observationA = observed.get(a)!
|
||||
const observationB = observed.get(b)!
|
||||
const aRouted = observationA.exitId !== undefined
|
||||
const bRouted = observationB.exitId !== undefined
|
||||
const aCli = Boolean(observationA.client)
|
||||
const bCli = Boolean(observationB.client)
|
||||
const attributed = aRouted !== bRouted ? (aRouted ? a : b)
|
||||
: aCli !== bCli ? (aCli ? a : b)
|
||||
: a.bytes >= b.bytes ? a : b
|
||||
// Route/client evidence and the largest byte observation can come from different exporters.
|
||||
payloadBytes.set(attributed, Math.max(payloadBytes.get(a) ?? a.bytes, b.bytes))
|
||||
const clientA = observationA.client, clientB = observationB.client
|
||||
const chosen = observed.get(attributed)!
|
||||
chosen.client = clientA === null || clientB === null || (clientA && clientB && clientA.userId !== clientB.userId)
|
||||
? null : clientA ?? clientB
|
||||
for (const [id, bytes] of (attributed === a ? observationB : observationA).nodeBytes) {
|
||||
chosen.nodeBytes.set(id, Math.max(chosen.nodeBytes.get(id) ?? 0, bytes))
|
||||
}
|
||||
return attributed
|
||||
})
|
||||
: working
|
||||
|
||||
for (const r of payloadRows) {
|
||||
const inName = resolveIfaceName(r.serverId, r.inIface).name
|
||||
const outName = resolveIfaceName(r.serverId, r.outIface).name
|
||||
totalBytes += r.bytes
|
||||
const { endpoints: ep, exitId, reverse } = observed.get(r)!
|
||||
const bytes = payloadBytes.get(r) ?? r.bytes
|
||||
totalBytes += bytes
|
||||
const { endpoints: ep, exitId, viaIface, reverse, client, nodeBytes } = observed.get(r)!
|
||||
for (const [id, observedBytes] of nodeBytes) {
|
||||
const users = nodeUsers.get(id) ?? new Map<string, ClientAcc>()
|
||||
bumpClient(users, observedBytes, client ?? null)
|
||||
nodeUsers.set(id, users)
|
||||
}
|
||||
const dst = ep.internetPeer
|
||||
const dstPort = ep.peerPort || r.dstPort
|
||||
const srcPort = ep.otherPort || r.srcPort
|
||||
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
|
||||
const client = resolveMapClient(topo, r.serverId, inName, outName)
|
||||
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, fromBytes: new Map<string, FromAcc>() }
|
||||
acc.bytes += r.bytes
|
||||
if (exitId !== undefined) bumpFrom(acc, String(r.serverId), String(exitId), r.bytes, reverse, client)
|
||||
const application = flowPortApplication(r.proto, dstPort) ?? flowPortApplication(r.proto, srcPort)
|
||||
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : JSON.stringify([r.proto, application])
|
||||
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, lastBucketAt: "", proto: r.proto, dstPort, srcPort, application, fromBytes: new Map<string, FromAcc>() }
|
||||
acc.bytes += bytes
|
||||
if (bytes > 0 && r.bucketAt > acc.lastBucketAt) acc.lastBucketAt = r.bucketAt
|
||||
bumpFrom(acc, String(r.serverId), exitId === undefined ? "" : String(exitId), viaIface, bytes, reverse, client)
|
||||
dstAcc.set(destKey, acc)
|
||||
}
|
||||
|
||||
@@ -716,13 +741,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
const ripe = dst ? resolveFlowIp(dst) : null
|
||||
const classified = dst
|
||||
? mapInternetBrand(dst, acc.proto, acc.dstPort, acc.srcPort, ripe)
|
||||
: { service: OTHER_SERVICE, category: OTHER_SERVICE }
|
||||
: OTHER_BRAND
|
||||
const svcId = mapServiceNodeId(classified.service)
|
||||
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes)
|
||||
const detail = { transport: protoName(acc.proto), application: acc.application, basis: classified.basis }
|
||||
bumpDestTotal(svcTotals, svcId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
|
||||
const country = countryDestFromRipe(ripe, dst)
|
||||
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes)
|
||||
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes, acc.lastBucketAt)
|
||||
const nestedId = mapCountryServiceNodeId(country.id, svcId)
|
||||
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes)
|
||||
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes, acc.lastBucketAt, detail)
|
||||
for (const from of acc.fromBytes.values()) {
|
||||
const { exporterId, enId: fromId } = from
|
||||
const enName = nodeName(fromId)
|
||||
@@ -755,15 +781,19 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
||||
if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || !isDeepStrictEqual(limits, await readFlowMapSourceLimits()))) throw new Error("Топология или пределы карты NetFlow изменились во время чтения")
|
||||
await authorize()
|
||||
// Whole-interface counters must never be exposed as per-user payload or added to totalBytes.
|
||||
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, end)
|
||||
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, start, end)
|
||||
await authorize()
|
||||
return {
|
||||
...(interfaceTraffic ? { interfaceTraffic } : {}),
|
||||
nodeUsers: Object.fromEntries([...nodeUsers].map(([id, users]) => [id, [...users].map(([clientId, { name, bytes }]) => (
|
||||
{ clientId, clientName: name, bytes, bps: bytes * 8 / windowSec }
|
||||
)).sort((a, b) => b.bytes - a.bytes)])),
|
||||
hops: [...hops.values()]
|
||||
.map((a) => toHop(a, windowSec))
|
||||
.sort((a, b) => a.bytes === b.bytes ? 0 : b.bytes - a.bytes),
|
||||
live: listener.bound,
|
||||
rangeMinutes: q.minutes,
|
||||
...(q.includeCurrentMinute ? { includesCurrentMinute: true as const } : {}),
|
||||
windowSec,
|
||||
totalBytes,
|
||||
namedBytes,
|
||||
|
||||
@@ -7,7 +7,7 @@ export const PLANE_LABEL: Record<FlowPlane, string> = {
|
||||
mgmt: "mgmt",
|
||||
}
|
||||
|
||||
const WG_PORTS = new Set([51820, 13232, 51821])
|
||||
const WG_PORTS = new Set([51820, 13231, 13232, 51821])
|
||||
const FLOW_PORTS = new Set([4739, 2055])
|
||||
|
||||
export function isRfc1918(ip: string): boolean {
|
||||
|
||||
@@ -42,6 +42,27 @@ export interface ServerCatalogEntry {
|
||||
|
||||
const CATALOG_TTL_MS = 5_000
|
||||
|
||||
// The latest completed RouterOS wave records all observed peers, including disabled peers.
|
||||
export const flowBindingAttributionSql = `
|
||||
NOT EXISTS (
|
||||
SELECT 1 FROM user_interface_bindings conflict
|
||||
WHERE conflict.server_id=b.server_id AND conflict.interface_name=b.interface_name AND conflict.id<>b.id
|
||||
) AND (b.peer_public_key='' OR (b.interface_type='wg' AND EXISTS (
|
||||
SELECT 1 FROM traffic_collection_state state
|
||||
JOIN servers source ON source.id=state.server_id AND source.enabled AND source.updated_at=state.server_updated_at
|
||||
JOIN traffic_samples peer ON peer.server_id=state.server_id AND peer.sampled_at=state.last_succeeded_at
|
||||
AND peer.interface_name=b.interface_name AND peer.peer_public_key=b.peer_public_key
|
||||
WHERE state.server_id=b.server_id AND state.status IN ('ok','pending')
|
||||
AND state.last_succeeded_at >= now() - make_interval(secs => 5 * greatest(5, COALESCE(
|
||||
(SELECT interval_sec FROM traffic_settings WHERE id=1), 30)))
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM traffic_samples sibling
|
||||
WHERE sibling.server_id=peer.server_id AND sibling.sampled_at=peer.sampled_at
|
||||
AND sibling.interface_name=peer.interface_name AND sibling.peer_public_key NOT IN ('',peer.peer_public_key)
|
||||
)
|
||||
)))
|
||||
`
|
||||
|
||||
let seeded: FlowTopology | null = null
|
||||
let topologyCache: { at: number; topo: FlowTopology } | null = null
|
||||
let serverCatalogCache: { at: number; list: ServerCatalogEntry[]; byId: Map<number, ServerCatalogEntry> } | null = null
|
||||
@@ -124,11 +145,17 @@ export async function loadFlowTopology(serverIds?: readonly number[], authorize:
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=u.id AND NOT(hidden.server_id=ANY(?::bigint[]))) LIMIT 1001
|
||||
`, [serverIds, serverIds])
|
||||
await authorize()
|
||||
const binds = serverIds === undefined ? await flowReadDbAll<{userId:string;serverId:number;interfaceName:string}>('SELECT user_id AS "userId",server_id AS "serverId",interface_name AS "interfaceName" FROM user_interface_bindings') : await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string }>(`
|
||||
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName" FROM user_interface_bindings b
|
||||
WHERE b.server_id=ANY(?::bigint[]) AND b.peer_public_key='' AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[]))) ORDER BY b.id
|
||||
LIMIT 1001
|
||||
`, [serverIds, serverIds])
|
||||
const binds = await flowReadDbAll<{ userId: string; serverId: number; interfaceName: string; attributable: boolean }>(`
|
||||
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName",
|
||||
(${flowBindingAttributionSql}) AS attributable
|
||||
FROM user_interface_bindings b
|
||||
WHERE (?::bigint[] IS NULL OR (
|
||||
b.server_id=ANY(?::bigint[]) AND ${flowBindingAttributionSql}
|
||||
AND NOT EXISTS(SELECT 1 FROM user_interface_bindings hidden WHERE hidden.user_id=b.user_id AND NOT(hidden.server_id=ANY(?::bigint[])))
|
||||
))
|
||||
ORDER BY b.id
|
||||
LIMIT ?
|
||||
`, [serverIds ?? null, serverIds ?? null, serverIds ?? null, serverIds === undefined ? null : 1001])
|
||||
if (serverIds !== undefined && (binds.length > 1000 || users.length > 1000)) throw new Error("Превышен предел топологии NetFlow")
|
||||
const loginById = new Map(users.map((u) => [u.id, u]))
|
||||
const clientIfaces = new Map<number, Set<string>>()
|
||||
@@ -139,6 +166,7 @@ export async function loadFlowTopology(serverIds?: readonly number[], authorize:
|
||||
set.add(b.interfaceName)
|
||||
clientIfaces.set(b.serverId, set)
|
||||
allClientNames.add(b.interfaceName)
|
||||
if (!b.attributable) continue
|
||||
const user = loginById.get(b.userId)
|
||||
clientByIface.set(ifaceKey(b.serverId, b.interfaceName), {
|
||||
userId: b.userId,
|
||||
@@ -213,6 +241,24 @@ export function resolveClient(
|
||||
return topo.clientByIface.get(ifaceKey(serverId, inIfaceName)) ?? null
|
||||
}
|
||||
|
||||
/** null represents conflicting ownership; undefined means no attributable interface. */
|
||||
export function resolveFlowClient(topo: FlowTopology, serverId: number, inIface: string, outIface: string) {
|
||||
const ingress = resolveClient(topo, serverId, inIface)
|
||||
const egress = resolveClient(topo, serverId, outIface)
|
||||
if (ingress && egress && ingress.userId !== egress.userId) return null
|
||||
return ingress ?? egress ?? undefined
|
||||
}
|
||||
|
||||
export function flowClientInterfaces(topo: FlowTopology, userId: string) {
|
||||
const interfaces = new Map<number, Set<string>>()
|
||||
for (const binding of topo.clientByIface.values()) if (binding.userId === userId) {
|
||||
const names = interfaces.get(binding.serverId) ?? new Set<string>()
|
||||
names.add(binding.interfaceName)
|
||||
interfaces.set(binding.serverId, names)
|
||||
}
|
||||
return interfaces
|
||||
}
|
||||
|
||||
export function resolveEn(
|
||||
topo: FlowTopology,
|
||||
nextHop: string,
|
||||
|
||||
@@ -47,10 +47,18 @@ else {
|
||||
assert.equal(sample.headers["cache-control"], "no-store")
|
||||
assert.deepEqual(sample.json(), { rxMbps: 0, txMbps: 0, at: sample.json().at, timestampKind: "backend-receipt" })
|
||||
assert.equal(nativeRequests, beforeSample + 1)
|
||||
assert.equal((await app.inject(sampleUrl + "&ifaces=ether1,ether1")).statusCode, 400)
|
||||
assert.equal((await app.inject(sampleUrl + "&ifaces=ether1,ether2&iface=ether1")).statusCode, 400)
|
||||
assert.equal(nativeRequests, beforeSample + 1)
|
||||
const batch = await app.inject(sampleUrl + "&ifaces=ether1,ether2")
|
||||
assert.equal(batch.statusCode, 200)
|
||||
assert.equal(batch.headers["cache-control"], "no-store")
|
||||
assert.deepEqual(Object.keys(batch.json().interfaces), ["ether1", "ether2"])
|
||||
assert.equal(nativeRequests, beforeSample + 2)
|
||||
mode = "malformed"
|
||||
assert.equal((await app.inject(sampleUrl + "&iface=ether1")).statusCode, 503)
|
||||
mode = "zero"
|
||||
cases += 3
|
||||
cases += 6
|
||||
let stream=await open(),event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);assert.equal(event?.data.timestampKind,"backend-receipt");stream.close();cases++
|
||||
for(const kind of ["empty","malformed","partial"]){mode=kind;two=kind==="partial";stream=await open();event=await stream.next();assert.equal(event?.event,"error");stream.close();cases++}
|
||||
mode="fallback";two=true;stream=await open();event=await stream.next();assert.equal(event?.event,"sample");assert.equal(event?.data.rxMbps,0);stream.close();cases++
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { parseMonitorTraffic, rateBpsFromDelta, bpsToMbps } from "./traffic-rate.js"
|
||||
import { readTrafficLiveSample, TrafficLiveSourceChanged } from "./traffic-live.js"
|
||||
import { readTrafficLiveInterfaces, readTrafficLiveSample, TrafficLiveSourceChanged } from "./traffic-live.js"
|
||||
import { MikrotikError, type MikrotikClient } from "./mikrotik.js"
|
||||
const point=(name="ether1",rx:unknown="0",tx:unknown="0")=>({name,"rx-bits-per-second":rx,"tx-bits-per-second":tx})
|
||||
for(const raw of [[],{},null,[null],[{...point(),"rx-bits-per-second":undefined}], [point("ether1","12bad")],[point("ether1",-1)], [point("ether1"),point("ether1")]]) {
|
||||
@@ -34,4 +34,18 @@ const many={get:async()=>Array.from({length:10},(_,i)=>({name:`ether${i}`,runnin
|
||||
}} as unknown as Pick<MikrotikClient,"get"|"post">
|
||||
const bounded=await readTrafficLiveSample(many,undefined,{names:[],joinedFailed:false},new AbortController().signal,async()=>{})
|
||||
assert.equal(bounded.rxMbps,0);assert.equal(maximum,4)
|
||||
|
||||
const batch = (testClient = cast) =>
|
||||
readTrafficLiveInterfaces(testClient, ["ether1", "ether2"], new AbortController().signal, async () => {})
|
||||
const joined = { ...cast, post: async () => [point("ether2", "0", "80000000"), point("ether1", "1300000", "0")] } as typeof cast
|
||||
const measurements = await batch(joined)
|
||||
assert.equal(measurements.ether1.rxMbps, 1.3)
|
||||
assert.equal(measurements.ether2.txMbps, 80)
|
||||
assert.equal(measurements.ether1.at, measurements.ether2.at)
|
||||
mode = "partial"
|
||||
assert.deepEqual(Object.keys(await batch()), ["ether1"])
|
||||
mode = "fallback"
|
||||
assert.deepEqual(Object.keys(await batch()), ["ether1", "ether2"])
|
||||
mode = "auth"
|
||||
await assert.rejects(batch(), /401/)
|
||||
console.log("traffic live completeness/fallback/auth/source/abort/positive-small-rate tests ok")
|
||||
@@ -1,14 +1,15 @@
|
||||
import { MikrotikError, type MikrotikClient } from "./mikrotik.js"
|
||||
import { isLoopbackName, parseMonitorTraffic, type MonitorLiveSample } from "./traffic-rate.js"
|
||||
import { isLoopbackName, parseMonitorTraffic, parseMonitorTrafficInterfaces, type MonitorLiveSample } from "./traffic-rate.js"
|
||||
|
||||
const TIMEOUT_MS = 4000
|
||||
export class TrafficLiveSourceChanged extends Error {}
|
||||
export interface TrafficLiveCache { names: string[]; joinedFailed: boolean }
|
||||
type Client = Pick<MikrotikClient, "get" | "post">
|
||||
type Monitor = (names: string) => Promise<unknown>
|
||||
|
||||
/** Never emit a partial sum, and check the source before every new native request. */
|
||||
export async function readTrafficLiveSample(client: Client, onlyInterface: string | undefined,
|
||||
cache: TrafficLiveCache, signal: AbortSignal, assertSource: () => Promise<void>): Promise<MonitorLiveSample> {
|
||||
/** Check the source before every new native request. */
|
||||
async function withTrafficMonitor<T>(client: Client, signal: AbortSignal, assertSource: () => Promise<void>,
|
||||
read: (monitor: Monitor, ensure: () => Promise<void>) => Promise<T>): Promise<T> {
|
||||
const parentSignal = signal, wave = new AbortController()
|
||||
const onAbort = () => wave.abort(parentSignal.reason)
|
||||
parentSignal.addEventListener("abort", onAbort, { once: true })
|
||||
@@ -16,52 +17,12 @@ export async function readTrafficLiveSample(client: Client, onlyInterface: strin
|
||||
const timeout = setTimeout(() => wave.abort(new Error("Не успели получить полный live-срез за 8 секунд. Выберите отдельный интерфейс")), 8000)
|
||||
signal = wave.signal
|
||||
try {
|
||||
const ensure = async () => { signal.throwIfAborted(); await assertSource(); signal.throwIfAborted() }
|
||||
const monitor = async (name: string) => {
|
||||
await ensure()
|
||||
return client.post<unknown>("/interface/monitor-traffic", { interface: name, once: "" }, TIMEOUT_MS, signal)
|
||||
}
|
||||
if (onlyInterface) {
|
||||
const raw = await monitor(onlyInterface)
|
||||
await ensure()
|
||||
return parseMonitorTraffic(raw, { onlyInterface })
|
||||
}
|
||||
await ensure()
|
||||
const raw = await client.get<unknown>("/interface", TIMEOUT_MS)
|
||||
if (!Array.isArray(raw)) throw new Error("Не получен каталог интерфейсов live")
|
||||
const names: string[] = []
|
||||
const flag = (value: unknown) => {
|
||||
if (value === true || value === "true" || value === "yes") return true
|
||||
if (value === false || value === "false" || value === "no") return false
|
||||
throw new Error("Неизвестное состояние интерфейса live")
|
||||
}
|
||||
for (const row of raw) {
|
||||
if (!row || typeof row !== "object" || Array.isArray(row) || typeof row.name !== "string" || !row.name.trim()) throw new Error("Некорректный каталог интерфейсов live")
|
||||
if (flag(row.running) && !flag(row.disabled) && !isLoopbackName(row.name)) names.push(row.name)
|
||||
}
|
||||
if (!names.length || new Set(names).size !== names.length) throw new Error("Нет достоверного набора активных интерфейсов live")
|
||||
if ([...names].sort().join("\0") !== [...cache.names].sort().join("\0")) cache.joinedFailed = false
|
||||
cache.names = names
|
||||
if (!cache.joinedFailed) {
|
||||
try {
|
||||
const result = await monitor(names.join(","))
|
||||
const ensure = async () => { signal.throwIfAborted(); await assertSource(); signal.throwIfAborted() }
|
||||
const monitor = async (name: string) => {
|
||||
await ensure()
|
||||
return parseMonitorTraffic(result, { expectedInterfaces: names })
|
||||
} catch (error) {
|
||||
// Unsupported joined command may fall back; auth/transport/invalid payload cannot become partial zero.
|
||||
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
|
||||
cache.joinedFailed = true
|
||||
return client.post<unknown>("/interface/monitor-traffic", { interface: name, once: "" }, TIMEOUT_MS, signal)
|
||||
}
|
||||
}
|
||||
const results: MonitorLiveSample[] = []
|
||||
for (let i = 0; i < names.length; i += 4) {
|
||||
results.push(...await Promise.all(names.slice(i, i + 4).map(async name =>
|
||||
parseMonitorTraffic(await monitor(name), { onlyInterface: name }))))
|
||||
}
|
||||
await ensure()
|
||||
const rxMbps = results.reduce((sum, r) => sum + r.rxMbps, 0), txMbps = results.reduce((sum, r) => sum + r.txMbps, 0)
|
||||
if (![rxMbps, txMbps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER / 1_000_000)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return { rxMbps, txMbps, at: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
return await read(monitor, ensure)
|
||||
} catch (error) {
|
||||
if (signal.aborted && !parentSignal.aborted && signal.reason instanceof Error) throw signal.reason
|
||||
throw error
|
||||
@@ -71,3 +32,71 @@ export async function readTrafficLiveSample(client: Client, onlyInterface: strin
|
||||
wave.abort()
|
||||
}
|
||||
}
|
||||
|
||||
export function readTrafficLiveInterfaces(client: Client, names: readonly string[], signal: AbortSignal, assertSource: () => Promise<void>) {
|
||||
return withTrafficMonitor(client, signal, assertSource, async (monitor, ensure) => {
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = await monitor(names.join(","))
|
||||
} catch (error) {
|
||||
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
|
||||
const samples = []
|
||||
for (let offset = 0; offset < names.length; offset += 4) {
|
||||
const reads = await Promise.allSettled(names.slice(offset, offset + 4).map(async name =>
|
||||
[name, parseMonitorTraffic(await monitor(name), { onlyInterface: name })] as const))
|
||||
for (const read of reads) if (read.status === "fulfilled") samples.push(read.value)
|
||||
}
|
||||
await ensure()
|
||||
return Object.fromEntries(samples)
|
||||
}
|
||||
await ensure()
|
||||
return parseMonitorTrafficInterfaces(raw, names)
|
||||
})
|
||||
}
|
||||
|
||||
export function readTrafficLiveSample(client: Client, onlyInterface: string | undefined,
|
||||
cache: TrafficLiveCache, signal: AbortSignal, assertSource: () => Promise<void>): Promise<MonitorLiveSample> {
|
||||
return withTrafficMonitor(client, signal, assertSource, async (monitor, ensure) => {
|
||||
if (onlyInterface) {
|
||||
const raw = await monitor(onlyInterface)
|
||||
await ensure()
|
||||
return parseMonitorTraffic(raw, { onlyInterface })
|
||||
}
|
||||
await ensure()
|
||||
const raw = await client.get<unknown>("/interface", TIMEOUT_MS)
|
||||
if (!Array.isArray(raw)) throw new Error("Не получен каталог интерфейсов live")
|
||||
const names: string[] = []
|
||||
const flag = (value: unknown) => {
|
||||
if (value === true || value === "true" || value === "yes") return true
|
||||
if (value === false || value === "false" || value === "no") return false
|
||||
throw new Error("Неизвестное состояние интерфейса live")
|
||||
}
|
||||
for (const row of raw) {
|
||||
if (!row || typeof row !== "object" || Array.isArray(row) || typeof row.name !== "string" || !row.name.trim()) throw new Error("Некорректный каталог интерфейсов live")
|
||||
if (flag(row.running) && !flag(row.disabled) && !isLoopbackName(row.name)) names.push(row.name)
|
||||
}
|
||||
if (!names.length || new Set(names).size !== names.length) throw new Error("Нет достоверного набора активных интерфейсов live")
|
||||
if ([...names].sort().join("\0") !== [...cache.names].sort().join("\0")) cache.joinedFailed = false
|
||||
cache.names = names
|
||||
if (!cache.joinedFailed) {
|
||||
try {
|
||||
const result = await monitor(names.join(","))
|
||||
await ensure()
|
||||
return parseMonitorTraffic(result, { expectedInterfaces: names })
|
||||
} catch (error) {
|
||||
// Unsupported joined command may fall back; auth/transport/invalid payload cannot become partial zero.
|
||||
if (!(error instanceof MikrotikError) || error.statusCode !== 400 || names.length < 2) throw error
|
||||
cache.joinedFailed = true
|
||||
}
|
||||
}
|
||||
const results: MonitorLiveSample[] = []
|
||||
for (let i = 0; i < names.length; i += 4) {
|
||||
results.push(...await Promise.all(names.slice(i, i + 4).map(async name =>
|
||||
parseMonitorTraffic(await monitor(name), { onlyInterface: name }))))
|
||||
}
|
||||
await ensure()
|
||||
const rxMbps = results.reduce((sum, r) => sum + r.rxMbps, 0), txMbps = results.reduce((sum, r) => sum + r.txMbps, 0)
|
||||
if (![rxMbps, txMbps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER / 1_000_000)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return { rxMbps, txMbps, at: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
})
|
||||
}
|
||||
@@ -360,14 +360,11 @@ export function mergeBuiltTraffic(parts: BuiltTrafficSeries[]): BuiltTrafficSeri
|
||||
} } : acc,waves)
|
||||
}
|
||||
|
||||
export function parseMonitorTraffic(
|
||||
raw: unknown,
|
||||
opts?: { onlyInterface?: string; expectedInterfaces?: readonly string[] },
|
||||
): MonitorLiveSample {
|
||||
type MonitorTrafficSelection = { onlyInterface?: string; expectedInterfaces?: readonly string[]; allowMissing?: boolean }
|
||||
|
||||
function monitorTrafficRates(raw: unknown, opts?: MonitorTrafficSelection) {
|
||||
const items = Array.isArray(raw) ? raw : raw != null ? [raw] : []
|
||||
let rxBps = 0
|
||||
let txBps = 0
|
||||
const seen = new Set<string>()
|
||||
const samples = new Map<string, { rxBps: number; txBps: number }>()
|
||||
const expected = opts?.expectedInterfaces ? new Set(opts.expectedInterfaces) : null
|
||||
const rate = (raw: unknown) => {
|
||||
if (typeof raw !== "number" && (typeof raw !== "string" || !/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(raw.trim()))) throw new Error("Некорректная скорость monitor-traffic")
|
||||
@@ -382,21 +379,33 @@ export function parseMonitorTraffic(
|
||||
if (typeof name !== "string" || !name.trim()) throw new Error("Не указан интерфейс monitor-traffic")
|
||||
if (opts?.onlyInterface) {
|
||||
if (name !== opts.onlyInterface) throw new Error("Ответ monitor-traffic относится к другому интерфейсу")
|
||||
} else if (isLoopbackName(name)) {
|
||||
} else if (isLoopbackName(name) && !expected?.has(name)) {
|
||||
continue
|
||||
}
|
||||
if (seen.has(name) || expected && !expected.has(name)) throw new Error("Некорректный набор интерфейсов monitor-traffic")
|
||||
seen.add(name)
|
||||
rxBps += rate(rec["rx-bits-per-second"])
|
||||
txBps += rate(rec["tx-bits-per-second"])
|
||||
}
|
||||
if (!seen.size || expected && (expected.size !== opts!.expectedInterfaces!.length ||
|
||||
[...expected].some(name => !seen.has(name)))) throw new Error("Не получены все live-измерения интерфейсов")
|
||||
if (![rxBps, txBps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return {
|
||||
rxMbps: rxBps / 1_000_000,
|
||||
txMbps: txBps / 1_000_000,
|
||||
at: new Date().toISOString(),
|
||||
timestampKind: "backend-receipt",
|
||||
if (samples.has(name) || expected && !expected.has(name)) throw new Error("Некорректный набор интерфейсов monitor-traffic")
|
||||
samples.set(name, {
|
||||
rxBps: rate(rec["rx-bits-per-second"]),
|
||||
txBps: rate(rec["tx-bits-per-second"]),
|
||||
})
|
||||
}
|
||||
if (!opts?.allowMissing && (!samples.size || expected && (expected.size !== opts!.expectedInterfaces!.length ||
|
||||
samples.size !== expected.size))) throw new Error("Не получены все live-измерения интерфейсов")
|
||||
return samples
|
||||
}
|
||||
|
||||
export function parseMonitorTrafficInterfaces(raw: unknown, expectedInterfaces: readonly string[]): Record<string, MonitorLiveSample> {
|
||||
const at = new Date().toISOString()
|
||||
return Object.fromEntries([...monitorTrafficRates(raw, { expectedInterfaces, allowMissing: true })].map(([name, sample]) =>
|
||||
[name, { rxMbps: sample.rxBps / 1_000_000, txMbps: sample.txBps / 1_000_000, at, timestampKind: "backend-receipt" }]))
|
||||
}
|
||||
|
||||
export function parseMonitorTraffic(
|
||||
raw: unknown,
|
||||
opts?: { onlyInterface?: string; expectedInterfaces?: readonly string[] },
|
||||
): MonitorLiveSample {
|
||||
const samples = [...monitorTrafficRates(raw, opts).values()]
|
||||
const rxBps = samples.reduce((sum, row) => sum + row.rxBps, 0)
|
||||
const txBps = samples.reduce((sum, row) => sum + row.txBps, 0)
|
||||
if (![rxBps, txBps].every(n => Number.isFinite(n) && n <= Number.MAX_SAFE_INTEGER)) throw new Error("Суммарная live-скорость вне допустимого диапазона")
|
||||
return { rxMbps: rxBps / 1_000_000, txMbps: txBps / 1_000_000, at: new Date().toISOString(), timestampKind: "backend-receipt" }
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { NavMain, type NavGroup } from "@/components/nav-main"
|
||||
import { NavMain, type NavGroup, type NavItem } from "@/components/nav-main"
|
||||
import { AppSwitcher } from "@/components/app-switcher"
|
||||
import { NavUser } from "@/components/nav-user"
|
||||
import {
|
||||
@@ -12,103 +12,43 @@ import {
|
||||
} from "@/components/ui/sidebar"
|
||||
import { navigationGroups } from "@/lib/navigation"
|
||||
import { useDataSource } from "@/lib/data-source"
|
||||
import { can,ensureAuthConfig } from "@/lib/auth"
|
||||
import { useEvoBGP } from "@/lib/evobgp-context"
|
||||
import {getSidebarCounts,getSidebarGreCount} from "@/shared/api/sidebar-counts"
|
||||
import {
|
||||
formatSidebarBadgeCount,
|
||||
mockSidebarBadgesByUrl,
|
||||
type SidebarCountsDto,
|
||||
} from "@/lib/sidebar-badges"
|
||||
import { pingProbes, servers } from "@/lib/data"
|
||||
|
||||
type LiveSidebarCounts = Partial<SidebarCountsDto> & {
|
||||
greTunnels?: number
|
||||
certificates?: number
|
||||
wireguard?: number
|
||||
ipsec?: number
|
||||
users?: number
|
||||
bgpSessions?: number
|
||||
vxlan?: number
|
||||
containers?: number
|
||||
/**
|
||||
* Точки проблем у разделов. В демо — из моков; живой источник проблем по разделам API пока не отдаёт,
|
||||
* поэтому в live-режиме точек нет (неизвестное не выдаём за «всё в норме» и не рисуем ложные сбои).
|
||||
*/
|
||||
function demoProblems(): Record<string, NavItem["problem"]> {
|
||||
const offline = servers.filter((s) => s.enabled && s.status === "offline").length
|
||||
const degraded = servers.filter((s) => s.enabled && s.status === "degraded").length
|
||||
const down = pingProbes.filter((p) => p.enabled && p.status === "down").length
|
||||
const warn = pingProbes.filter((p) => p.enabled && p.status === "warn").length
|
||||
return {
|
||||
"/servers": offline ? { tone: "er", label: `Не в сети: ${offline}` } : degraded ? { tone: "wn", label: `С ухудшением: ${degraded}` } : undefined,
|
||||
"/uptime": down ? { tone: "er", label: `Проверок с ошибкой: ${down}` } : warn ? { tone: "wn", label: `Проверок с предупреждением: ${warn}` } : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** Боковое меню общего макета v2 и EvoBGP: переключатель приложений, поиск ⌘K, закреплённые, группы, профиль. */
|
||||
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
|
||||
const { mode, backendUrl, prefsHydrated } = useDataSource()
|
||||
const evo = useEvoBGP()
|
||||
const [mounted, setMounted] = React.useState(false)
|
||||
const [snapshot, setSnapshot] = React.useState<{source:string;counts:LiveSidebarCounts}|null>(null)
|
||||
const source=JSON.stringify([mode,backendUrl]),liveCounts=snapshot?.source===source?snapshot.counts:null
|
||||
const countsAllowed=can("mm:dashboard:read"),greAllowed=can("mm:filters:read")
|
||||
|
||||
const mockBadges = React.useMemo(() => mockSidebarBadgesByUrl(), [])
|
||||
|
||||
React.useEffect(() => {
|
||||
let cancelled=false
|
||||
void ensureAuthConfig().then(()=>{if(!cancelled)setMounted(true)})
|
||||
return()=>{cancelled=true}
|
||||
}, [])
|
||||
|
||||
React.useEffect(() => {
|
||||
if(!mounted||!prefsHydrated||mode!=="live")return
|
||||
let cancelled=false,revision=0,controller:AbortController|null=null
|
||||
const load=async()=>{
|
||||
controller?.abort();controller=new AbortController();const request=++revision,signal=AbortSignal.any([controller.signal,AbortSignal.timeout(30_000)])
|
||||
const publish=(counts:LiveSidebarCounts)=>{if(cancelled||request!==revision)return;setSnapshot(previous=>({source,counts:{...(previous?.source===source?previous.counts:{}),...counts}}))}
|
||||
await Promise.allSettled([
|
||||
can("mm:dashboard:read")?getSidebarCounts(backendUrl,signal).then(counts=>{if(can("mm:dashboard:read"))publish(counts)}):Promise.resolve(),
|
||||
can("mm:filters:read")?getSidebarGreCount(backendUrl,signal).then(greTunnels=>{if(can("mm:filters:read"))publish({greTunnels})}):Promise.resolve(),
|
||||
])
|
||||
}
|
||||
void load();const timer=window.setInterval(load,120_000)
|
||||
return()=>{cancelled=true;revision++;controller?.abort();window.clearInterval(timer)}
|
||||
},[mounted,mode,backendUrl,prefsHydrated,source,countsAllowed,greAllowed])
|
||||
const { mode, prefsHydrated } = useDataSource()
|
||||
|
||||
const navGroups = React.useMemo((): NavGroup[] => {
|
||||
function badgeFor(url: string): string | undefined {
|
||||
if (mode !== "live") return mockBadges[url]
|
||||
|
||||
if (url === "/domains" || url === "/ip-ranges" || url === "/asns") {
|
||||
if (!evo.settingsLoaded || !evo.enabled || !can("mm:settings:admin")) return undefined
|
||||
if (!evo.snapshot) return undefined
|
||||
if (url === "/domains") return formatSidebarBadgeCount(evo.snapshot.domains.length)
|
||||
if (url === "/ip-ranges") return formatSidebarBadgeCount(evo.snapshot.ipRanges.length)
|
||||
return formatSidebarBadgeCount(evo.snapshot.asns.length)
|
||||
}
|
||||
|
||||
if (!liveCounts||(!countsAllowed&&url!=="/gre")) return undefined
|
||||
const permission=({"/servers":"mm:servers:read","/users":"mm:users:read","/filters":"mm:filters:read","/uptime":"mm:uptime:read","/gre":"mm:filters:read","/certificates":"mm:certificates:read","/wireguard":"mm:network:read","/ipsec":"mm:network:read","/bgp":"mm:bgp:read","/vxlan":"mm:network:read","/containers":"mm:dashboard:read"} as Record<string,string>)[url]
|
||||
if(permission&&!can(permission))return undefined
|
||||
const format=(value:number|undefined)=>value===undefined?undefined:formatSidebarBadgeCount(value)
|
||||
|
||||
if (url === "/servers") return format(liveCounts.servers)
|
||||
if (url === "/users") return format(liveCounts.users )
|
||||
if (url === "/filters") return format(liveCounts.filterRules)
|
||||
if (url === "/uptime") return format(liveCounts.monitoringItems)
|
||||
if (url === "/gre") return format(liveCounts.greTunnels )
|
||||
if (url === "/certificates") return format(liveCounts.certificates )
|
||||
if (url === "/wireguard") return format(liveCounts.wireguard )
|
||||
if (url === "/ipsec") return format(liveCounts.ipsec )
|
||||
if (url === "/bgp") return format(liveCounts.bgpSessions )
|
||||
if (url === "/vxlan") return format(liveCounts.vxlan )
|
||||
if (url === "/containers") return format(liveCounts.containers )
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
const problems = prefsHydrated && mode !== "live" ? demoProblems() : {}
|
||||
return navigationGroups.map((g) => ({
|
||||
label: g.label,
|
||||
items: g.items.map((it) => ({
|
||||
title: it.title,
|
||||
url: it.url,
|
||||
icon: React.createElement(it.icon, { "aria-hidden": true }),
|
||||
badge: mounted ? badgeFor(it.url) : undefined,
|
||||
problem: problems[it.url],
|
||||
})),
|
||||
}))
|
||||
}, [mounted, mode, liveCounts, countsAllowed, mockBadges, evo.settingsLoaded, evo.enabled, evo.snapshot])
|
||||
}, [mode, prefsHydrated])
|
||||
|
||||
return (
|
||||
<Sidebar variant="inset" collapsible="icon" {...props}>
|
||||
<SidebarHeader>
|
||||
<Sidebar collapsible="icon" {...props}>
|
||||
<SidebarHeader className="pb-1.5">
|
||||
<AppSwitcher />
|
||||
</SidebarHeader>
|
||||
<SidebarContent>
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
import {
|
||||
APP_SWITCHER_ICONS,
|
||||
CURRENT_APP_ID,
|
||||
authPortalBaseUrl,
|
||||
getCurrentApp,
|
||||
} from "@/lib/app-switcher-config"
|
||||
import { useAppSwitcherConfig } from "@/hooks/use-app-switcher"
|
||||
@@ -26,6 +28,8 @@ export function AppSwitcher() {
|
||||
const { isMobile } = useSidebar()
|
||||
const { config, isLoading } = useAppSwitcherConfig()
|
||||
const current = getCurrentApp(config)
|
||||
const portalBase = authPortalBaseUrl()
|
||||
const portalAppsUrl = portalBase ? `${portalBase}/admin/apps` : null
|
||||
const CurrentIcon = APP_SWITCHER_ICONS[current.icon] ?? APP_SWITCHER_ICONS.server
|
||||
|
||||
return (
|
||||
@@ -34,7 +38,7 @@ export function AppSwitcher() {
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<SidebarMenuButton size="lg" className="aria-expanded:bg-muted" />
|
||||
<SidebarMenuButton size="lg" aria-label={`Переключатель приложений: ${current.name}`} className="aria-expanded:bg-muted" />
|
||||
}
|
||||
>
|
||||
<div
|
||||
@@ -89,6 +93,12 @@ export function AppSwitcher() {
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
{portalAppsUrl ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem render={<a href={portalAppsUrl} />}>Настроить на портале</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { LayoutGridIcon } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import {
|
||||
APP_SWITCHER_ICONS,
|
||||
CURRENT_APP_ID,
|
||||
authPortalBaseUrl,
|
||||
} from "@/lib/app-switcher-config"
|
||||
import { useAppSwitcherConfig } from "@/hooks/use-app-switcher"
|
||||
|
||||
/** Header apps grid — app-shell-12. @see https://reui.io/preview/base/app-shell-12 */
|
||||
export function AppsMenu() {
|
||||
const { config, isLoading } = useAppSwitcherConfig()
|
||||
const portalBase = authPortalBaseUrl()
|
||||
const portalAppsUrl = portalBase ? `${portalBase}/admin/apps` : null
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<Button variant="ghost" size="icon" aria-label="Приложения" />
|
||||
}
|
||||
>
|
||||
<LayoutGridIcon className="size-4.5" aria-hidden="true" />
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuContent
|
||||
side="bottom"
|
||||
align="end"
|
||||
sideOffset={8}
|
||||
className="w-72"
|
||||
>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuLabel>
|
||||
{isLoading ? "Загрузка…" : config.menuLabel}
|
||||
</DropdownMenuLabel>
|
||||
<div className="grid grid-cols-3 gap-1 p-1">
|
||||
{config.apps.map((app) => {
|
||||
const Icon = APP_SWITCHER_ICONS[app.icon] ?? APP_SWITCHER_ICONS.server
|
||||
const isCurrent = app.id === CURRENT_APP_ID
|
||||
|
||||
if (isCurrent) {
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={app.id}
|
||||
disabled
|
||||
className="h-auto flex-col gap-1.5 py-3 text-center [&_svg]:size-5"
|
||||
>
|
||||
<span className="text-muted-foreground">
|
||||
<Icon aria-hidden="true" />
|
||||
</span>
|
||||
<span className="text-xs font-medium">{app.name}</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={app.id}
|
||||
render={<a href={app.url} />}
|
||||
className="h-auto flex-col gap-1.5 py-3 text-center [&_svg]:size-5"
|
||||
>
|
||||
<span className="text-muted-foreground">
|
||||
<Icon aria-hidden="true" />
|
||||
</span>
|
||||
<span className="text-xs font-medium">{app.name}</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{portalAppsUrl ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
render={<a href={portalAppsUrl} />}
|
||||
className="justify-center text-sm font-medium"
|
||||
>
|
||||
Настроить на портале
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,13 @@ import { navigationGroups } from "@/lib/navigation"
|
||||
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"
|
||||
|
||||
const OPEN_EVENT = "mm:open-command-palette"
|
||||
|
||||
/** Открыть палитру из кнопки «Поиск и команды» (сайдбар) или поиска в шапке на телефоне. */
|
||||
export function openCommandPalette() {
|
||||
window.dispatchEvent(new Event(OPEN_EVENT))
|
||||
}
|
||||
|
||||
/** Keyboard search from the App Shell 12 composition, using installed Base UI primitives. */
|
||||
export function CommandPalette() {
|
||||
const [open, setOpen] = useState(false)
|
||||
@@ -26,8 +33,18 @@ export function CommandPalette() {
|
||||
setOpen(!open)
|
||||
}
|
||||
}
|
||||
function onOpen() {
|
||||
if (open) return
|
||||
returnFocusRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
setQuery("")
|
||||
setOpen(true)
|
||||
}
|
||||
window.addEventListener("keydown", onKey)
|
||||
return () => window.removeEventListener("keydown", onKey)
|
||||
window.addEventListener(OPEN_EVENT, onOpen)
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKey)
|
||||
window.removeEventListener(OPEN_EVENT, onOpen)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import Link from "next/link"
|
||||
import { usePathname } from "next/navigation"
|
||||
import { ChevronDownIcon, SearchIcon, StarIcon } from "lucide-react"
|
||||
import {
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarSeparator,
|
||||
useSidebar,
|
||||
} from "@/components/ui/sidebar"
|
||||
import { Kbd } from "@/components/ui/kbd"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { openCommandPalette } from "@/components/command-palette"
|
||||
|
||||
export interface NavItem {
|
||||
title: string
|
||||
url: string
|
||||
icon?: React.ReactNode
|
||||
/** Если `undefined` — счётчик не показываем (нет данных или раздел без live-источника). */
|
||||
badge?: string
|
||||
/** Точка проблемы у пункта: сбой (er) или внимание (wn); без данных — не показываем. */
|
||||
problem?: { tone: "er" | "wn"; label: string }
|
||||
}
|
||||
|
||||
export interface NavGroup {
|
||||
@@ -24,36 +32,144 @@ export interface NavGroup {
|
||||
items: NavItem[]
|
||||
}
|
||||
|
||||
export function NavMain({ groups }: { groups: NavGroup[] }) {
|
||||
const PINS_KEY = "mm:sidebar-pins"
|
||||
const CLOSED_KEY = "mm:sidebar-closed-groups"
|
||||
const DOT_CLASS = { er: "bg-destructive", wn: "bg-warning" } as const
|
||||
|
||||
function readList(key: string): string[] {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(key) ?? "[]")
|
||||
return Array.isArray(raw) ? raw.filter((v): v is string => typeof v === "string") : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function writeList(key: string, list: string[]) {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(list))
|
||||
} catch {
|
||||
/* хранилище недоступно — настройка действует до перезагрузки */
|
||||
}
|
||||
}
|
||||
|
||||
function NavEntry({ item, pinned, onTogglePin }: { item: NavItem; pinned: boolean; onTogglePin: () => void }) {
|
||||
const pathname = usePathname()
|
||||
const { setOpenMobile } = useSidebar()
|
||||
const active = pathname === item.url || pathname.startsWith(`${item.url}/`)
|
||||
return (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
isActive={active}
|
||||
tooltip={item.problem ? `${item.title} · ${item.problem.label}` : item.title}
|
||||
className="relative pr-8 group-data-[collapsible=icon]:pr-2!"
|
||||
render={<Link href={item.url} aria-current={active ? "page" : undefined} onNavigate={() => setOpenMobile(false)} />}
|
||||
>
|
||||
{item.icon}
|
||||
<span>{item.title}</span>
|
||||
{item.problem ? (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={item.problem.label}
|
||||
className={cn(
|
||||
"ml-auto size-2 shrink-0 rounded-full group-data-[collapsible=icon]:absolute group-data-[collapsible=icon]:top-1 group-data-[collapsible=icon]:right-1 group-data-[collapsible=icon]:ml-0 group-data-[collapsible=icon]:size-1.5 group-data-[collapsible=icon]:ring-2 group-data-[collapsible=icon]:ring-sidebar",
|
||||
DOT_CLASS[item.problem.tone],
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
</SidebarMenuButton>
|
||||
<SidebarMenuAction
|
||||
showOnHover={!pinned}
|
||||
aria-label={pinned ? `Открепить ${item.title}` : `Закрепить ${item.title}`}
|
||||
aria-pressed={pinned}
|
||||
onClick={onTogglePin}
|
||||
>
|
||||
<StarIcon className={cn(pinned && "fill-current")} aria-hidden />
|
||||
</SidebarMenuAction>
|
||||
</SidebarMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Навигация общего макета v2 (как в EvoBGP): поиск ⌘K, «Закреплённые», сворачиваемые группы,
|
||||
* точки проблем у разделов.
|
||||
*/
|
||||
export function NavMain({ groups }: { groups: NavGroup[] }) {
|
||||
const [pins, setPins] = useState<string[]>([])
|
||||
const [closed, setClosed] = useState<string[]>([])
|
||||
useEffect(() => {
|
||||
queueMicrotask(() => {
|
||||
setPins(readList(PINS_KEY))
|
||||
setClosed(readList(CLOSED_KEY))
|
||||
})
|
||||
}, [])
|
||||
|
||||
const items = groups.flatMap((g) => g.items)
|
||||
const pinned = pins.map((url) => items.find((i) => i.url === url)).filter((i): i is NavItem => Boolean(i))
|
||||
const togglePin = (url: string) => setPins((prev) => {
|
||||
const next = prev.includes(url) ? prev.filter((u) => u !== url) : [...prev, url]
|
||||
writeList(PINS_KEY, next)
|
||||
return next
|
||||
})
|
||||
const toggleGroup = (label: string) => setClosed((prev) => {
|
||||
const next = prev.includes(label) ? prev.filter((l) => l !== label) : [...prev, label]
|
||||
writeList(CLOSED_KEY, next)
|
||||
return next
|
||||
})
|
||||
|
||||
return (
|
||||
<nav aria-label="Основная навигация">
|
||||
{groups.map((group) => (
|
||||
<SidebarGroup key={group.label}>
|
||||
<SidebarGroupLabel>{group.label}</SidebarGroupLabel>
|
||||
<SidebarMenu>
|
||||
{group.items.map((item) => (
|
||||
<SidebarMenuItem key={item.title}>
|
||||
<SidebarMenuButton
|
||||
isActive={pathname === item.url}
|
||||
tooltip={item.title}
|
||||
render={<Link href={item.url} aria-current={pathname === item.url ? "page" : undefined} onNavigate={() => setOpenMobile(false)} />}
|
||||
>
|
||||
{item.icon}
|
||||
<span>{item.title}</span>
|
||||
{item.badge != null && item.badge !== "" && (
|
||||
<span className="ml-auto text-[10.5px] font-mono tabular-nums text-sidebar-foreground/50 group-data-[collapsible=icon]:hidden">
|
||||
{item.badge}
|
||||
</span>
|
||||
)}
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
<nav aria-label="Основная навигация" className="flex flex-col">
|
||||
<SidebarGroup className="pb-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
tooltip="Поиск и команды"
|
||||
onClick={openCommandPalette}
|
||||
className="border-sidebar-border text-sidebar-foreground/70 border"
|
||||
>
|
||||
<SearchIcon aria-hidden />
|
||||
<span>Поиск и команды</span>
|
||||
<Kbd className="ml-auto group-data-[collapsible=icon]:hidden">⌘K</Kbd>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
|
||||
{pinned.length > 0 ? (
|
||||
<SidebarGroup className="py-0 group-data-[collapsible=icon]:hidden">
|
||||
<SidebarGroupLabel className="text-xs font-semibold tracking-wide uppercase">Закреплённые</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu className="gap-px">
|
||||
{pinned.map((item) => <NavEntry key={item.url} item={item} pinned onTogglePin={() => togglePin(item.url)} />)}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
))}
|
||||
) : null}
|
||||
|
||||
{groups.map((group, gi) => {
|
||||
const isClosed = closed.includes(group.label)
|
||||
return (
|
||||
<div key={group.label} className="flex flex-col">
|
||||
{gi > 0 ? <SidebarSeparator className="mx-2 my-1 hidden h-px shrink-0 group-data-[collapsible=icon]:block" /> : null}
|
||||
<SidebarGroup className="py-0">
|
||||
<SidebarGroupLabel
|
||||
render={<button type="button" aria-expanded={!isClosed} onClick={() => toggleGroup(group.label)} />}
|
||||
className="h-7 cursor-pointer justify-between text-xs font-semibold tracking-wide uppercase"
|
||||
>
|
||||
{group.label}
|
||||
<ChevronDownIcon className={cn("size-3.5 transition-transform", isClosed && "-rotate-90")} aria-hidden />
|
||||
</SidebarGroupLabel>
|
||||
<SidebarGroupContent className={cn(isClosed && "hidden group-data-[collapsible=icon]:block")}>
|
||||
<SidebarMenu className="gap-px">
|
||||
{group.items.map((item) => (
|
||||
<NavEntry key={item.url} item={item} pinned={pins.includes(item.url)} onTogglePin={() => togglePin(item.url)} />
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -1,51 +1,51 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useRef } from "react"
|
||||
import { InfoIcon } from "lucide-react"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { InfoIcon, LockIcon, UsersIcon } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
|
||||
|
||||
const STATUS = [["var(--success)", "Онлайн"], ["var(--warning)", "Внимание"], ["var(--destructive)", "Оффлайн"], ["var(--muted-foreground)", "Неизвестно"]] as const
|
||||
const ROLES = [["HR", "Home Router", "var(--chart-2)"], ["JH", "JumpHost", "var(--chart-1)"], ["EN", "Exit Node", "var(--chart-3)"], ["IX", "IX Node", "var(--chart-4)"]] as const
|
||||
|
||||
/** Легенда карты макета v3: статус, роли узлов, виды связей и что значат подписи. */
|
||||
export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
||||
const details = useRef<HTMLDetailsElement>(null)
|
||||
useEffect(() => {
|
||||
if (compact && details.current) details.current.open = false
|
||||
}, [compact])
|
||||
const head = "text-muted-foreground mt-1 text-[11px] font-semibold tracking-wider uppercase"
|
||||
return (
|
||||
<details ref={details} data-map-legend className="relative">
|
||||
<summary className="border-border/60 text-muted-foreground hover:text-foreground flex h-7 cursor-pointer list-none items-center gap-1.5 rounded-md border px-2.5 text-xs transition-colors focus-visible:outline-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
|
||||
<InfoIcon aria-hidden="true" className="size-3.5" />Легенда
|
||||
</summary>
|
||||
<div role="region" aria-label="Легенда карты" className="bg-popover text-popover-foreground absolute top-full right-0 z-30 mt-1 max-sm:fixed max-sm:inset-x-4 max-sm:top-auto max-sm:w-auto flex max-h-[60vh] w-56 max-w-[calc(100vw-2rem)] flex-col gap-2 overflow-y-auto rounded-lg border px-3 py-2 text-xs shadow-md">
|
||||
<div>
|
||||
<p className="mb-1.5 font-medium text-muted-foreground">Статус устройства</p>
|
||||
<div className="grid grid-cols-2 gap-x-2 gap-y-1.5">
|
||||
{[["var(--status-online)", "Онлайн"], ["var(--status-degraded)", "Внимание"], ["var(--status-offline)", "Оффлайн"], ["var(--muted-foreground)", "Неизвестно"]].map(([color, label]) => (
|
||||
<span key={label} className="flex items-center gap-1.5"><span aria-hidden className="size-2 shrink-0 rounded-full" style={{ background: color }} />{label}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="font-medium text-muted-foreground">Тип узла</p>
|
||||
{[["JH", "JumpHost", "var(--chart-1)"], ["EN", "Exit Node", "var(--chart-3)"], ["HR", "Home Router", "var(--chart-2)"], ["IX", "IX Node", "var(--chart-4)"]].map(([label, name, color]) => (
|
||||
<span key={label} className="flex items-center gap-2"><Badge variant="secondary" style={{ color }} className="min-w-8 justify-center text-xs">{label}</Badge><span>{name}</span></span>
|
||||
<Popover key={compact ? "compact" : "overview"}>
|
||||
<PopoverTrigger render={<Button type="button" variant="outline" className="text-[13px]" />}>
|
||||
<InfoIcon aria-hidden="true" className="size-4" />Легенда
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" role="region" aria-label="Легенда карты" className="max-h-[min(60vh,var(--available-height))] w-[310px] max-w-[calc(100vw-2rem)] gap-2 overflow-y-auto border p-3 text-xs">
|
||||
<p className={head}>Статус</p>
|
||||
<div className="grid grid-cols-2 gap-x-2.5 gap-y-1.5">
|
||||
{STATUS.map(([color, label]) => (
|
||||
<span key={label} className="flex items-center gap-2"><span aria-hidden className="size-2 shrink-0 rounded-full" style={{ background: color }} />{label}</span>
|
||||
))}
|
||||
<span className="flex items-center gap-2"><span aria-hidden className="mx-1 size-3 rounded-full border border-current" />WAN · аплинк</span>
|
||||
<span className="flex items-center gap-2"><span aria-hidden className="mx-1 size-3 rounded border border-current" />Сервис / страна</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="font-medium text-muted-foreground">Связи и измерения</p>
|
||||
{[
|
||||
["GRE", "var(--status-online)", undefined],
|
||||
["GRE + IPsec", "var(--status-online)", "7 4"],
|
||||
["Поток NetFlow", "var(--chart-4)", "6 5"],
|
||||
["WAN → JH · модель", "var(--muted-foreground)", "5 4"],
|
||||
].map(([label, color, dash]) => (
|
||||
<span key={label} className="flex items-center gap-2"><svg aria-hidden width="28" height="12" className="shrink-0"><line x1="0" y1="6" x2="28" y2="6" stroke={color} strokeWidth="2" strokeDasharray={dash} /></svg>{label}</span>
|
||||
<p className={head}>Узлы</p>
|
||||
<div className="grid grid-cols-2 gap-x-2.5 gap-y-1.5">
|
||||
{ROLES.map(([label, name, color]) => (
|
||||
<span key={label} className="flex items-center gap-2">
|
||||
<b className="bg-muted inline-flex h-[18px] w-7 items-center justify-center rounded-[5px] font-mono text-[10.5px] font-semibold" style={{ color }}>{label}</b><span>{name}</span>
|
||||
</span>
|
||||
))}
|
||||
<p className="text-muted-foreground">RTT · задержка пробы. «—» · нет измерения.</p>
|
||||
<p className="text-muted-foreground">NetFlow · трафик за 5 минут, не пропускная способность канала.</p>
|
||||
<p className="text-muted-foreground">Live GRE · текущие RX/TX в деталях туннеля.</p>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="28" height="16" viewBox="0 0 28 16"><rect x="1" y="2" width="26" height="12" rx="6" fill="none" stroke="var(--muted-foreground)" strokeWidth="1.5" /></svg>WAN-аплинк</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="28" height="16" viewBox="0 0 28 16"><rect x="1" y="2" width="26" height="12" rx="3" fill="none" stroke="var(--muted-foreground)" strokeWidth="1.5" /></svg>Сервис / страна</span>
|
||||
<span className="flex items-center gap-2"><UsersIcon aria-hidden className="size-4" />Пользователи</span>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
<p className={head}>Связи</p>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--success)" strokeWidth="3" /></svg>GRE-туннель</span>
|
||||
<span className="flex items-center gap-2"><LockIcon aria-hidden className="mx-2 size-4" />GRE + IPsec</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--destructive)" strokeWidth="3" /></svg>GRE · нет связи</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeWidth="2" /></svg>Home Router → аплинк</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="10" viewBox="0 0 32 10"><line x1="0" y1="5" x2="32" y2="5" stroke="var(--muted-foreground)" strokeOpacity=".5" strokeWidth="2" /></svg>WAN → JH · модель связности</span>
|
||||
<span className="flex items-center gap-2"><svg aria-hidden width="32" height="12" viewBox="0 0 32 12"><path d="M0 3 C16 3 16 9 32 9" fill="none" stroke="var(--chart-4)" strokeWidth="2" /></svg>Связь с сервисом</span>
|
||||
<span className="flex items-center gap-2"><Badge variant="outline" size="xs">IPFIX</Badge>Наблюдение экспортёра · выход не подтверждён</span>
|
||||
</div>
|
||||
<p className="text-muted-foreground leading-snug">Подпись линии GRE показывает последний замер RX/TX интерфейса RouterOS. Скорость сервиса и знак «≈» показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, type ReactNode } from "react"
|
||||
import Link from "next/link"
|
||||
import { ChevronRightIcon, XIcon } from "lucide-react"
|
||||
import type { FlowAnalyticsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath, FlowMapUser, FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
|
||||
import { flowMapHopsDtoSchema } from "@mmapp/contracts/traffic-flow"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Sparkline } from "@/components/sparkline"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { formatBytes, fmtRate } from "@/lib/fmt-rate"
|
||||
import { formatNetflowRate } from "@/lib/map-netflow-hops"
|
||||
import { servicePathKey } from "@/lib/format-service-path-label"
|
||||
import { projectTrafficObservations } from "@/lib/traffic-observations"
|
||||
import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
import { matchesMapService } from "@/lib/flow-map-service-match"
|
||||
|
||||
const evidenceLabel: Record<FlowServiceBasis, string> = {
|
||||
catalog: "По каталогу",
|
||||
network: "По IP / ASN",
|
||||
port: "По протоколу / порту",
|
||||
heuristic: "Оценка по сети и порту",
|
||||
unknown: "Сервис не определён",
|
||||
}
|
||||
const percent = new Intl.NumberFormat("ru-RU", {style: "percent", maximumFractionDigits: 1})
|
||||
|
||||
export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][] }) {
|
||||
return <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-t-lg border-b bg-border">
|
||||
{rows.map(([name, value, title]) => <div key={name} title={title} className="flex min-w-0 flex-col gap-0.5 bg-card px-3.5 py-2.5">
|
||||
<dt className="text-[11px] text-muted-foreground">{name}</dt>
|
||||
<dd className="font-mono text-sm font-semibold leading-tight [overflow-wrap:anywhere]">{value}</dd>
|
||||
</div>)}
|
||||
</dl>
|
||||
}
|
||||
|
||||
export function serviceUsers(service: FlowMapService, paths: FlowMapServicePath[]): FlowMapUser[] {
|
||||
const users = new Map<string, FlowMapUser>()
|
||||
function add(clientId: string, clientName: string, bytes: number, bps: number) {
|
||||
const user = users.get(clientId) ?? { clientId, clientName, bytes: 0, bps: 0 }
|
||||
user.bytes += bytes
|
||||
user.bps += bps
|
||||
users.set(clientId, user)
|
||||
}
|
||||
let attributedBytes = 0
|
||||
for (const p of paths) {
|
||||
add(p.clientId, p.clientName, p.bytes, p.bps)
|
||||
attributedBytes += p.bytes
|
||||
}
|
||||
if (service.bytes > attributedBytes) {
|
||||
const bytes = service.bytes - attributedBytes
|
||||
add("—", "—", bytes, service.bps * bytes / service.bytes)
|
||||
}
|
||||
return [...users.values()]
|
||||
}
|
||||
|
||||
export function InspectorUsers({ users, windowLabel }: { users?: FlowMapUser[]; windowLabel: string }) {
|
||||
const ranked = [...(users ?? [])].sort((a, b) => b.bytes - a.bytes || a.clientName.localeCompare(b.clientName))
|
||||
const total = ranked.reduce((sum, user) => sum + user.bytes, 0)
|
||||
return <section aria-label="Трафик по пользователям" title="Сохранённые потоки NetFlow и привязки интерфейсов. Узел может быть определён по наблюдаемому GRE-соседу." className="space-y-2 border-b px-3.5 py-3">
|
||||
<h3 className="flex justify-between gap-2 font-mono text-[11px] text-muted-foreground">
|
||||
<span>Пользователи</span><span>NetFlow · {windowLabel}</span>
|
||||
</h3>
|
||||
{!ranked.length && <p className="text-xs text-muted-foreground">{users ? "Нет сохранённых потоков в этом интервале" : "Разбивка в этом снимке недоступна"}</p>}
|
||||
{ranked.length > 0 && <ul className="max-h-52 space-y-2 overflow-y-auto">
|
||||
{ranked.map(user => <li key={user.clientId} className="flex items-start justify-between gap-2 text-xs">
|
||||
<span className="min-w-0 font-medium [overflow-wrap:anywhere]">{user.clientId === "—" ? "Без привязки к пользователю" : user.clientName}</span>
|
||||
<span className="shrink-0 text-right font-mono tabular-nums">
|
||||
{formatNetflowRate(user)}
|
||||
<span className="block text-[10px] text-muted-foreground">{formatBytes(user.bytes)}{total > 0 && ` · ${Math.round(user.bytes / total * 100)}%`}</span>
|
||||
</span>
|
||||
</li>)}
|
||||
</ul>}
|
||||
</section>
|
||||
}
|
||||
|
||||
export function NodeHistory({ base, id, refresh, degraded }: { base: string | null; id: string; refresh: number; degraded: boolean }) {
|
||||
const [sample, setSample] = useState<ReturnType<typeof projectTrafficObservations> | null>(null)
|
||||
const [unavailable, setUnavailable] = useState(false)
|
||||
useEffect(() => {
|
||||
if (base === null) return
|
||||
const controller = new AbortController()
|
||||
void requestJson<{ server?: { id?: string } }>(base, `/api/traffic/servers/${encodeURIComponent(id)}?range=24h`, { signal: controller.signal })
|
||||
.then(raw => {
|
||||
if (raw?.server?.id !== id) throw new Error("Не подтверждён сервер")
|
||||
const observations = projectTrafficObservations(raw.server)
|
||||
if (!controller.signal.aborted) { setSample(observations); setUnavailable(false) }
|
||||
})
|
||||
.catch(() => { if (!controller.signal.aborted) { setSample(null); setUnavailable(true) } })
|
||||
return () => controller.abort()
|
||||
}, [base, id, refresh])
|
||||
const points = sample?.rxSeries.map((rx, i) => {
|
||||
const tx = sample.txSeries[i]
|
||||
return rx != null && tx != null ? rx + tx : null
|
||||
}) ?? []
|
||||
const measured = points.filter((n): n is number => n !== null)
|
||||
const peak = measured.length ? Math.max(...measured) : null
|
||||
const obs = sample?.observations
|
||||
const warning = obs?.currentState === "error" ? obs.error : null
|
||||
return <>
|
||||
{(warning || degraded) && <div className="border-b px-3 py-2"><div className="rounded-md border border-warning/30 bg-warning/10 px-2.5 py-2 text-xs text-warning-foreground [overflow-wrap:anywhere]">
|
||||
{warning ? <>Сбор трафика{obs?.lastAttemptAt ? " · " + new Date(obs.lastAttemptAt).toLocaleString("ru-RU") : ""}. {warning}</> : "Последний опрос устройства вернул статус «Внимание»."}
|
||||
</div></div>}
|
||||
<section aria-label="История трафика устройства" title="Сумма RX и TX по сохранённым счётчикам интерфейсов за последние 24 часа" className="border-b px-3.5 py-3">
|
||||
<div className="flex justify-between gap-2 text-[11px] text-muted-foreground"><span>Трафик · 24 ч</span><span className="font-mono">{peak !== null ? "пик " + fmtRate(peak) : "—"}</span></div>
|
||||
{peak !== null ? <><div className="my-2 [&_svg]:h-12 [&_svg]:w-full"><Sparkline data={points} width={244} height={48} filled color="var(--chart-1)" /></div>
|
||||
<div className="flex justify-between font-mono text-[10px] text-muted-foreground"><span>−24 ч</span><span>−12 ч</span><span>конец окна</span></div></>
|
||||
: <p className="py-3 text-xs text-muted-foreground">{base !== null && !sample && !unavailable ? "Загрузка истории…" : "Нет подтверждённых измерений RX и TX"}</p>}
|
||||
</section>
|
||||
</>
|
||||
}
|
||||
|
||||
export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, flowAt, stale, activePath, onPath, onClose, filtered, onFilter, userId, ix, topology }: {
|
||||
service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string
|
||||
country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean
|
||||
activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void
|
||||
onClose: () => void; filtered: boolean; onFilter: () => void
|
||||
userId?: string; ix?: boolean; topology?: ReadonlySet<string>
|
||||
}) {
|
||||
const [recent, setRecent] = useState<{ data: FlowAnalyticsDto; at: string } | null>(null)
|
||||
const [volume, setVolume] = useState<{ bytes: number | null; window: string; at: string } | null>(null)
|
||||
const canMatchService = !service.id.endsWith("svc:other") && service.label !== "Прочее"
|
||||
const sources = [...new Set(paths.map(path => path.viaId).filter(id => /^[1-9]\d*$/.test(id)))].sort()
|
||||
const exporter = sources.length === 1 && /^[1-9]\d*$/.test(sources[0]) ? sources[0] : undefined
|
||||
const scopedUser = userId && !userId.startsWith("ix:") ? userId : undefined
|
||||
const scoped = Boolean(userId || topology)
|
||||
useEffect(() => {
|
||||
if (base === null) return
|
||||
const controller = new AbortController()
|
||||
const init = { signal: controller.signal }
|
||||
if (canMatchService && (!scoped || scopedUser || exporter && !userId)) void getFlowAnalytics(base, { range: "5m", userId: scopedUser, serverId: !scopedUser && scoped ? exporter : undefined }, init)
|
||||
.then(data => { if (!controller.signal.aborted) setRecent({data, at: new Date().toISOString()}) })
|
||||
.catch(() => { if (!controller.signal.aborted) setRecent(null) })
|
||||
if (!scoped) void getFlowMapHops(base, { range: "24h" }, init)
|
||||
.then(raw => {
|
||||
if (controller.signal.aborted) return
|
||||
const data = flowMapHopsDtoSchema.parse(raw)
|
||||
const minutes = data.sourceWindow?.effectiveMinutes ?? 1440
|
||||
if (data.rangeMinutes !== minutes || data.windowSec !== minutes * 60 || data.sourceWindow && data.sourceWindow.requestedMinutes !== 1440) throw new Error("Не подтверждено окно объёма")
|
||||
const services = country ? data.countryServiceGroups?.find(g => g.countryId === service.id.split("|")[0])?.services : data.services
|
||||
setVolume({bytes: services?.find(row => row.id === service.id)?.bytes ?? null,
|
||||
window: data.sourceWindow ? minutes + " мин" : "24 ч", at: new Date().toISOString()})
|
||||
})
|
||||
.catch(() => { if (!controller.signal.aborted) setVolume(null) })
|
||||
return () => controller.abort()
|
||||
}, [base, refresh, country, service.id, canMatchService, scoped, scopedUser, exporter, userId])
|
||||
const countryFilter = service.id.startsWith("cc:other|") ? "unknown" : country
|
||||
const flows = recent?.data.conversationsList.filter(row => (!topology || topology.has(row.enId || row.serverId)) && matchesMapService(row, service.label, countryFilter))
|
||||
.sort((a, b) => b.bps - a.bps).slice(0, 5) ?? []
|
||||
const asns = [...new Set(flows.flatMap(flow => flow.dstAsn ? [flow.dstAsn] : []))]
|
||||
const rates = [...exits].sort((a, b) => b.bps - a.bps)
|
||||
const exitIds = [...new Set([...rates.filter(e => !e.observedOnly).map(e => e.fromId), ...paths.map(p => p.enId).filter(Boolean)])]
|
||||
const exporterIds = [...new Set([...rates.filter(e => e.observedOnly).map(e => e.fromId), ...paths.filter(p => !p.enId).map(p => p.viaId)])]
|
||||
const attributedBytes = (country ? paths : exits).reduce((sum, entry) => sum + entry.bytes, 0)
|
||||
const remainder = Math.max(0, service.bytes - attributedBytes)
|
||||
const observed = service.bytes > 0 && !stale
|
||||
const currentVolume = base === null || scoped
|
||||
const trafficTypes = service.trafficTypes ?? []
|
||||
const serviceEvidence = service.serviceEvidence ?? []
|
||||
const otherTypeBytes = Math.max(0, service.bytes - trafficTypes.reduce((sum, row) => sum + row.bytes, 0))
|
||||
const typeShare = (bytes: number) => percent.format(Math.min(1, bytes / service.bytes))
|
||||
const trafficQuery = new URLSearchParams({ view: "flows", service: service.label, serviceId: service.id, from: "map" })
|
||||
if (scopedUser) trafficQuery.set("user", scopedUser)
|
||||
else if (exporter) trafficQuery.set("server", exporter)
|
||||
if (userId?.startsWith("ix:")) trafficQuery.set("mapUser", userId)
|
||||
if (ix) trafficQuery.set("mapView", "ix")
|
||||
if (topology) {
|
||||
if (!scopedUser) trafficQuery.set("exporters", sources.join(","))
|
||||
trafficQuery.set("nodes", [...topology].filter(id => /^[1-9]\d*$/.test(id)).join(","))
|
||||
}
|
||||
if (countryFilter) trafficQuery.set("country", countryFilter)
|
||||
return <>
|
||||
<header className="flex items-center gap-2 px-3 py-3">
|
||||
<div className="grid size-8 shrink-0 place-items-center rounded-md bg-muted"><ServiceBrandIcon label={service.label} size={18} /></div>
|
||||
<div className="min-w-0 flex-1"><h2 className="truncate text-sm font-semibold" title={service.label}>{service.label}</h2>
|
||||
<p className="truncate text-[11px] text-muted-foreground" title={flowAt ? new Date(flowAt).toLocaleString("ru-RU") : undefined}>{[service.category, asns.length === 1 ? "AS" + asns[0] : null, country, windowLabel].filter(Boolean).join(" · ")}</p></div>
|
||||
<Badge size="sm" variant={observed ? "success-light" : "secondary"} title="Наличие трафика в окне NetFlow"><span aria-hidden>•</span>{stale ? "Архив" : observed ? "Есть трафик" : "Нет трафика"}</Badge>
|
||||
<Button size="icon-xs" variant="ghost" aria-label="Закрыть детали назначения" onClick={onClose}><XIcon /></Button>
|
||||
</header>
|
||||
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
|
||||
<InspectorMetrics rows={[
|
||||
["Средняя скорость IPFIX", formatNetflowRate({ bps: service.bps }), "Сохранённые потоки за " + windowLabel],
|
||||
[country ? "Доля страны" : "Доля трафика", percent.format(service.share)],
|
||||
["Объём · " + (currentVolume ? windowLabel : volume?.window ?? "24 ч"), <>{currentVolume ? formatBytes(service.bytes) : volume?.bytes == null ? "—" : formatBytes(volume.bytes)}{volume && <time dateTime={volume.at} title={new Date(volume.at).toLocaleString("ru-RU")} className="block text-[10px] font-normal text-muted-foreground">ответ {new Date(volume.at).toLocaleTimeString("ru-RU")}</time>}</>],
|
||||
exitIds.length || !exporterIds.length
|
||||
? ["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder || exporterIds.length ? "Часть трафика без подтверждённого выхода" : undefined]
|
||||
: ["Экспортёр", exporterIds.map(exitName).join(", "), "Наблюдение IPFIX, дальнейший маршрут не подтверждён"],
|
||||
]} />
|
||||
{trafficTypes.length > 0 && service.bytes > 0 && <section className="space-y-2 border-b px-3.5 py-3 text-xs" aria-label="Состав трафика IPFIX">
|
||||
<h3 className="flex justify-between gap-2 font-medium"><span>Состав трафика</span><span className="font-normal text-muted-foreground">IPFIX · {windowLabel}</span></h3>
|
||||
<dl className="space-y-1">
|
||||
{trafficTypes.map(({transport, application, bytes}) => <div key={JSON.stringify([transport, application])} className="flex justify-between gap-2">
|
||||
<dt>{application ? `${application} · ${transport}` : transport}</dt>
|
||||
<dd className="shrink-0 font-mono tabular-nums">{typeShare(bytes)}</dd>
|
||||
</div>)}
|
||||
{otherTypeBytes > 0 && <div className="flex justify-between gap-2"><dt>Остальные типы</dt><dd className="font-mono tabular-nums">{typeShare(otherTypeBytes)}</dd></div>}
|
||||
</dl>
|
||||
{trafficTypes.some(row => row.application) && <p className="text-muted-foreground">Приложения определены по портам.</p>}
|
||||
{service.lastBucketAt && <p className="text-muted-foreground">Последняя минута с потоками <time dateTime={service.lastBucketAt} className="font-mono">{new Date(service.lastBucketAt).toLocaleTimeString("ru-RU", {hour: "2-digit", minute: "2-digit"})}</time></p>}
|
||||
{serviceEvidence.length ? <ul aria-label="Основание классификации" className="flex flex-wrap gap-1">
|
||||
{serviceEvidence.map(row => <li key={row.basis}>
|
||||
<Badge size="sm" variant={row.basis === "heuristic" ? "info-light" : "secondary"}
|
||||
title={row.basis === "heuristic" ? "Сервис предполагается по сети назначения и порту 443" : undefined}>
|
||||
{evidenceLabel[row.basis]}{serviceEvidence.length > 1 && ` · ${typeShare(row.bytes)}`}
|
||||
</Badge>
|
||||
</li>)}
|
||||
</ul> : null}
|
||||
</section>}
|
||||
<InspectorUsers users={serviceUsers(service, paths)} windowLabel={windowLabel} />
|
||||
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3>
|
||||
{paths.map(p => {
|
||||
const parts = [p.clientName !== "—" ? p.clientName : "", p.viaId !== p.enId ? p.viaName : "",
|
||||
p.enName, service.label].filter(Boolean)
|
||||
const key = servicePathKey(p)
|
||||
const active = activePath && servicePathKey(activePath) === key
|
||||
return <button type="button" key={key} onClick={() => onPath(p)} aria-pressed={Boolean(active)} title={formatNetflowRate(p)} className={cn("flex w-full flex-wrap items-center gap-1 rounded-sm text-left", active && "ring-1 ring-primary")}>
|
||||
{parts.map((name, i) => <span key={i} className="inline-flex max-w-full items-center gap-1">{i > 0 && <ChevronRightIcon aria-hidden className="size-3 shrink-0 text-muted-foreground" />}<span className={cn("truncate rounded-md bg-muted px-1.5 py-1 font-mono text-[10px] font-semibold", i === parts.length - 1 && "bg-chart-4/20")}>{name}</span></span>)}
|
||||
{!p.enId && <span className="basis-full text-[10px] text-muted-foreground">
|
||||
Наблюдение IPFIX{p.viaIface ? ` · интерфейс ${p.viaIface}` : ""} · выход не подтверждён
|
||||
</span>}
|
||||
</button>
|
||||
})}
|
||||
{rates.filter(e => !paths.some(p => (p.enId || p.viaId) === e.fromId && Boolean(p.enId) !== Boolean(e.observedOnly))).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}{e.observedOnly && " · наблюдение IPFIX"}</span><span className="shrink-0 font-mono">{formatNetflowRate(e)}</span></div>)}
|
||||
{remainder > 0 && <div className="flex justify-between gap-2 text-xs text-muted-foreground"><span>Выход не определён</span><span className="font-mono">{formatNetflowRate({bps:service.bps * remainder / service.bytes})}</span></div>}
|
||||
{!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>}
|
||||
</section>
|
||||
<section className="space-y-3 border-b px-3.5 py-3"><h3 className="flex items-center justify-between font-mono text-[11px] text-muted-foreground"><span>Крупные потоки · {recent?.data.sourceWindow?.effectiveMinutes ?? 5} мин</span><span title="Наблюдения экспортёров">{recent ? flows.length : "—"}</span></h3>
|
||||
{flows.map((f,i) => {
|
||||
const port = f.internetPeerPort || f.dstPort
|
||||
const transport = port ? `${f.protoName}/${port}` : f.protoName
|
||||
return <div key={i} className="flex items-center gap-2 text-xs">
|
||||
<span aria-hidden className="size-1.5 shrink-0 rounded-full bg-[var(--status-online)]" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="font-medium [overflow-wrap:anywhere]">{f.src} → {f.dst}</p>
|
||||
<p className="truncate text-[11px] text-muted-foreground" title={`Экспортёр: ${f.serverName || f.serverId}`}>
|
||||
{transport}{f.application && f.application !== transport && f.application !== f.protoName && ` · ${f.application}`} · {f.serverName || f.serverId}
|
||||
</p>
|
||||
</div>
|
||||
<span className="font-mono text-[11px] text-muted-foreground">{formatNetflowRate({bps:f.bps})}</span>
|
||||
</div>
|
||||
})}
|
||||
{!flows.length && <p className="text-xs text-muted-foreground">{recent ? "Сервис отсутствует в выборке крупных потоков" : "Нет подтверждённых записей"}</p>}
|
||||
{recent && <time dateTime={recent.at} title={new Date(recent.at).toLocaleString("ru-RU")} className="block font-mono text-[10px] text-muted-foreground">ответ {new Date(recent.at).toLocaleTimeString("ru-RU")}</time>}
|
||||
</section>
|
||||
<div className="flex flex-wrap gap-1.5 px-3.5 py-3">
|
||||
<Link href={`/traffic?${trafficQuery}`} className={buttonVariants({size:"xs"})}>Открыть в «Трафике»</Link>
|
||||
<Button size="xs" variant="outline" aria-pressed={filtered} onClick={onFilter}>{filtered ? "Снять фильтр" : "Фильтр по сервису"}</Button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
"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<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 || !userId || userId.startsWith("ix:")) return
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
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<string, AccessRate>()
|
||||
let userRate: ReturnType<typeof projectTrafficObservations> | 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<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,
|
||||
userRate,
|
||||
}
|
||||
}
|
||||
|
||||
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, 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 <CommandDialog open={open} onOpenChange={onOpenChange} showCloseButton title="Выбор пользователя" description="Поиск по имени, логину, узлу или интерфейсу">
|
||||
<Command>
|
||||
<div className="flex flex-col gap-1 px-3 pt-3 pb-2">
|
||||
<p className="pr-8 text-sm font-semibold">Кого показать на карте?</p>
|
||||
<p className="text-xs text-muted-foreground">Выберите пользователя, чтобы увидеть его подключения и сервисы.</p>
|
||||
</div>
|
||||
<CommandInput aria-label="Поиск пользователей" placeholder="Имя, логин, узел или интерфейс…" />
|
||||
<CommandList>
|
||||
<CommandEmpty>{pending ? "Загрузка пользователей…" : unavailable ? "Каталог пользователей недоступен" : "Пользователи не найдены"}</CommandEmpty>
|
||||
{selectedUser && <CommandItem value="all-network" keywords={["Вся схема", "Сбросить пользователя"]} onSelect={onClear}>Вся схема</CommandItem>}
|
||||
<CommandGroup heading={ordered.length ? `Пользователи · ${ordered.length}` : undefined}>
|
||||
{ordered.map(user => {
|
||||
const nodes = [...new Set(user.bindings.map(binding => nodeName(binding.node)))].sort()
|
||||
return <CommandItem key={user.id} value={user.id} keywords={[user.name, user.login ?? "", ...nodes, ...user.bindings.map(binding => binding.name)]} onSelect={() => onPick(user)}>
|
||||
<UsersIcon aria-hidden /><span className="grid min-w-0 flex-1 gap-0.5">
|
||||
<span className="truncate font-medium">{user.name}</span>
|
||||
<span className="truncate text-xs text-muted-foreground" title={nodes.join(", ")}>{[user.login !== user.name && user.login, ...nodes].filter(Boolean).join(" · ")}</span>
|
||||
</span>
|
||||
{selectedUser?.id === user.id ? <Badge variant="secondary" size="sm">На карте</Badge> : <Badge variant="outline" size="sm" title="Привязки интерфейсов">{user.bindings.length} инт.</Badge>}
|
||||
</CommandItem>
|
||||
})}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
<p className="px-3 py-2 text-xs text-muted-foreground">↑ ↓ выбор · Enter открыть · Esc закрыть</p>
|
||||
</Command>
|
||||
</CommandDialog>
|
||||
}
|
||||
|
||||
export function MapUserDetails({ user, groups, paths, services, rates, userRate, windowLabel, onClose, onService, nodeName, trafficHref }: {
|
||||
user: MapAccessUser; groups: Map<string, AccessBinding[]>; paths: FlowMapServicePath[]; services: FlowMapService[]; rates?: Map<string, AccessRate>; windowLabel: string
|
||||
userRate?: ReturnType<typeof projectTrafficObservations>
|
||||
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">
|
||||
{!user.linux && <section className="grid gap-1 text-xs" aria-label="Трафик пользователя">
|
||||
<h3 className="text-muted-foreground">Счётчики подключений · RouterOS</h3>
|
||||
<p className="font-mono">RX {fmtRate(userRate?.rxNow ?? null)} · TX {fmtRate(userRate?.txNow ?? null)}</p>
|
||||
{userRate?.observations?.sampledAt && (userRate.rxNow !== null || userRate.txNow !== null) && <time className="text-muted-foreground" dateTime={userRate.observations.sampledAt}>{new Date(userRate.observations.sampledAt).toLocaleTimeString("ru-RU")}</time>}
|
||||
</section>}
|
||||
<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>}
|
||||
{!paths.length && user.bindings.some(binding => binding.peerScoped) && <p className="text-xs text-muted-foreground">Для привязки IPFIX к peer последний опрос RouterOS должен подтвердить, что на интерфейсе он один.</p>}
|
||||
</section>
|
||||
{trafficHref && <Link href={trafficHref} className={buttonVariants({size:"xs"})}>{user.linux ? "Открыть Linux-клиентов IX" : "Открыть в «Трафике»"}</Link>}
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
@@ -1,21 +1,23 @@
|
||||
"use client"
|
||||
|
||||
import type { ReactNode } from "react"
|
||||
import { useState, type ReactNode } from "react"
|
||||
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
import { FramePanel } from "@/components/reui/frame"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { SectionFrame, ToneBadge, ToneDot, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import { SectionFrame, ToneBadge, TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
export type MapFlowRow = { id: string; client: string; exit: string; dest: string; rate: string; volume: string; hl: boolean }
|
||||
export type MapRttRow = { id: string; name: string; route: string; rtt: string; speed: string; tone: Tone; status: string; hl: boolean }
|
||||
export type MapDestRow = { id: string; label: string; category: string; rate: string; share: number; hl: boolean }
|
||||
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string }
|
||||
export type MapEventRow = { id: string; ts: number; tone: Tone; label: string; title: string; message: string; serverId?: string }
|
||||
export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
|
||||
|
||||
function Table({ head, cols, empty, children }: { head: string[]; cols: string; empty: string | null; children: ReactNode }) {
|
||||
return (
|
||||
<div className="max-h-[420px] overflow-auto">
|
||||
<div className="max-h-[min(34svh,310px)] overflow-auto">
|
||||
<div className="min-w-[720px]">
|
||||
<div aria-hidden="true" className={cn("bg-muted/55 text-muted-foreground sticky top-0 z-[1] grid h-10 items-center gap-x-3 border-b px-4 text-xs font-medium", cols)}>
|
||||
{head.map((h) => <span key={h}>{h}</span>)}
|
||||
@@ -39,44 +41,53 @@ const EVENT_COLS = "grid-cols-[70px_110px_minmax(200px,1.4fr)_minmax(200px,2fr)]
|
||||
* Рабочая панель под картой (макет v3): потоки NetFlow, RTT каналов, назначения и события.
|
||||
* Строки выбранного объекта подсвечены.
|
||||
*/
|
||||
export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, eventsError, stat }: {
|
||||
export function MapBottomPanel({ tab, onTab, open, onOpenChange, flows, rtt, destinations, events, onEvent, onFlow, onDestination, eventsError, stat }: {
|
||||
tab: MapBottomTab
|
||||
onTab: (tab: MapBottomTab) => void
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
flows: MapFlowRow[]
|
||||
rtt: MapRttRow[]
|
||||
destinations: MapDestRow[]
|
||||
events: MapEventRow[]
|
||||
onEvent: (event: MapEventRow) => void
|
||||
onFlow: (id: string) => void
|
||||
onDestination: (id: string) => void
|
||||
eventsError: string | null
|
||||
stat: string
|
||||
}) {
|
||||
const [showRoutineEvents, setShowRoutineEvents] = useState(false)
|
||||
const incidentEvents = events.filter(event => event.tone === "er" || event.tone === "wn")
|
||||
const visibleEvents = showRoutineEvents ? events : incidentEvents
|
||||
const tabs: Array<{ id: MapBottomTab; label: string; count: number }> = [
|
||||
{ id: "flows", label: "Потоки NetFlow", count: flows.length },
|
||||
{ id: "rtt", label: "RTT каналов", count: rtt.length },
|
||||
{ id: "dest", label: "Назначения", count: destinations.length },
|
||||
{ id: "events", label: "События", count: events.length },
|
||||
{ id: "events", label: "События", count: visibleEvents.length },
|
||||
]
|
||||
return (
|
||||
<SectionFrame aria-label="Рабочая панель карты" bare>
|
||||
<Tabs value={tab} onValueChange={(value) => onTab(value as MapBottomTab)} className="gap-1">
|
||||
<div className="flex flex-wrap items-center gap-3 px-2 pt-1.5 pb-1">
|
||||
<TabsList aria-label="Рабочая панель">
|
||||
<SectionFrame aria-label="Рабочая панель карты" bare className="min-w-0 shrink-0">
|
||||
<Tabs value={tab} onValueChange={(value) => { onTab(value as MapBottomTab); onOpenChange(true) }} className="gap-1">
|
||||
<div className="flex min-w-0 items-center gap-2 px-2 py-1">
|
||||
<div className="min-w-0 flex-1 overflow-x-auto"><TabsList aria-label="Рабочая панель">
|
||||
{tabs.map((t) => (
|
||||
<TabsTrigger key={t.id} value={t.id} className="px-2.5">
|
||||
<TabsTrigger key={t.id} value={t.id} className="px-2.5" onClick={() => onOpenChange(true)}>
|
||||
{t.label}
|
||||
<Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge>
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
<span className="text-muted-foreground ml-auto text-xs">{stat}</span>
|
||||
</TabsList></div>
|
||||
{open && <span className="hidden text-xs text-muted-foreground xl:inline">{stat}</span>}
|
||||
<Button type="button" variant="ghost" size="icon-sm" aria-expanded={open} aria-controls="network-map-analysis" aria-label={open ? "Свернуть рабочую панель" : "Открыть рабочую панель"} onClick={() => onOpenChange(!open)}>{open ? <ChevronDownIcon /> : <ChevronUpIcon />}</Button>
|
||||
</div>
|
||||
<FramePanel className="p-0">
|
||||
<FramePanel id="network-map-analysis" hidden={!open} className="p-0">
|
||||
<TabsContent value="flows">
|
||||
<Table head={["Источник", "Exit", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
|
||||
<Table head={["Пользователь", "Выход / экспортёр", "Назначение", "Скорость", "Объём"]} cols={FLOW_COLS} empty={flows.length ? null : "NetFlow за окно не прислал потоков к назначениям"}>
|
||||
{flows.map((r) => (
|
||||
<Row key={r.id} cols={FLOW_COLS} hl={r.hl}>
|
||||
<span className="truncate font-mono">{r.client}</span>
|
||||
<span className="truncate font-mono">{r.exit}</span>
|
||||
<span className="truncate">{r.dest}</span>
|
||||
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onFlow(r.id)}><span className="truncate">{r.dest}</span></Button>
|
||||
<span className="font-mono tabular-nums">{r.rate}</span>
|
||||
<span className="text-muted-foreground font-mono tabular-nums">{r.volume}</span>
|
||||
</Row>
|
||||
@@ -100,7 +111,7 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, e
|
||||
<Table head={["Назначение", "Категория", "Скорость", "Доля окна"]} cols={DEST_COLS} empty={destinations.length ? null : "Назначений за окно нет"}>
|
||||
{destinations.map((r) => (
|
||||
<Row key={r.id} cols={DEST_COLS} hl={r.hl}>
|
||||
<span className="truncate font-medium">{r.label}</span>
|
||||
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onDestination(r.id)}><span className="truncate">{r.label}</span></Button>
|
||||
<span className="text-muted-foreground truncate">{r.category}</span>
|
||||
<span className="font-mono tabular-nums">{r.rate}</span>
|
||||
<span className="flex items-center gap-2">
|
||||
@@ -112,12 +123,17 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, e
|
||||
</Table>
|
||||
</TabsContent>
|
||||
<TabsContent value="events">
|
||||
<Table head={["Время", "Тип", "Событие", "Подробности"]} cols={EVENT_COLS} empty={eventsError ? `События недоступны: ${eventsError}` : events.length ? null : "Событий пока нет"}>
|
||||
{events.map((r) => (
|
||||
<div className="flex items-center gap-2 border-b px-3 py-1">
|
||||
<Button type="button" size="xs" variant={showRoutineEvents ? "outline" : "secondary"} aria-pressed={!showRoutineEvents} onClick={() => setShowRoutineEvents(false)}>Сбои и предупреждения</Button>
|
||||
<Button type="button" size="xs" variant={showRoutineEvents ? "secondary" : "outline"} aria-pressed={showRoutineEvents} onClick={() => setShowRoutineEvents(true)}>Все события</Button>
|
||||
</div>
|
||||
{eventsError && <p role="status" className="px-3 py-1 text-xs text-muted-foreground">{eventsError}</p>}
|
||||
<Table head={["Время", "Тип", "Событие", "Подробности"]} cols={EVENT_COLS} empty={visibleEvents.length ? null : eventsError ? "Нет подтверждённых событий" : showRoutineEvents ? "Событий пока нет" : "В полученных событиях нет сбоев и предупреждений"}>
|
||||
{visibleEvents.map((r) => (
|
||||
<Row key={r.id} cols={EVENT_COLS}>
|
||||
<time dateTime={new Date(r.ts).toISOString()} className="text-muted-foreground font-mono text-xs">{new Date(r.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</time>
|
||||
<span><ToneBadge tone={r.tone} mark={false}>{r.label}</ToneBadge></span>
|
||||
<span className="truncate font-medium">{r.title}</span>
|
||||
<Button type="button" variant="link" size="xs" className="min-w-0 justify-start" onClick={() => onEvent(r)}><span className="truncate">{r.title}</span></Button>
|
||||
<span className="text-muted-foreground truncate text-xs">{r.message}</span>
|
||||
</Row>
|
||||
))}
|
||||
@@ -133,31 +149,47 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, e
|
||||
* «Момент времени» (макет v3): инциденты за 24 часа на шкале и текущий Live-снимок.
|
||||
* Архив снимков карты не хранится, поэтому прошлые моменты не выбираются.
|
||||
*/
|
||||
export function MapTimeline({ events, now, onPick }: { events: MapEventRow[]; now: number; onPick: (event: MapEventRow) => void }) {
|
||||
export function MapTimeline({ events, now, state, onPick }: { events: MapEventRow[]; now: number; state?: string; onPick: (event: MapEventRow) => void }) {
|
||||
const from = now - 24 * 3_600_000
|
||||
const marks = events.filter((e) => e.ts >= from && e.ts <= now)
|
||||
const pos = (ts: number) => `calc(10px + (100% - 20px) * ${((ts - from) / (now - from)).toFixed(4)})`
|
||||
const hours = new Map<number, MapEventRow[]>()
|
||||
for (const event of events) {
|
||||
if (event.ts < from || event.ts > now || event.tone !== "er" && event.tone !== "wn") continue
|
||||
const hour = Math.min(23, Math.floor((event.ts - from) / 3_600_000))
|
||||
const group = hours.get(hour) ?? []
|
||||
group.push(event)
|
||||
hours.set(hour, group)
|
||||
}
|
||||
const at = (t: number) => `calc(10px + (100% - 20px) * ${t.toFixed(4)})`
|
||||
// Шкала макета v3: остановки (кружок и подпись под ним), инциденты — цветные засечки над линией.
|
||||
const stop = "absolute top-[7px] flex -translate-x-1/2 flex-col items-center gap-1 text-[11px] leading-none whitespace-nowrap"
|
||||
return (
|
||||
<div className="flex shrink-0 items-center gap-3 border-t px-3 py-2">
|
||||
<small className="text-muted-foreground text-xs whitespace-nowrap">Момент времени</small>
|
||||
<div role="group" aria-label="Инциденты карты за 24 часа" className="relative h-8 min-w-0 flex-1">
|
||||
<span aria-hidden="true" className="bg-border absolute inset-x-2.5 top-1/2 h-px" />
|
||||
{[0, 0.75, 0.9583].map((t, i) => (
|
||||
<span key={i} aria-hidden="true" className="text-muted-foreground absolute top-0 -translate-x-1/2 text-xs leading-none" style={{ left: `calc(10px + (100% - 20px) * ${t})` }}>{["−24 ч", "−6 ч", "−1 ч"][i]}</span>
|
||||
<div className="flex shrink-0 items-center gap-3 border-t px-3 pt-1.5 pb-1">
|
||||
<small className="flex flex-col text-xs text-muted-foreground" title={state}>Инциденты{state ? <span role="status" className="hidden sm:inline">{state}</span> : null}</small>
|
||||
<div role="group" aria-label="Инциденты карты за 24 часа" className="relative mx-3.5 h-9 min-w-0 flex-1">
|
||||
<span aria-hidden="true" className="bg-border absolute inset-x-2.5 top-[11px] h-0.5 rounded-full" />
|
||||
{[["−24 ч", 0], ["−6 ч", 0.75], ["−1 ч", 0.9583]].map(([label, t]) => (
|
||||
<span key={label} aria-hidden="true" className={cn(stop, "text-muted-foreground")} style={{ left: at(Number(t)) }}>
|
||||
<i className="bg-card border-muted-foreground block size-2.5 rounded-full border-2" />{label === "−1 ч" ? <span className="hidden xl:inline">{label}</span> : label}
|
||||
</span>
|
||||
))}
|
||||
{marks.map((e) => (
|
||||
{[...hours].map(([hour, group]) => {
|
||||
const e = group.find(event => event.tone === "er") ?? group[0]
|
||||
const label = `${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}${group.length > 1 ? ` · ещё ${group.length - 1}` : ""}`
|
||||
return (
|
||||
<button
|
||||
key={e.id}
|
||||
type="button"
|
||||
onClick={() => onPick(e)}
|
||||
aria-label={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
|
||||
title={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
|
||||
className="focus-visible:ring-ring absolute top-1/2 size-3 -translate-1/2 rounded-full border-2 border-[var(--card)] outline-none focus-visible:ring-2"
|
||||
style={{ left: pos(e.ts), background: TONE_COLOR[e.tone] }}
|
||||
/>
|
||||
))}
|
||||
<span className="text-success absolute top-1/2 right-0 flex translate-x-1/2 -translate-y-1/2 items-center gap-1 text-xs font-medium">
|
||||
<ToneDot tone="ok" />Live
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className="focus-visible:ring-ring absolute top-1 flex h-4 w-3 -translate-x-1/2 justify-center rounded-sm outline-none focus-visible:ring-2"
|
||||
style={{ left: at((hour + 0.5) / 24) }}
|
||||
>
|
||||
<span aria-hidden="true" className="block h-full w-1.5 rounded-sm" style={{ background: TONE_COLOR[e.tone] }} />
|
||||
</button>
|
||||
)})}
|
||||
<span className={cn(stop, "text-foreground font-semibold")} style={{ left: at(1) }}>
|
||||
<i className="bg-success border-success block size-2.5 rounded-full border-2 shadow-[0_0_0_4px_color-mix(in_oklch,var(--success)_25%,transparent)]" />Live
|
||||
</span>
|
||||
</div>
|
||||
<small className="text-muted-foreground font-mono text-xs">{new Date(now).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })}</small>
|
||||
|
||||
@@ -1,18 +1,27 @@
|
||||
"use client"
|
||||
|
||||
import type { Server } from "@/lib/data"
|
||||
import { fmtRate } from "@/lib/fmt-rate"
|
||||
import { formatMapFlowWindow, formatNetflowRate } from "@/lib/map-netflow-hops"
|
||||
import { TONE_COLOR, type Tone } from "@/components/reui-kit/ops-blocks"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
type StatusFilter = "online" | "degraded" | "offline"
|
||||
type StatusFilter = "online" | "degraded" | "offline" | "unknown"
|
||||
|
||||
const STATUS: Array<{ key: StatusFilter; label: string; tone: Tone }> = [
|
||||
{ key: "online", label: "Онлайн", tone: "ok" },
|
||||
{ key: "degraded", label: "Внимание", tone: "wn" },
|
||||
{ key: "offline", label: "Оффлайн", tone: "er" },
|
||||
{ key: "unknown", label: "Неизвестно", tone: "mu" },
|
||||
]
|
||||
|
||||
const EXIT_COLORS = ["var(--chart-4)", "var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-5)"]
|
||||
|
||||
/** Русское склонение: 1 узел, 2 узла, 5 узлов. */
|
||||
export function ruPlural(n: number, one: string, few: string, many: string) {
|
||||
const m10 = n % 10, m100 = n % 100
|
||||
return m10 === 1 && m100 !== 11 ? one : m10 >= 2 && m10 <= 4 && (m100 < 12 || m100 > 14) ? few : many
|
||||
}
|
||||
|
||||
function Seg({ parts }: { parts: Array<{ n: number; color: string }> }) {
|
||||
const shown = parts.filter((part) => part.n > 0)
|
||||
return (
|
||||
@@ -39,9 +48,14 @@ function Card({ title, value, unit, children }: { title: string; value: string;
|
||||
* KPI-полоса над картой (макет v3): узлы, GRE-туннели, NetFlow и узлы, требующие внимания.
|
||||
* Счётчики статусов фильтруют карту, строки проблем открывают узел.
|
||||
*/
|
||||
export function MapKpiStrip({ servers, tunnels, netflowBytes, windowSec, filter, onFilter, onSelect, className }: {
|
||||
export function MapKpiStrip({ servers, tunnels, downRoutes = [], exits = [], liveLink, netflowBytes, windowSec, filter, onFilter, onSelect, className }: {
|
||||
servers: Server[]
|
||||
tunnels: Array<{ status: "up" | "down" | "degraded" }>
|
||||
/** «A → B» недоступных GRE на карте — для подвала карточки туннелей. */
|
||||
downRoutes?: string[]
|
||||
/** Скорость NetFlow через Exit-узлы за окно, бит/с. */
|
||||
exits?: Array<{ name: string; bps: number }>
|
||||
liveLink?: { name: string; bps: number; bpsFwd: number; bpsRev: number }
|
||||
/** Байты NetFlow за окно; null — потоки не загружены. */
|
||||
netflowBytes: number | null
|
||||
windowSec: number
|
||||
@@ -53,14 +67,20 @@ export function MapKpiStrip({ servers, tunnels, netflowBytes, windowSec, filter,
|
||||
const count = (status: Server["status"]) => servers.filter((server) => server.status === status).length
|
||||
const up = tunnels.filter((tunnel) => tunnel.status === "up").length
|
||||
const degraded = tunnels.filter((tunnel) => tunnel.status === "degraded").length
|
||||
const down = tunnels.length - up - degraded
|
||||
const problems = servers.filter((server) => server.enabled !== false && server.status !== "online")
|
||||
const minutes = Math.max(1, Math.round(windowSec / 60))
|
||||
const topExits = netflowBytes == null ? [] : [...exits].filter((exit) => exit.bps > 0).sort((a, b) => b.bps - a.bps)
|
||||
const flowRate = netflowBytes == null ? null : formatNetflowRate({ bps: (netflowBytes * 8) / Math.max(1, windowSec) })
|
||||
const flowLabel = `NetFlow · ${formatMapFlowWindow(windowSec)}`
|
||||
const greFoot = !tunnels.length ? "Туннелей на карте нет"
|
||||
: downRoutes.length ? `${downRoutes[0]} — без ответа${downRoutes.length > 1 ? ` · ещё ${downRoutes.length - 1}` : ""}`
|
||||
: degraded ? `С деградацией: ${degraded}` : "Все туннели на карте работают"
|
||||
return (
|
||||
<div className={cn("grid grid-cols-[repeat(auto-fit,minmax(min(240px,100%),1fr))] gap-3", className)}>
|
||||
<Card title="Узлы на карте" value={String(servers.length)} unit="устройств">
|
||||
<Card title="Узлы на карте" value={String(servers.length)} unit={ruPlural(servers.length, "устройство", "устройства", "устройств")}>
|
||||
<Seg parts={STATUS.map((s) => ({ n: count(s.key), color: TONE_COLOR[s.tone] }))} />
|
||||
<div className="-mx-1.5 -mb-1 flex flex-wrap gap-0.5">
|
||||
{STATUS.map((s) => (
|
||||
{STATUS.filter((s) => s.key !== "unknown" || count(s.key) > 0).map((s) => (
|
||||
<button
|
||||
key={s.key}
|
||||
type="button"
|
||||
@@ -76,14 +96,20 @@ export function MapKpiStrip({ servers, tunnels, netflowBytes, windowSec, filter,
|
||||
</div>
|
||||
</Card>
|
||||
<Card title="GRE-туннели на карте" value={tunnels.length ? `${up} из ${tunnels.length}` : "—"} unit="работают">
|
||||
<Seg parts={[{ n: up, color: TONE_COLOR.ok }, { n: degraded, color: TONE_COLOR.wn }, { n: tunnels.length - up - degraded, color: TONE_COLOR.er }]} />
|
||||
<div className="text-muted-foreground text-xs">{tunnels.length ? `Деградация: ${degraded} · недоступны: ${tunnels.length - up - degraded}` : "Туннелей на карте нет"}</div>
|
||||
<Seg parts={[{ n: up, color: TONE_COLOR.ok }, { n: degraded, color: TONE_COLOR.wn }, { n: down, color: TONE_COLOR.er }]} />
|
||||
<div className="text-muted-foreground text-xs [overflow-wrap:anywhere]">{greFoot}</div>
|
||||
</Card>
|
||||
<Card title={`NetFlow · окно ${minutes} мин`} value={netflowBytes == null ? "—" : fmtRate((netflowBytes * 8) / Math.max(1, windowSec))} unit="в среднем за окно">
|
||||
<Seg parts={[{ n: netflowBytes ? 1 : 0, color: "var(--chart-4)" }]} />
|
||||
<div className="text-muted-foreground text-xs">{netflowBytes == null ? "Потоки ещё не загружены" : "Все потоки NetFlow за окно"}</div>
|
||||
<Card title={liveLink ? "Макс. из замеров · Live" : flowLabel} value={liveLink ? formatNetflowRate(liveLink) : flowRate ?? "—"} unit={liveLink ? "RX + TX" : "в среднем"}>
|
||||
<Seg parts={liveLink ? [{ n: liveLink.bpsFwd, color: "var(--chart-4)" }, { n: liveLink.bpsRev, color: "var(--chart-1)" }]
|
||||
: topExits.length ? topExits.map((exit, i) => ({ n: exit.bps, color: EXIT_COLORS[i % EXIT_COLORS.length] })) : [{ n: netflowBytes ? 1 : 0, color: "var(--chart-4)" }]} />
|
||||
<div className="text-muted-foreground text-xs [overflow-wrap:anywhere]">
|
||||
{liveLink && <div title={liveLink.name}>{liveLink.name}</div>}
|
||||
{liveLink
|
||||
? flowRate && `${flowLabel} · среднее ${flowRate}`
|
||||
: netflowBytes == null ? "Потоки ещё не загружены" : topExits.length ? topExits.slice(0, 3).map((exit) => `${exit.name} ${formatNetflowRate({ bps: exit.bps })}`).join(" · ") : "Выборка IPFIX"}
|
||||
</div>
|
||||
</Card>
|
||||
<Card title="Требуют внимания" value={String(problems.length)} unit="узлов">
|
||||
<Card title="Требуют внимания" value={String(problems.length)} unit={ruPlural(problems.length, "узел", "узла", "узлов")}>
|
||||
{problems.length ? (
|
||||
<div className="-mx-1.5 -mb-1 flex flex-col">
|
||||
{problems.slice(0, 3).map((server) => (
|
||||
@@ -94,7 +120,7 @@ export function MapKpiStrip({ servers, tunnels, netflowBytes, windowSec, filter,
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-muted-foreground text-xs">Проблемных узлов нет</div>
|
||||
<div className="text-muted-foreground text-xs">На момент снимка все узлы отвечали.</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
"use client"
|
||||
|
||||
import { Fragment, type ReactNode } from "react"
|
||||
import { usePathname } from "next/navigation"
|
||||
import { InfoIcon, SearchIcon } from "lucide-react"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbItem,
|
||||
@@ -11,8 +16,8 @@ import {
|
||||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
} from "@/components/ui/breadcrumb"
|
||||
import { AppsMenu } from "@/components/apps-menu"
|
||||
import { SystemMonitorPopover } from "@/components/system-monitor-popover"
|
||||
import { openCommandPalette } from "@/components/command-palette"
|
||||
|
||||
interface Crumb {
|
||||
label: string
|
||||
@@ -26,21 +31,53 @@ interface PageHeaderProps {
|
||||
status?: ReactNode
|
||||
}
|
||||
|
||||
/** Header chrome — AppsMenu + SystemMonitor; theme in NavUser. @see https://reui.io/preview/base/app-shell-12 */
|
||||
export function PageHeader({ crumbs, actions, status }: PageHeaderProps) {
|
||||
/** Откуда раздел берёт данные — окно «Источники и свежесть данных» (как в шапке EvoBGP и макета v2). */
|
||||
const FRESH: Record<string, { badge: string; text: string }> = {
|
||||
"/dashboard": { badge: "Live", text: "Серверы, туннели, пробы, BGP, трафик, Internet path и события из API · обновление каждые 30 с" },
|
||||
"/traffic": { badge: "Live", text: "Счётчики интерфейсов RouterOS и потоки IPFIX · текущая скорость по live-потоку" },
|
||||
"/statistics": { badge: "Куб", text: "Куб NetFlow: факты IPFIX по суткам и часам · уникальный объём без дублей" },
|
||||
"/network-map": { badge: "Снимок", text: "Снимок карты из API и NetFlow за окно 5 мин · DNS для адресов GRE" },
|
||||
"/uptime": { badge: "Пробы", text: "Пробы ping и скорости по серверам · история RTT за час" },
|
||||
"/servers": { badge: "Каталог", text: "Каталог серверов и последний опрос RouterOS API" },
|
||||
"/ix": { badge: "IX", text: "Сегменты, площадки и Linux-клиенты точек обмена трафиком" },
|
||||
}
|
||||
|
||||
function freshFor(pathname: string) {
|
||||
const key = Object.keys(FRESH).sort((a, b) => b.length - a.length).find((k) => pathname === k || pathname.startsWith(`${k}/`))
|
||||
return key ? FRESH[key] : { badge: "API", text: "Данные раздела из API MikrotikManager" }
|
||||
}
|
||||
|
||||
function FreshnessPopover() {
|
||||
const fresh = freshFor(usePathname())
|
||||
return (
|
||||
<header className="bg-background sticky top-0 z-10 flex min-h-12 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-1.5 md:px-6">
|
||||
<Popover>
|
||||
<PopoverTrigger render={<Button type="button" variant="ghost" size="icon" aria-label="Источники и свежесть данных" title="Источники и свежесть данных" />}>
|
||||
<InfoIcon aria-hidden />
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" sideOffset={8} className="flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-2">
|
||||
<Badge variant="success-light" size="sm" className="w-fit">{fresh.badge}</Badge>
|
||||
<p className="text-muted-foreground text-sm">{fresh.text}</p>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
/** Шапка общего макета v2 и EvoBGP: меню, «Главная / раздел / страница», источники данных, поиск, состояние системы. */
|
||||
export function PageHeader({ crumbs, actions, status }: PageHeaderProps) {
|
||||
const trail = crumbs[0]?.label === "Главная" ? crumbs : [{ label: "Главная", href: "/dashboard" }, ...crumbs]
|
||||
return (
|
||||
<header className="bg-background/80 sticky top-0 z-10 flex min-h-12 shrink-0 flex-wrap items-center gap-2 border-b px-4 py-1.5 backdrop-blur md:px-6">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<Separator orientation="vertical" className="mr-2 data-[orientation=vertical]:h-4" />
|
||||
<Breadcrumb aria-label="Путь страницы" className="min-w-0 flex-1">
|
||||
<BreadcrumbList className="flex-nowrap">
|
||||
{crumbs.map((crumb, i) => (
|
||||
{trail.map((crumb, i) => (
|
||||
<Fragment key={i}>
|
||||
{i > 0 && <BreadcrumbSeparator className="text-muted-foreground hidden shrink-0 sm:block">/</BreadcrumbSeparator>}
|
||||
<BreadcrumbItem className={i < crumbs.length - 1 ? "hidden shrink-0 sm:inline-flex" : "min-w-0"}>
|
||||
{i < crumbs.length - 1 && crumb.href ? (
|
||||
<BreadcrumbItem className={i < trail.length - 1 ? "hidden shrink-0 sm:inline-flex" : "min-w-0"}>
|
||||
{i < trail.length - 1 && crumb.href ? (
|
||||
<BreadcrumbLink href={crumb.href}>{crumb.label}</BreadcrumbLink>
|
||||
) : i < crumbs.length - 1 ? (
|
||||
) : i < trail.length - 1 ? (
|
||||
<span className="text-muted-foreground text-sm">{crumb.label}</span>
|
||||
) : (
|
||||
<BreadcrumbPage className="wrap-anywhere">{crumb.label}</BreadcrumbPage>
|
||||
@@ -54,7 +91,10 @@ export function PageHeader({ crumbs, actions, status }: PageHeaderProps) {
|
||||
{actions ? <div role="group" aria-label="Действия страницы" className="flex min-w-0 flex-1 flex-wrap items-center gap-2">{actions}</div> : null}
|
||||
<div className="ml-auto flex shrink-0 items-center gap-2">
|
||||
{status}
|
||||
<AppsMenu />
|
||||
<FreshnessPopover />
|
||||
<Button type="button" variant="outline" size="icon" aria-label="Командная палитра (⌘K)" className="md:hidden" onClick={openCommandPalette}>
|
||||
<SearchIcon aria-hidden />
|
||||
</Button>
|
||||
<SystemMonitorPopover />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts"
|
||||
import { useState } from "react"
|
||||
import { CartesianGrid, Line, LineChart, ReferenceLine, XAxis, YAxis } from "recharts"
|
||||
import { Frame, FramePanel } from "@/components/reui/frame"
|
||||
import { ChartContainer, ChartTooltip, type ChartConfig } from "@/components/ui/chart"
|
||||
import { fmtRate, formatRangeAgo, TRAFFIC_RANGE_MINUTES } from "@/lib/fmt-rate"
|
||||
@@ -59,6 +60,7 @@ function toChartData(rx: (number|null)[], tx: (number|null)[], rangeMinutes: num
|
||||
return Array.from({ length: n }, (_, i) => {
|
||||
const minutesAgo = Math.round((1 - i / denom) * rangeMinutes)
|
||||
return {
|
||||
index: i,
|
||||
time: formatRangeAgo(minutesAgo),
|
||||
rx: typeof rx[i] === "number" && Number.isFinite(rx[i]) && rx[i] >= 0 ? rx[i] : null,
|
||||
tx: typeof tx[i] === "number" && Number.isFinite(tx[i]) && tx[i] >= 0 ? tx[i] : null,
|
||||
@@ -72,6 +74,7 @@ export function TrafficRxTxChart({
|
||||
range = "1h",
|
||||
rangeMinutes: actualMinutes,
|
||||
embedded = false,
|
||||
scrub = false,
|
||||
}: {
|
||||
rx: (number|null)[]
|
||||
tx: (number|null)[]
|
||||
@@ -79,9 +82,13 @@ export function TrafficRxTxChart({
|
||||
rangeMinutes?: number
|
||||
/** Skip outer Frame when already inside OpsPanel / Frame. */
|
||||
embedded?: boolean
|
||||
scrub?: boolean
|
||||
}) {
|
||||
const rangeMinutes = actualMinutes ?? TRAFFIC_RANGE_MINUTES[range] ?? 60
|
||||
const data = toChartData(rx, tx, rangeMinutes)
|
||||
const [selected, setSelected] = useState<number>()
|
||||
const index = Math.min(selected ?? data.length - 1, data.length - 1)
|
||||
const point = data[index]
|
||||
const tickEvery = Math.max(1, Math.ceil(data.length / 6))
|
||||
|
||||
const hasRx = data.some(point => point.rx !== null)
|
||||
@@ -105,7 +112,8 @@ export function TrafficRxTxChart({
|
||||
stroke="var(--border)"
|
||||
/>
|
||||
<XAxis
|
||||
dataKey="time"
|
||||
dataKey="index"
|
||||
tickFormatter={(value: number) => data[value]?.time ?? ""}
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
tick={{ fontSize: 11 }}
|
||||
@@ -121,6 +129,7 @@ export function TrafficRxTxChart({
|
||||
width={72}
|
||||
/>
|
||||
<ChartTooltip content={<CustomTooltip />} />
|
||||
{scrub && selected !== undefined && <ReferenceLine x={index} stroke="var(--muted-foreground)" />}
|
||||
{hasRx && <Line
|
||||
dataKey="rx"
|
||||
type="monotone"
|
||||
@@ -141,6 +150,15 @@ export function TrafficRxTxChart({
|
||||
<ChartLegendItem label="RX (входящий)" color="var(--chart-rx)" />
|
||||
<ChartLegendItem label="TX (исходящий)" color="var(--chart-tx)" />
|
||||
</div>
|
||||
{scrub && data.length > 1 && <div className="grid gap-2 border-t pt-2 text-xs">
|
||||
<label className="flex flex-wrap items-center gap-2 text-muted-foreground">
|
||||
Точка на графике
|
||||
<input type="range" className="min-w-24 flex-1 accent-primary" min={0} max={data.length - 1} value={index}
|
||||
aria-valuetext={`${point.time} · RX ${fmtRate(point.rx)} · TX ${fmtRate(point.tx)}`}
|
||||
onChange={event => setSelected(Number(event.target.value))} />
|
||||
</label>
|
||||
<p className="font-mono tabular-nums">{point.time} · RX {fmtRate(point.rx)} · TX {fmtRate(point.tx)}</p>
|
||||
</div>}
|
||||
</div>
|
||||
)
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState, type ReactNode } from "react"
|
||||
import { Activity, Filter, HeartPulse, Server } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { Activity, ArrowRightIcon, Filter, HeartPulse, Server } from "lucide-react"
|
||||
|
||||
import { Badge } from "@/components/reui/badge"
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
|
||||
@@ -151,7 +152,15 @@ export function SystemMonitorPopover() {
|
||||
[apiOk, filtersCount, healthOk, monitoringCount, serversCount],
|
||||
)
|
||||
|
||||
const spiking = metrics.some((m) => m.alert)
|
||||
// Проблемы для «Состояния системы» — только подтверждённые сигналы: API и сводка.
|
||||
const items: Array<{ id: string; tone: "er" | "wn"; title: string; text: string }> = []
|
||||
if (healthOk === false) items.push({ id: "api", tone: "er", title: "API MikrotikManager не отвечает", text: "GET /health вернул ошибку или не ответил" })
|
||||
if (data?.countsError) items.push({ id: "counts", tone: "wn", title: "Сводка не обновлена", text: data.countsError })
|
||||
const errors = items.filter((i) => i.tone === "er").length
|
||||
const warnings = items.length - errors
|
||||
const okCount = metrics.length - items.length
|
||||
const label = errors ? "Сбой" : warnings ? "Внимание" : healthOk == null ? "Нет данных" : "Норма"
|
||||
const tone = errors ? "destructive" : warnings || healthOk == null ? "warning" : "success"
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
@@ -159,63 +168,73 @@ export function SystemMonitorPopover() {
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Монитор системы"
|
||||
aria-label={`Состояние системы: ${label.toLowerCase()}, сбоев ${errors}, предупреждений ${warnings}`}
|
||||
className={cn(
|
||||
"relative inline-flex h-8 items-center gap-1.5 rounded-md border px-2 transition-colors outline-none",
|
||||
"border-border hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring",
|
||||
"relative inline-flex h-8 items-center gap-2 rounded-md border px-2 text-sm font-medium transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring max-[760px]:w-8 max-[760px]:justify-center max-[760px]:border-transparent max-[760px]:bg-transparent max-[760px]:px-0",
|
||||
tone === "destructive" && "border-destructive/40 bg-destructive/10 hover:bg-destructive/20 aria-expanded:bg-destructive/20",
|
||||
tone === "warning" && "border-warning/40 bg-warning/10 hover:bg-warning/20 aria-expanded:bg-warning/20",
|
||||
tone === "success" && "border-border hover:bg-accent aria-expanded:bg-accent",
|
||||
)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="relative flex size-3.5 items-center justify-center">
|
||||
<Activity
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"size-3.5 transition-colors",
|
||||
spiking ? "text-destructive" : "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
{spiking ? (
|
||||
<span className="bg-destructive/25 absolute inset-0 animate-ping rounded-full" aria-hidden />
|
||||
) : null}
|
||||
<Activity aria-hidden className={cn("size-4", tone === "destructive" ? "text-destructive" : tone === "warning" ? "text-warning" : "text-success")} />
|
||||
<span className={cn("hidden min-[1000px]:inline", tone === "destructive" ? "text-destructive-foreground" : tone === "warning" ? "text-warning-foreground" : "text-foreground")}>{label}</span>
|
||||
<span className="hidden items-center gap-1.5 tabular-nums min-[1240px]:inline-flex">
|
||||
<span className="bg-destructive size-1.5 rounded-full" aria-hidden />
|
||||
{errors}
|
||||
<span className="bg-warning size-1.5 rounded-full" aria-hidden />
|
||||
{warnings}
|
||||
</span>
|
||||
<span className="text-foreground hidden text-xs font-medium sm:inline">Система</span>
|
||||
<Badge
|
||||
variant={spiking ? "destructive-light" : apiOk?"success-light":"outline"}
|
||||
size="xs"
|
||||
className={cn("h-4 px-1.5 text-[10px]",apiOk&&"text-emerald-700 dark:text-emerald-400",spiking&&"text-red-700 dark:text-red-400")}
|
||||
>
|
||||
{spiking?"Нет связи":apiOk?"API доступен":"Нет данных"}
|
||||
</Badge>
|
||||
{items.length ? <span className="bg-destructive ring-background absolute top-1 right-1 size-2 rounded-full ring-2 min-[760px]:hidden" aria-hidden /> : null}
|
||||
</PopoverTrigger>
|
||||
|
||||
<PopoverContent align="end" sideOffset={8} className="flex w-80 max-w-[calc(100vw-2rem)] flex-col gap-0! p-0!">
|
||||
<div className="border-border flex items-center justify-between border-b px-3 py-2.5">
|
||||
<span className="text-foreground text-xs font-medium">Монитор MikrotikManager</span>
|
||||
<span className="text-muted-foreground text-[11px] tabular-nums">
|
||||
{mode!=="live"?"Демо":data?.receivedAt?new Date(data.receivedAt).toLocaleTimeString("ru-RU"):"Снимок не получен"}
|
||||
</span>
|
||||
<PopoverContent align="end" sideOffset={8} className="flex w-[24rem] max-w-[calc(100vw-1.5rem)] flex-col gap-2 p-2">
|
||||
<div className="flex items-start justify-between gap-2 px-1.5 pt-1.5">
|
||||
<div className="grid leading-tight">
|
||||
<b className="text-sm font-semibold">Состояние системы</b>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{mode !== "live" ? "Демо-данные" : data?.receivedAt ? `обновлено ${new Date(data.receivedAt).toLocaleTimeString("ru-RU")}` : "Снимок не получен"}
|
||||
</span>
|
||||
</div>
|
||||
<Badge variant={errors ? "destructive-light" : warnings ? "warning-light" : "success-light"} size="sm" className={cn(!errors && !warnings && "text-emerald-700 dark:text-emerald-400", errors && "text-red-700 dark:text-red-400")}>{label}</Badge>
|
||||
</div>
|
||||
{data?.countsError?<p role="status" className="px-3 py-2 text-xs text-muted-foreground">{data.countsError}</p>:null}
|
||||
<div className="grid grid-cols-2">
|
||||
<div className="grid grid-cols-3 gap-1.5">
|
||||
{[
|
||||
{ n: errors, l: "сбой", c: "text-destructive-foreground" },
|
||||
{ n: warnings, l: "предупреждения", c: "text-warning-foreground" },
|
||||
{ n: Math.max(0, okCount), l: "в норме", c: "text-success-foreground" },
|
||||
].map((x) => (
|
||||
<span key={x.l} className="bg-muted/55 text-muted-foreground flex flex-col rounded-lg px-2.5 py-2 text-xs">
|
||||
<b className={cn("text-lg leading-tight font-semibold tabular-nums", x.c)}>{x.n}</b>
|
||||
{x.l}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{items.length ? (
|
||||
<div role="status"><ul className="flex flex-col gap-0.5">
|
||||
{items.map((m) => (
|
||||
<li key={m.id} className="flex items-center gap-2.5 rounded-md px-1.5 py-2">
|
||||
<span aria-hidden className={cn("size-2 shrink-0 rounded-full", m.tone === "er" ? "bg-destructive" : "bg-warning")} />
|
||||
<span className="grid min-w-0 flex-1 leading-tight">
|
||||
<b className="truncate text-[13px] font-medium">{m.title}</b>
|
||||
<span className="text-muted-foreground truncate text-xs">{m.text}</span>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul></div>
|
||||
) : null}
|
||||
<div className="grid grid-cols-2 overflow-hidden rounded-lg border">
|
||||
{metrics.map((metric, i) => (
|
||||
<div
|
||||
key={metric.id}
|
||||
className={cn(
|
||||
i % 2 === 1 && "border-border border-l",
|
||||
i >= 2 && "border-border border-t",
|
||||
)}
|
||||
>
|
||||
<div key={metric.id} className={cn(i % 2 === 1 && "border-l", i >= 2 && "border-t")}>
|
||||
<MetricCell metric={metric} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="border-border text-muted-foreground border-t px-3 py-2 text-[11px]">
|
||||
Источник:{" "}
|
||||
<span className="text-foreground font-medium">
|
||||
{mode === "live" ? "API" : "мок"}
|
||||
</span>
|
||||
</div>
|
||||
<Link href="/uptime" className="text-muted-foreground hover:text-foreground flex items-center justify-between px-1.5 pt-1 pb-0.5 text-sm">
|
||||
Мониторинг
|
||||
<ArrowRightIcon className="size-3.5" aria-hidden />
|
||||
</Link>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
DATA_GRID_CELL_PAD_LAST,
|
||||
} from "@/components/data-grids/shared/data-grid-layout"
|
||||
import { TrafficFlowsDataGrid } from "@/components/data-grids/traffic-flows-data-grid"
|
||||
import { matchesMapService } from "@/lib/flow-map-service-match"
|
||||
import { FlowTrafficMap } from "@/components/traffic/flow-traffic-map"
|
||||
import { StatusDot } from "@/components/status-dot"
|
||||
import { Flag } from "@/components/flag"
|
||||
@@ -79,7 +80,9 @@ export function FlowEntityCardView({
|
||||
{card.site}
|
||||
</span>
|
||||
</div>
|
||||
<TrafficMiniChart rx={card.rxSeries} tx={card.txSeries} />
|
||||
{card.rxNow === null && card.txNow === null
|
||||
? <p className="text-xs text-muted-foreground">Нет потоков с подтверждённой привязкой</p>
|
||||
: <TrafficMiniChart rx={card.rxSeries} tx={card.txSeries} />}
|
||||
<div className="flex justify-between mt-2 gap-2">
|
||||
<div className="flex items-center gap-1 text-xs">
|
||||
<ArrowDownIcon className="size-3 text-success" />
|
||||
@@ -103,13 +106,14 @@ type BreakdownFilter = {
|
||||
label: string
|
||||
serverId?: string
|
||||
}
|
||||
type SessionFilter = BreakdownFilter | { kind: "path"; path: FlowPathRow; label: string }
|
||||
type SessionFilter = BreakdownFilter | { kind: "path"; path: FlowPathRow; label: string } | { kind: "map-service"; label: string; country?: string }
|
||||
|
||||
function talkerMatchesFilter(row: FlowTalkerDto, filter: SessionFilter): boolean {
|
||||
switch (filter.kind) {
|
||||
case "application": return row.application === filter.value
|
||||
case "category": return row.category === filter.value
|
||||
case "service": return row.service === filter.value
|
||||
case "map-service": return matchesMapService(row, filter.label, filter.country)
|
||||
case "asn": return String(row.dstAsn ?? "unknown") === filter.value
|
||||
case "country": return (!filter.serverId || row.serverId === filter.serverId) && (row.dstCountry || "unknown") === filter.value
|
||||
case "protocol": return row.protoName === filter.value
|
||||
@@ -329,6 +333,9 @@ export function FlowAnalyticsDetail({
|
||||
onExcludeOverlay,
|
||||
liveHint,
|
||||
emptyHint,
|
||||
initialService,
|
||||
initialCountry,
|
||||
mapNodes,
|
||||
}: {
|
||||
card: (Pick<FlowEntityCard, "id" | "name" | "country" | "site"> & Partial<FlowEntityCard>) | null
|
||||
analytics: FlowAnalyticsDto | null
|
||||
@@ -349,14 +356,16 @@ export function FlowAnalyticsDetail({
|
||||
onExcludeOverlay: (value: boolean) => void
|
||||
liveHint?: string
|
||||
emptyHint?: string
|
||||
initialService?: string
|
||||
initialCountry?: string
|
||||
mapNodes?: string[]
|
||||
}) {
|
||||
const [slice, setSlice] = useState("applications")
|
||||
const [sessionFilter, setSessionFilter] = useState<SessionFilter | null>(null)
|
||||
const rxNow = analytics ? analytics.bpsNow / 1_000_000 : (card?.rxNow ?? 0)
|
||||
const [slice, setSlice] = useState(initialService ? "sessions" : "applications")
|
||||
const [sessionFilter, setSessionFilter] = useState<SessionFilter | null>(initialService ? { kind: "map-service", label: initialService, country: initialCountry } : null)
|
||||
const rxNow = analytics?.bytes ? analytics.bpsNow / 1_000_000 : (card?.rxNow ?? null)
|
||||
const bytes = analytics?.bytes ?? card?.bytes ?? 0
|
||||
const sessionRows = (analytics?.conversationsList ?? []).filter((row) =>
|
||||
sessionFilter ? talkerMatchesFilter(row, sessionFilter) : true,
|
||||
)
|
||||
const sessionRows = (analytics?.conversationsList ?? []).filter(row =>
|
||||
(!mapNodes || mapNodes.includes(row.enId || row.serverId)) && (!sessionFilter || talkerMatchesFilter(row, sessionFilter)))
|
||||
|
||||
function pickBreakdown(kind: BreakdownFilter["kind"], row: FlowBreakdownRow) {
|
||||
setSessionFilter({ kind, value: row.id, label: row.label })
|
||||
|
||||
|
Before Width: | Height: | Size: 163 KiB After Width: | Height: | Size: 169 KiB |
|
Before Width: | Height: | Size: 66 KiB After Width: | Height: | Size: 61 KiB |
|
Before Width: | Height: | Size: 62 KiB After Width: | Height: | Size: 60 KiB |
|
Before Width: | Height: | Size: 146 KiB After Width: | Height: | Size: 145 KiB |
|
Before Width: | Height: | Size: 65 KiB After Width: | Height: | Size: 60 KiB |
|
Before Width: | Height: | Size: 63 KiB After Width: | Height: | Size: 54 KiB |
@@ -1,70 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { isTrafficLiveSample } from "@/hooks/use-traffic-live"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
|
||||
export interface GreTrafficTarget {
|
||||
edgeId: string
|
||||
serverId: string
|
||||
iface: string
|
||||
}
|
||||
|
||||
type Rate = { bps: number; bpsFwd: number; bpsRev: number; receivedAt: number }
|
||||
const MAX_CONCURRENT_READS = 4
|
||||
const REFRESH_MS = 8_000
|
||||
const MAX_SAMPLE_AGE_MS = 30_000
|
||||
|
||||
export function useMapGreTraffic(backendUrl: string, targets: GreTrafficTarget[]) {
|
||||
const key = JSON.stringify(targets)
|
||||
const [snapshot, setSnapshot] = useState<{ backendUrl: string; key: string; rates: Map<string, Rate> }>()
|
||||
|
||||
useEffect(() => {
|
||||
const scope: GreTrafficTarget[] = JSON.parse(key)
|
||||
if (!scope.length) return
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const run = async () => {
|
||||
if (document.hidden) {
|
||||
timer = setTimeout(run, REFRESH_MS)
|
||||
return
|
||||
}
|
||||
for (let offset = 0; offset < scope.length && !controller.signal.aborted; offset += MAX_CONCURRENT_READS) {
|
||||
const batch = await Promise.all(scope.slice(offset, offset + MAX_CONCURRENT_READS).map(async ({ edgeId, serverId, iface }) => {
|
||||
try {
|
||||
const query = new URLSearchParams({ iface, once: "1" })
|
||||
const sample = await requestJson<unknown>(backendUrl, `/api/traffic/servers/${encodeURIComponent(serverId)}/live?${query}`, {
|
||||
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(6_000)]),
|
||||
cache: "no-store",
|
||||
})
|
||||
if (isTrafficLiveSample(sample)) {
|
||||
const bpsFwd = sample.rxMbps * 1_000_000
|
||||
const bpsRev = sample.txMbps * 1_000_000
|
||||
return { edgeId, rate: { bps: bpsFwd + bpsRev, bpsFwd, bpsRev, receivedAt: Date.now() } }
|
||||
}
|
||||
} catch {
|
||||
// One unavailable interface cannot hide readings on other links.
|
||||
}
|
||||
return { edgeId }
|
||||
}))
|
||||
if (controller.signal.aborted) return
|
||||
setSnapshot(previous => {
|
||||
const rates = new Map(previous?.key === key && previous.backendUrl === backendUrl ? previous.rates : [])
|
||||
for (const { edgeId, rate } of batch) {
|
||||
if (rate) rates.set(edgeId, rate)
|
||||
else rates.delete(edgeId)
|
||||
}
|
||||
return { backendUrl, key, rates }
|
||||
})
|
||||
}
|
||||
if (!controller.signal.aborted) timer = setTimeout(run, REFRESH_MS)
|
||||
}
|
||||
void run()
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [backendUrl, key])
|
||||
|
||||
return (edgeId: string) => {
|
||||
const rate = snapshot?.key === key && snapshot.backendUrl === backendUrl ? snapshot.rates.get(edgeId) : undefined
|
||||
return rate && Date.now() - rate.receivedAt <= MAX_SAMPLE_AGE_MS ? rate : undefined
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { isTrafficLiveSample, type TrafficLiveSample } from "@/hooks/use-traffic-live"
|
||||
import { requestJson } from "@/shared/api/http-client"
|
||||
|
||||
export interface MapTrafficTarget {
|
||||
edgeId: string
|
||||
serverId: string
|
||||
iface: string
|
||||
}
|
||||
|
||||
type Rate = { bps: number; bpsFwd: number; bpsRev: number; at: string; receivedAt: number }
|
||||
const MAX_CONCURRENT_READS = 4
|
||||
const REFRESH_MS = 8_000
|
||||
const MAX_SAMPLE_AGE_MS = 30_000
|
||||
|
||||
export function isFreshMapTrafficSample(sample: unknown, now = Date.now()): sample is TrafficLiveSample {
|
||||
return isTrafficLiveSample(sample) && Math.abs(now - Date.parse(sample.at)) <= MAX_SAMPLE_AGE_MS
|
||||
}
|
||||
|
||||
export function useMapInterfaceTraffic(backendUrl: string, targets: MapTrafficTarget[]) {
|
||||
const key = JSON.stringify(targets)
|
||||
const [snapshot, setSnapshot] = useState<{ backendUrl: string; key: string; rates: Map<string, Rate> }>()
|
||||
|
||||
useEffect(() => {
|
||||
const scope: MapTrafficTarget[] = JSON.parse(key)
|
||||
if (!scope.length) return
|
||||
const servers = new Map<string, Map<string, string[]>>()
|
||||
for (const { edgeId, serverId, iface } of scope) {
|
||||
const interfaces = servers.get(serverId) ?? new Map<string, string[]>()
|
||||
interfaces.set(iface, [...(interfaces.get(iface) ?? []), edgeId])
|
||||
servers.set(serverId, interfaces)
|
||||
}
|
||||
const requests = [...servers].flatMap(([serverId, interfaces]) => {
|
||||
const entries = [...interfaces]
|
||||
return Array.from({ length: Math.ceil(entries.length / 16) }, (_, i) => ({
|
||||
serverId, entries: entries.slice(i * 16, (i + 1) * 16),
|
||||
}))
|
||||
})
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const run = async () => {
|
||||
if (document.hidden) {
|
||||
timer = setTimeout(run, REFRESH_MS)
|
||||
return
|
||||
}
|
||||
for (let offset = 0; offset < requests.length && !controller.signal.aborted; offset += MAX_CONCURRENT_READS) {
|
||||
const batch = await Promise.all(requests.slice(offset, offset + MAX_CONCURRENT_READS).map(async ({ serverId, entries }) => {
|
||||
const single = entries.length === 1
|
||||
let samples: Record<string, unknown> = {}
|
||||
try {
|
||||
const names = entries.map(([iface]) => iface).join(",")
|
||||
const query = new URLSearchParams({ [single ? "iface" : "ifaces"]: names, once: "1" })
|
||||
const response = await requestJson<{ interfaces?: Record<string, unknown> }>(backendUrl, `/api/traffic/servers/${encodeURIComponent(serverId)}/live?${query}`, {
|
||||
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(9_000)]),
|
||||
cache: "no-store",
|
||||
})
|
||||
samples = single ? { [names]: response } : response?.interfaces ?? {}
|
||||
} catch {
|
||||
// Other routers can still return fresh samples.
|
||||
}
|
||||
return entries.flatMap(([iface, edgeIds]) => {
|
||||
const sample = samples[iface]
|
||||
const receivedAt = Date.now()
|
||||
const rate = isFreshMapTrafficSample(sample, receivedAt) ? {
|
||||
bps: (sample.rxMbps + sample.txMbps) * 1_000_000,
|
||||
bpsFwd: sample.rxMbps * 1_000_000,
|
||||
bpsRev: sample.txMbps * 1_000_000,
|
||||
at: sample.at,
|
||||
receivedAt,
|
||||
} : undefined
|
||||
return edgeIds.map(edgeId => ({ edgeId, rate }))
|
||||
})
|
||||
}))
|
||||
if (controller.signal.aborted) return
|
||||
setSnapshot(previous => {
|
||||
const rates = new Map(previous?.key === key && previous.backendUrl === backendUrl ? previous.rates : [])
|
||||
for (const { edgeId, rate } of batch.flat()) {
|
||||
if (rate) rates.set(edgeId, rate)
|
||||
else rates.delete(edgeId)
|
||||
}
|
||||
return { backendUrl, key, rates }
|
||||
})
|
||||
}
|
||||
if (!controller.signal.aborted) timer = setTimeout(run, REFRESH_MS)
|
||||
}
|
||||
void run()
|
||||
return () => { controller.abort(); clearTimeout(timer) }
|
||||
}, [backendUrl, key])
|
||||
|
||||
return (edgeId: string) => {
|
||||
const rate = snapshot?.key === key && snapshot.backendUrl === backendUrl ? snapshot.rates.get(edgeId) : undefined
|
||||
return rate && Date.now() - Math.min(rate.receivedAt, Date.parse(rate.at)) <= MAX_SAMPLE_AGE_MS ? rate : undefined
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { FlowTalkerDto } from "@mmapp/contracts/traffic-flow"
|
||||
|
||||
export function matchesMapService(row: Pick<FlowTalkerDto, "service" | "category" | "dstCountry">, label: string, country?: string) {
|
||||
const service = row.service === label || row.category === label && (row.service === "Прочее" || ["DNS", "SSH", "BGP"].includes(label))
|
||||
if (!service || !country) return service
|
||||
return country === "unknown" ? !row.dstCountry || row.dstCountry.toLowerCase() === "unknown" : row.dstCountry?.toUpperCase() === country.toUpperCase()
|
||||
}
|
||||
@@ -43,3 +43,7 @@ export function formatServicePathTitle(label: string, serviceLabel: string): str
|
||||
if (label.includes(svc)) return label
|
||||
return `${label} · ${svc}`
|
||||
}
|
||||
|
||||
export function servicePathKey(p: { clientId: string; viaId: string; viaIface?: string; enId: string; serviceId: string }): string {
|
||||
return JSON.stringify([p.clientId, p.viaId, p.viaIface, p.enId, p.serviceId])
|
||||
}
|
||||
@@ -18,6 +18,7 @@ export interface GreSpeedProbeSnapshot {
|
||||
lastRxAvgMbps?: number | null
|
||||
lastPingAt?: string | null
|
||||
lastPingRttMs?: number | null
|
||||
lastPingLossPct?: number | null
|
||||
}
|
||||
|
||||
export type GreTunnelProbeEdge = {
|
||||
|
||||
@@ -51,6 +51,11 @@ export function formatNetflowDir(hop: Pick<MatchedNetflowHop, "bpsFwd" | "bpsRev
|
||||
return `↓${formatNetflowRate({ bps: hop.bpsFwd })} ↑${formatNetflowRate({ bps: hop.bpsRev })}`
|
||||
}
|
||||
|
||||
export function formatMapFlowWindow(windowSec: number): string {
|
||||
const seconds = Math.floor(windowSec % 60)
|
||||
return `${Math.floor(windowSec / 60)} мин${seconds ? ` ${seconds} с` : ""}`
|
||||
}
|
||||
|
||||
/** GRE rates use RX/TX at the tunnel owner, regardless of its position on the map. */
|
||||
function greInterfaceObservation(
|
||||
tunnel: { name: string; serverId: string },
|
||||
|
||||
@@ -2,4 +2,5 @@ import {test} from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import {fitNetworkMapCamera} from "./network-map-camera"
|
||||
test("camera fits off-world nodes and labels across aspect ratios",()=>{for(const h of [580,1600]){const points=[{x:-200,y:50},{x:1000,y:700}],c=fitNetworkMapCamera(points,1240,h);for(const p of points){assert.ok(p.x>=c.pan.x+119);assert.ok(p.x<=c.pan.x+1240/c.zoom-119);assert.ok(p.y>=c.pan.y+99);assert.ok(p.y<=c.pan.y+h/c.zoom-99)}}})
|
||||
test("camera keeps objects above the bottom overlay band",()=>{const points=[{x:0,y:0},{x:1000,y:600}],c=fitNetworkMapCamera(points,1240,900,.25);for(const p of points)assert.ok(p.y<=c.pan.y+(900*.75)/c.zoom-99)})
|
||||
test("empty/invalid positions and maximum initial zoom",()=>{assert.deepEqual(fitNetworkMapCamera([],1240,580),{pan:{x:0,y:0},zoom:1});assert.deepEqual(fitNetworkMapCamera([{x:NaN,y:1}],1240,580),{pan:{x:0,y:0},zoom:1});assert.equal(fitNetworkMapCamera([{x:1,y:1}],1240,1600).zoom,3)})
|
||||
@@ -1,8 +1,10 @@
|
||||
export interface MapPoint {x:number;y:number}
|
||||
export function fitNetworkMapCamera(points:readonly MapPoint[],width:number,height:number) {
|
||||
/** bottomReserve — доля высоты снизу под панель масштаба и миникарту: объекты вписываются над ней. */
|
||||
export function fitNetworkMapCamera(points:readonly MapPoint[],width:number,height:number,bottomReserve=0) {
|
||||
const valid=points.filter(p=>Number.isFinite(p.x)&&Number.isFinite(p.y))
|
||||
if(!valid.length||width<=0||height<=0)return {pan:{x:0,y:0},zoom:1}
|
||||
const xs=valid.map(p=>p.x),ys=valid.map(p=>p.y),left=Math.min(...xs)-120,right=Math.max(...xs)+120,top=Math.min(...ys)-100,bottom=Math.max(...ys)+100
|
||||
const zoom=Math.max(.2,Math.min(3,width/(right-left),height/(bottom-top)))
|
||||
return {pan:{x:(left+right)/2-width/(2*zoom),y:(top+bottom)/2-height/(2*zoom)},zoom}
|
||||
const usable=height*(1-Math.min(.6,Math.max(0,bottomReserve)))
|
||||
const zoom=Math.max(.2,Math.min(3,width/(right-left),usable/(bottom-top)))
|
||||
return {pan:{x:(left+right)/2-width/(2*zoom),y:(top+bottom)/2-usable/(2*zoom)},zoom}
|
||||
}
|
||||
@@ -73,14 +73,93 @@ const MAX_NODE_Y = H - 44
|
||||
export function mapLinkPath(
|
||||
a: { x: number; y: number }, aHalfW: number,
|
||||
b: { x: number; y: number }, bHalfW: number,
|
||||
): { d: string; x1: number; y1: number; x2: number; y2: number } {
|
||||
): MapLink {
|
||||
if (Math.abs(b.x - a.x) < aHalfW + bHalfW) {
|
||||
const x1 = a.x + aHalfW, x2 = b.x + bHalfW, bend = Math.max(x1, x2) + 48
|
||||
return { d: `M ${x1} ${a.y} C ${bend} ${a.y} ${bend} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y }
|
||||
return { d: `M ${x1} ${a.y} C ${bend} ${a.y} ${bend} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y, cx: bend }
|
||||
}
|
||||
const dir = b.x > a.x ? 1 : -1
|
||||
const x1 = a.x + dir * aHalfW, x2 = b.x - dir * bHalfW, mx = (x1 + x2) / 2
|
||||
return { d: `M ${x1} ${a.y} C ${mx} ${a.y} ${mx} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y }
|
||||
return { d: `M ${x1} ${a.y} C ${mx} ${a.y} ${mx} ${b.y} ${x2} ${b.y}`, x1, y1: a.y, x2, y2: b.y, cx: mx }
|
||||
}
|
||||
|
||||
/** Связь карты: путь и опорные точки кривой (cx — x обеих управляющих точек). */
|
||||
export interface MapLink { d: string; x1: number; y1: number; x2: number; y2: number; cx: number }
|
||||
|
||||
/** Точка кривой связи при параметре t ∈ [0, 1]. */
|
||||
export function mapLinkPoint(l: MapLink, t: number): { x: number; y: number } {
|
||||
const u = 1 - t, a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t
|
||||
return { x: a * l.x1 + (b + c) * l.cx + d * l.x2, y: (a + b) * l.y1 + (c + d) * l.y2 }
|
||||
}
|
||||
|
||||
/** Прямоугольник на холсте (левый верхний угол и размеры). */
|
||||
export interface MapBox { x: number; y: number; w: number; h: number }
|
||||
|
||||
/** Подпись связи макета v3: «таблетка» 20 px, Geist Mono 11 px. */
|
||||
export const MAP_PILL_H = 20
|
||||
export const mapPillWidth = (text: string) => Math.round(text.length * 6.6 + 16)
|
||||
|
||||
const boxesHit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
|
||||
/** Сначала середина кривой (как в макете), затем ближе к концам. */
|
||||
const LABEL_T = [0.5, 0.42, 0.58, 0.34, 0.66, 0.27, 0.73]
|
||||
|
||||
/**
|
||||
* Раскладка подписей связей без наложений: каждая подпись ставится на свою кривую в первое свободное место —
|
||||
* не поверх карточек и других подписей. `texts` — варианты от полного к короткому; если не влезает ни один,
|
||||
* подпись не рисуется (значение остаётся в aria-label связи и в панели деталей).
|
||||
*/
|
||||
export function placeMapLinkLabels<T extends { id: string; link: MapLink; texts: string[] }>(
|
||||
labels: T[],
|
||||
obstacles: MapBox[],
|
||||
gap = 4,
|
||||
): Array<T & { x: number; y: number; w: number; text: string }> {
|
||||
const taken = obstacles.map((o) => ({ x: o.x - gap, y: o.y - gap, w: o.w + gap * 2, h: o.h + gap * 2 }))
|
||||
const out: Array<T & { x: number; y: number; w: number; text: string }> = []
|
||||
for (const label of labels) {
|
||||
search: for (const text of label.texts) {
|
||||
const w = mapPillWidth(text)
|
||||
for (const t of LABEL_T) {
|
||||
const p = mapLinkPoint(label.link, t)
|
||||
const box = { x: p.x - w / 2, y: p.y - MAP_PILL_H / 2, w, h: MAP_PILL_H }
|
||||
if (taken.some((o) => boxesHit(box, o))) continue
|
||||
taken.push({ x: box.x - gap, y: box.y - gap, w: w + gap * 2, h: MAP_PILL_H + gap * 2 })
|
||||
out.push({ ...label, x: Math.round(p.x), y: Math.round(p.y), w, text })
|
||||
break search
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Ленты NetFlow (Sankey) макета v3: толщина — скорость, ленты одного узла уложены стопкой у его края,
|
||||
* без подписей. Самая толстая стопка у узла — `maxPx`.
|
||||
*/
|
||||
export function mapRibbons<T extends { from: { x: number; y: number }; fromHalfW: number; to: { x: number; y: number }; toHalfW: number; bps: number }>(
|
||||
flows: T[],
|
||||
maxPx = 36,
|
||||
): Array<T & { d: string; w: number }> {
|
||||
const key = (p: { x: number; y: number }) => `${Math.round(p.x)},${Math.round(p.y)}`
|
||||
const sum = (m: Map<string, number>, k: string, v: number) => m.set(k, (m.get(k) ?? 0) + v)
|
||||
const outs = new Map<string, number>(), ins = new Map<string, number>()
|
||||
for (const f of flows) { sum(outs, key(f.from), Math.max(0, f.bps)); sum(ins, key(f.to), Math.max(0, f.bps)) }
|
||||
const peak = Math.max(0, ...outs.values(), ...ins.values())
|
||||
const rows = flows.map((f) => ({ f, w: Math.max(1.5, peak > 0 ? (Math.max(0, f.bps) / peak) * maxPx : 1.5), sy: 0, ty: 0 }))
|
||||
const stack = (side: "from" | "to", other: "from" | "to", y: "sy" | "ty") => {
|
||||
const groups = new Map<string, typeof rows>()
|
||||
for (const r of rows) groups.set(key(r.f[side]), [...(groups.get(key(r.f[side])) ?? []), r])
|
||||
for (const group of groups.values()) {
|
||||
group.sort((a, b) => a.f[other].y - b.f[other].y)
|
||||
let cum = group[0].f[side].y - group.reduce((s, r) => s + r.w, 0) / 2
|
||||
for (const r of group) { r[y] = cum + r.w / 2; cum += r.w }
|
||||
}
|
||||
}
|
||||
stack("from", "to", "sy")
|
||||
stack("to", "from", "ty")
|
||||
return rows.map(({ f, w, sy, ty }) => {
|
||||
const x1 = f.from.x + f.fromHalfW, x2 = f.to.x - f.toHalfW, cx = Math.round((x1 + x2) / 2)
|
||||
return { ...f, w: Number(w.toFixed(1)), d: `M ${x1} ${sy.toFixed(1)} C ${cx} ${sy.toFixed(1)} ${cx} ${ty.toFixed(1)} ${x2} ${ty.toFixed(1)}` }
|
||||
})
|
||||
}
|
||||
|
||||
/** Одна горизонтальная «полка» на карте: Home → JH → Exit слева направо. */
|
||||
@@ -831,6 +910,7 @@ function greEndpointAnchor(
|
||||
export interface GreMapEdge {
|
||||
tunnel: GreTunnel
|
||||
peerTunnel?: GreTunnel
|
||||
ambiguousPeerKey?: string
|
||||
from: { x: number; y: number }
|
||||
to: { x: number; y: number }
|
||||
fromServer: Server
|
||||
@@ -880,17 +960,16 @@ export function buildGreMapEdges(
|
||||
if (!a || !b) continue
|
||||
if (a.id === b.id) continue
|
||||
|
||||
const la = layerOfServer(a)
|
||||
const lb = layerOfServer(b)
|
||||
if (la == null || lb == null) continue
|
||||
// EN→EN, JH→JH и т.п. на карте не показываем — только межуровневые рёбра.
|
||||
if (la === lb) continue
|
||||
const aIsIx = a.type === "ix-node", bIsIx = b.type === "ix-node"
|
||||
const la = aIsIx ? roleLayer("EN") : layerOfServer(a)
|
||||
const lb = bIsIx ? roleLayer("EN") : layerOfServer(b)
|
||||
if (la == null || lb == null || la === lb && !aIsIx && !bIsIx) continue
|
||||
|
||||
// Строгий поток слева направо: HR → JH → EN.
|
||||
// Если направление туннеля против иерархии — переворачиваем визуальное ребро.
|
||||
let fromServer = a
|
||||
let toServer = b
|
||||
if (la > lb) {
|
||||
if (la > lb || la === lb && a.id > b.id) {
|
||||
fromServer = b
|
||||
toServer = a
|
||||
}
|
||||
@@ -903,8 +982,11 @@ export function buildGreMapEdges(
|
||||
if (group) group.push(edge)
|
||||
else links.set(key, [edge])
|
||||
}
|
||||
return [...links.values()].flatMap(group => {
|
||||
if (group.length !== 2 || group[0].tunnel.serverId === group[1].tunnel.serverId) return group
|
||||
return [...links.entries()].flatMap(([key, group]) => {
|
||||
if (group.length !== 2 || group[0].tunnel.serverId === group[1].tunnel.serverId) {
|
||||
return group.some(edge => edge.tunnel.serverId !== group[0].tunnel.serverId)
|
||||
? group.map(edge => ({ ...edge, ambiguousPeerKey: key })) : group
|
||||
}
|
||||
const [one, two] = group
|
||||
const [edge, peer] = tunnelPriority(two.tunnel) > tunnelPriority(one.tunnel) ? [two, one] : [one, two]
|
||||
return [{ ...edge, peerTunnel: peer.tunnel }]
|
||||
|
||||
@@ -3,6 +3,7 @@ import assert from "node:assert/strict"
|
||||
import {buildServerResourceMap,greTunnelProbe} from "./network-map-layout"
|
||||
import {mergeGreMetricsWithSpeedProbe} from "./map-gre-speed-probe"
|
||||
import {servers,greTunnels} from "./data"
|
||||
import {scopeMapDestinations} from "./network-map-scope"
|
||||
test("live resources preserve zero, partial poll and unknowns without fake history",()=>{
|
||||
const base={...servers[0],cpuLoad:undefined,totalMemory:undefined,freeMemory:undefined,uptime:undefined,polledAt:undefined}
|
||||
const unknown=buildServerResourceMap([base])[base.id]
|
||||
@@ -19,3 +20,15 @@ test("live GRE does not hash metrics and probe values retain zero and fractions"
|
||||
const merged=mergeGreMetricsWithSpeedProbe({id:"p",srcServerId:"1",dstServerId:"2",lastPingRttMs:0,lastTxAvgMbps:0,lastRxAvgMbps:0.125},fallback)
|
||||
assert.deepEqual(merged,{pingMs:0,dlMbps:0,ulMbps:0.125,hasSpeedMonitor:true})
|
||||
})
|
||||
|
||||
test("a filtered topology does not inherit a service's full-network traffic composition", () => {
|
||||
const service = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 100, bps: 10, share: 1,
|
||||
trafficTypes: [{transport: "UDP", application: "DNS", bytes: 100}], lastBucketAt: "2026-11-26T18:30:00.000Z"}
|
||||
const edges = ["1", "2"].map(fromId => ({fromId, toId: service.id, bytes: 50, bps: 5, bpsFwd: 5, bpsRev: 0}))
|
||||
const partial = scopeMapDestinations([service], edges, [], id => id === "1").services[0]
|
||||
const complete = scopeMapDestinations([service], edges, [], () => true).services[0]
|
||||
assert.equal(partial?.trafficTypes, undefined)
|
||||
assert.equal(partial?.lastBucketAt, undefined)
|
||||
assert.deepEqual(complete?.trafficTypes, service.trafficTypes)
|
||||
assert.equal(complete?.lastBucketAt, service.lastBucketAt)
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { MapBox } from "./network-map-layout"
|
||||
|
||||
type Point = { x: number; y: number }
|
||||
|
||||
/** Routes IPFIX around cards. A missing route leaves the observation available in service details. */
|
||||
export function mapObservationRoute(start: Point, end: Point, boxes: readonly MapBox[], usedTracks: readonly number[]) {
|
||||
if (end.x - start.x < 44) return null
|
||||
const padding = 8
|
||||
const obstacles = boxes.filter(box => box.x + box.w > start.x && box.x < end.x)
|
||||
const first = Math.min(start.x + 20, ...obstacles.map(box => box.x - padding))
|
||||
const last = Math.max(end.x - 20, ...obstacles.map(box => box.x + box.w + padding))
|
||||
if (first <= start.x || last >= end.x || last - first < 34) return null
|
||||
|
||||
const middle = (start.y + end.y) / 2
|
||||
const candidates = [middle, start.y, end.y, ...obstacles.flatMap(box => [box.y - 16, box.y + box.h + 16])]
|
||||
const legal = candidates.flatMap(y => [y, y - 14, y + 14, y - 28, y + 28])
|
||||
.filter(y => obstacles.every(box => y < box.y - padding || y > box.y + box.h + padding))
|
||||
.sort((a, b) => Math.abs(a - middle) - Math.abs(b - middle) || a - b)
|
||||
const y = legal.find(candidate => usedTracks.every(track => Math.abs(candidate - track) >= 18))
|
||||
if (y === undefined) return null
|
||||
|
||||
return {
|
||||
d: `M ${start.x} ${start.y} H ${first} V ${y} H ${last} V ${end.y} H ${end.x}`,
|
||||
marker: { x: (first + last) / 2, y },
|
||||
track: y,
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,10 @@ test("map Flow envelope retains zeros and refuses missing metadata and contradic
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...shorter,sourceWindow:{requestedMinutes:15,effectiveMinutes:2}}))
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...shorter,rangeMinutes:1,windowSec:60}))
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...shorter,windowSec:300}))
|
||||
const recent={...empty,rangeMinutes:1,windowSec:90.125,includesCurrentMinute:true}
|
||||
assert.equal(networkMapFlowSchema.parse(recent).windowSec,90.125)
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...recent,windowSec:120}))
|
||||
assert.throws(()=>networkMapFlowSchema.parse({...recent,includesCurrentMinute:undefined}))
|
||||
})
|
||||
test("map DNS matches exactly requested names and accepts explicit unresolved null",()=>{
|
||||
assert.deepEqual(validateNetworkMapDns({results:{"router.example":null}},["router.example"]),{"router.example":null})
|
||||
|
||||
@@ -27,11 +27,12 @@ export function validateNetworkMapSnapshot(servers:unknown,gre:unknown,probes:un
|
||||
|
||||
import {flowMapHopsDtoSchema} from "@mmapp/contracts/traffic-flow"
|
||||
import {isIpv4String} from "./gre-endpoint-resolve"
|
||||
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true }).refine(data =>
|
||||
(data.sourceWindow
|
||||
? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes
|
||||
: data.rangeMinutes === 5) &&
|
||||
data.windowSec === data.rangeMinutes * 60 &&
|
||||
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true, nodeUsers: true }).refine(data =>
|
||||
(data.includesCurrentMinute
|
||||
? !data.sourceWindow && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120
|
||||
: data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow
|
||||
? data.sourceWindow.requestedMinutes === 5 && data.sourceWindow.effectiveMinutes === data.rangeMinutes
|
||||
: data.rangeMinutes === 5)) &&
|
||||
data.namedBytes <= data.totalBytes && data.unclassifiedBytes <= data.totalBytes
|
||||
)
|
||||
export function validateNetworkMapDns(raw:unknown,hosts:string[]){
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
||||
import type { Server } from "@/lib/data"
|
||||
|
||||
export function isolatedIxServers(servers: Pick<Server, "id" | "type">[], links: readonly (readonly [string, string])[]) {
|
||||
const neighbors = new Map<string, string[]>()
|
||||
for (const [from, to] of links) {
|
||||
neighbors.set(from, [...(neighbors.get(from) ?? []), to])
|
||||
neighbors.set(to, [...(neighbors.get(to) ?? []), from])
|
||||
}
|
||||
const connected = new Set(servers.filter(server => server.type === "jump-host" || server.type === "exit-node").map(server => server.id))
|
||||
for (const id of connected) for (const neighbor of neighbors.get(id) ?? []) connected.add(neighbor)
|
||||
return new Set(servers.filter(server => server.type === "ix-node" && !connected.has(server.id)).map(server => server.id))
|
||||
}
|
||||
|
||||
export function scopeMapDestinations(
|
||||
services: FlowMapService[], edges: FlowMapServiceEdge[], paths: FlowMapServicePath[],
|
||||
includes: (id: string) => boolean, userId?: string, retainUnassigned = false,
|
||||
) {
|
||||
const visiblePaths = paths.filter(path => includes(path.enId || path.viaId) && (!userId || path.clientId === userId))
|
||||
const visibleEdges = userId ? [] : edges.filter(edge => includes(edge.fromId))
|
||||
if (userId) {
|
||||
const bySource = new Map<string, FlowMapServiceEdge>()
|
||||
for (const path of visiblePaths) {
|
||||
const fromId = path.enId || path.viaId
|
||||
const key = JSON.stringify([fromId, path.serviceId, Boolean(path.enId)])
|
||||
const edge = bySource.get(key) ?? {
|
||||
fromId, toId: path.serviceId, bytes: 0, bps: 0, bpsFwd: 0, bpsRev: 0,
|
||||
...(path.enId ? {} : { observedOnly: true as const }),
|
||||
}
|
||||
edge.bytes += path.bytes
|
||||
edge.bps += path.bps
|
||||
bySource.set(key, edge)
|
||||
}
|
||||
visibleEdges.push(...bySource.values())
|
||||
}
|
||||
const totals = new Map<string, { bytes: number; bps: number }>()
|
||||
const allByService = new Map<string, number>()
|
||||
if (retainUnassigned) for (const edge of edges) allByService.set(edge.toId, (allByService.get(edge.toId) ?? 0) + edge.bytes)
|
||||
let bytes = 0
|
||||
for (const edge of visibleEdges) {
|
||||
const total = totals.get(edge.toId) ?? { bytes: 0, bps: 0 }
|
||||
total.bytes += edge.bytes
|
||||
total.bps += edge.bps
|
||||
bytes += edge.bytes
|
||||
totals.set(edge.toId, total)
|
||||
}
|
||||
if (retainUnassigned) for (const service of services) {
|
||||
const unassigned = service.bytes - (allByService.get(service.id) ?? 0)
|
||||
if (unassigned <= 0) continue
|
||||
const total = totals.get(service.id) ?? { bytes: 0, bps: 0 }
|
||||
total.bytes += unassigned
|
||||
total.bps += service.bps * unassigned / service.bytes
|
||||
bytes += unassigned
|
||||
totals.set(service.id, total)
|
||||
}
|
||||
return {
|
||||
services: services.flatMap(service => {
|
||||
const total = totals.get(service.id)
|
||||
if (!total) return []
|
||||
const { trafficTypes, serviceEvidence, lastBucketAt, ...destination } = service
|
||||
return [{ ...destination, ...total, share: bytes ? total.bytes / bytes : 0,
|
||||
...(total.bytes === service.bytes ? { trafficTypes, serviceEvidence, lastBucketAt } : {}) }]
|
||||
}).sort((a, b) => b.bytes - a.bytes || a.label.localeCompare(b.label)),
|
||||
edges: visibleEdges,
|
||||
paths: visiblePaths,
|
||||
}
|
||||
}
|
||||
@@ -215,8 +215,8 @@ export const flowEntityCardSchema = z.object({
|
||||
site: z.string(),
|
||||
country: z.string(),
|
||||
status: z.enum(["online", "offline", "degraded"]),
|
||||
rxNow: z.number(),
|
||||
txNow: z.number(),
|
||||
rxNow: z.number().nullable(),
|
||||
txNow: z.number().nullable(),
|
||||
sessions: z.number().int().nonnegative(),
|
||||
rxSeries: z.array(z.number()),
|
||||
txSeries: z.array(z.number()),
|
||||
@@ -366,6 +366,9 @@ export const flowMapHopDtoSchema = z.object({
|
||||
bpsRev: z.number().nonnegative(),
|
||||
})
|
||||
|
||||
export const flowServiceBasisSchema = z.enum(["catalog", "network", "heuristic", "port", "unknown"])
|
||||
export type FlowServiceBasis = z.infer<typeof flowServiceBasisSchema>
|
||||
|
||||
export const flowMapServiceDtoSchema = z.object({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
@@ -373,6 +376,16 @@ export const flowMapServiceDtoSchema = z.object({
|
||||
bytes: z.number().nonnegative(),
|
||||
bps: z.number().nonnegative(),
|
||||
share: z.number().min(0).max(1),
|
||||
lastBucketAt: z.string().datetime().optional(),
|
||||
trafficTypes: z.array(z.object({
|
||||
transport: z.string(),
|
||||
application: z.string().nullable(),
|
||||
bytes: z.number().positive(),
|
||||
})).max(5).optional(),
|
||||
serviceEvidence: z.array(z.object({
|
||||
basis: flowServiceBasisSchema,
|
||||
bytes: z.number().positive(),
|
||||
})).max(flowServiceBasisSchema.options.length).optional(),
|
||||
})
|
||||
|
||||
export const flowMapServiceEdgeDtoSchema = z.object({
|
||||
@@ -388,6 +401,7 @@ export const flowMapServiceEdgeDtoSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
})).optional(),
|
||||
observedOnly: z.literal(true).optional(),
|
||||
})
|
||||
|
||||
export const flowMapServicePathDtoSchema = z.object({
|
||||
@@ -395,6 +409,8 @@ export const flowMapServicePathDtoSchema = z.object({
|
||||
clientName: z.string(),
|
||||
viaId: z.string(),
|
||||
viaName: z.string(),
|
||||
viaIface: z.string().optional(),
|
||||
/** Empty when IPFIX identified the exporter but the exit could not be inferred. */
|
||||
enId: z.string(),
|
||||
enName: z.string(),
|
||||
serviceId: z.string(),
|
||||
@@ -412,6 +428,13 @@ export const flowMapCountryServiceGroupDtoSchema = z.object({
|
||||
|
||||
export const flowMapHopsDtoSchema = z.object({
|
||||
sourceWindow: flowSourceWindowSchema.optional(),
|
||||
nodeUsers: z.record(z.string(), z.array(z.object({
|
||||
clientId: z.string(),
|
||||
clientName: z.string(),
|
||||
bytes: z.number().nonnegative(),
|
||||
bps: z.number().nonnegative(),
|
||||
}))).optional(),
|
||||
includesCurrentMinute: z.literal(true).optional(),
|
||||
/** Link counters include private routed payload. Mesh visibility applies to the inferred graph. */
|
||||
interfaceTraffic: z.array(z.object({
|
||||
serverId: z.string(), iface: z.string(),
|
||||
@@ -462,3 +485,4 @@ export type FlowMapServicePath = z.infer<typeof flowMapServicePathDtoSchema>
|
||||
export type FlowMapCountryServiceGroup = z.infer<typeof flowMapCountryServiceGroupDtoSchema>
|
||||
export type FlowMapHopsDto = z.infer<typeof flowMapHopsDtoSchema>
|
||||
export type FlowMapInterfaceTraffic = NonNullable<FlowMapHopsDto["interfaceTraffic"]>[number]
|
||||
export type FlowMapUser = NonNullable<FlowMapHopsDto["nodeUsers"]>[string][number]
|
||||
@@ -133,6 +133,7 @@ export async function getFlowMapHops(
|
||||
excludeMesh?: boolean
|
||||
excludeOverlay?: boolean
|
||||
} = {},
|
||||
init?: RequestInit,
|
||||
): Promise<FlowMapHopsDto> {
|
||||
return requestJson<FlowMapHopsDto>(baseUrl, `/api/traffic/flow/map-hops${flowQuery({
|
||||
range: params.range ?? "5m",
|
||||
@@ -142,7 +143,7 @@ export async function getFlowMapHops(
|
||||
dedup: params.dedup,
|
||||
excludeMesh: params.excludeMesh,
|
||||
excludeOverlay: params.excludeOverlay,
|
||||
})}`)
|
||||
})}`, init)
|
||||
}
|
||||
|
||||
export async function getFlowAnalytics(
|
||||
@@ -156,8 +157,9 @@ export async function getFlowAnalytics(
|
||||
excludeMesh?: boolean
|
||||
excludeOverlay?: boolean
|
||||
},
|
||||
init?: RequestInit,
|
||||
): Promise<FlowAnalyticsDto> {
|
||||
return flowConfirmed(flowAnalyticsSchema, await requestJson<unknown>(baseUrl, `/api/traffic/flow/analytics${flowQuery(params)}`))
|
||||
return flowConfirmed(flowAnalyticsSchema, await requestJson<unknown>(baseUrl, `/api/traffic/flow/analytics${flowQuery(params)}`, init))
|
||||
}
|
||||
|
||||
export async function getFlowMonthly(
|
||||
|
||||
@@ -20,14 +20,14 @@ for(const theme of ["dark","light"])for(const width of [320,1440])for(const path
|
||||
})
|
||||
test("Shell keyboard skip link moves focus to main and menus restore focus",async({page})=>{
|
||||
await setup(page,"dark");await page.goto("/releases");await expect(page.getByText("Текущая версия",{exact:true})).toBeVisible();await page.keyboard.press("Tab");const skip=page.getByRole("link",{name:"К содержимому",exact:true});await expect(skip).toBeFocused();await page.keyboard.press("Enter");await expect(page.locator("#main-content")).toBeFocused()
|
||||
const apps=page.getByRole("button",{name:"Приложения",exact:true});await apps.focus();await page.keyboard.press("Enter");await expect(page.getByRole("menu")).toBeVisible();await page.keyboard.press("Escape");await expect(apps).toBeFocused()
|
||||
const monitor=page.getByRole("button",{name:"Монитор системы",exact:true});await monitor.focus();await page.keyboard.press("Enter");await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.keyboard.press("Escape");await expect(monitor).toBeFocused()
|
||||
const apps=page.getByRole("button",{name:/^Переключатель приложений/});await apps.focus();await page.keyboard.press("Enter");await expect(page.getByRole("menu")).toBeVisible();await page.keyboard.press("Escape");await expect(apps).toBeFocused()
|
||||
const monitor=page.getByRole("button",{name:/^Состояние системы/});await monitor.focus();await page.keyboard.press("Enter");await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.keyboard.press("Escape");await expect(monitor).toBeFocused()
|
||||
})
|
||||
test("System monitor recognizes confirmed legacy health consistently",async({page})=>{await setup(page,"dark");await page.route("**/health",r=>r.fulfill({json:{ok:true}}));await page.goto("/releases");await expect(page.getByRole("button",{name:"Монитор системы",exact:true})).toContainText("API доступен")})
|
||||
test("System monitor recognizes confirmed legacy health consistently",async({page})=>{await setup(page,"dark");await page.route("**/health",r=>r.fulfill({json:{ok:true}}));await page.goto("/releases");await expect(page.getByRole("button",{name:/^Состояние системы/})).toContainText("Норма")})
|
||||
|
||||
for(const theme of ["dark","light"])for(const width of [320,1440])test("Open shell layers audit/"+theme+"/"+width,async({page},info)=>{
|
||||
await setup(page,theme);await page.setViewportSize({width,height:900});await page.goto("/releases");await expect(page.getByRole("button",{name:"Монитор системы",exact:true})).toContainText("API доступен");await page.getByRole("button",{name:"Монитор системы",exact:true}).click();await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.addScriptTag({content:axe.source});
|
||||
await setup(page,theme);await page.setViewportSize({width,height:900});await page.goto("/releases");await expect(page.getByRole("button",{name:/^Состояние системы/})).toContainText("Норма");await page.getByRole("button",{name:/^Состояние системы/}).click();await expect(page.locator('[data-slot="popover-content"]')).toBeVisible();await page.addScriptTag({content:axe.source});
|
||||
const result=await page.evaluate(async()=>{const engine=(window as unknown as {axe:typeof axe}).axe;return engine.run('[data-slot="popover-content"]',{runOnly:{type:"tag",values:["wcag2a","wcag2aa","wcag21a","wcag21aa","wcag22aa"]}})});await info.attach("axe-open-monitor",{body:JSON.stringify(result,null,2),contentType:"application/json"});expect(result.violations.map(v=>({id:v.id,nodes:v.nodes.map(n=>({target:n.target,html:n.html,summary:n.failureSummary}))}))).toEqual([]);
|
||||
await page.screenshot({path:"docs/ux-ui/screens/shell-monitor-"+theme+"-"+width+".png",animations:"disabled"});await page.keyboard.press("Escape");await page.getByRole("button",{name:"Приложения",exact:true}).click();await expect(page.getByRole("menu")).toBeVisible();await settleAnimations(page);const menu=await page.evaluate(async()=>{const engine=(window as unknown as {axe:typeof axe}).axe;return engine.run('[role="menu"]',{runOnly:{type:"tag",values:["wcag2a","wcag2aa","wcag21a","wcag21aa","wcag22aa"]}})});expect(menu.violations.map(v=>({id:v.id,nodes:v.nodes.map(n=>({target:n.target,html:n.html,summary:n.failureSummary}))}))).toEqual([]);
|
||||
await page.screenshot({path:"docs/ux-ui/screens/shell-monitor-"+theme+"-"+width+".png",animations:"disabled"});await page.keyboard.press("Escape");if(width<768)await page.getByRole("button",{name:"Боковое меню",exact:true}).click();await page.getByRole("button",{name:/^Переключатель приложений/}).click();await expect(page.getByRole("menu")).toBeVisible();await settleAnimations(page);const menu=await page.evaluate(async()=>{const engine=(window as unknown as {axe:typeof axe}).axe;return engine.run('[role="menu"]',{runOnly:{type:"tag",values:["wcag2a","wcag2aa","wcag21a","wcag21aa","wcag22aa"]}})});expect(menu.violations.map(v=>({id:v.id,nodes:v.nodes.map(n=>({target:n.target,html:n.html,summary:n.failureSummary}))}))).toEqual([]);
|
||||
})
|
||||
for(const theme of ["dark","light"])test("Unconfirmed health remains unavailable/"+theme,async({page})=>{await setup(page,theme);await page.route("**/health",r=>r.fulfill({json:{ok:false,status:"unknown"}}));await page.goto("/releases");await expect(page.getByRole("button",{name:"Монитор системы",exact:true})).toContainText("Нет связи")})
|
||||
for(const theme of ["dark","light"])test("Unconfirmed health remains unavailable/"+theme,async({page})=>{await setup(page,theme);await page.route("**/health",r=>r.fulfill({json:{ok:false,status:"unknown"}}));await page.goto("/releases");await expect(page.getByRole("button",{name:/^Состояние системы/})).toContainText("Сбой")})
|
||||
@@ -31,7 +31,7 @@ test("поиск страниц: одинаковые названия, сино
|
||||
for (const item of navigationItems) {
|
||||
await expect(sidebar.locator(`a[href="${item.url}"]`)).toContainText(item.title)
|
||||
}
|
||||
const opener = page.getByRole("button", { name: "Приложения", exact: true })
|
||||
const opener = page.getByRole("button", { name: "Источники и свежесть данных", exact: true })
|
||||
await opener.focus()
|
||||
await page.keyboard.press("Control+k")
|
||||
const dialog = page.getByRole("dialog", { name: "Поиск страниц", exact: true })
|
||||
|
||||
@@ -13,7 +13,7 @@ for(const change of ["backend","mode"])for(const part of ["snapshot","flow","dns
|
||||
})
|
||||
await page.goto("/settings");await page.getByRole("link",{name:/^Карта сети/}).click()
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Прежняя карта",{exact:true})).toBeVisible()
|
||||
await expect(page.getByText(/NetFlow · 5 мин · ответ/)).toBeVisible()
|
||||
await expect(page.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible()
|
||||
const path=part==="snapshot"?"/api/servers":part==="flow"?"/api/traffic/flow/map-hops":"/api/network/resolve-hosts"
|
||||
await page.route("**/api/**",async r=>{
|
||||
const u=new URL(r.request().url());if(u.port!=="8000"||u.pathname!==path||started)return r.fallback()
|
||||
@@ -25,8 +25,8 @@ for(const change of ["backend","mode"])for(const part of ["snapshot","flow","dns
|
||||
if(change==="backend"){const input=page.getByPlaceholder("http://localhost:8000");await input.fill("http://localhost:8101");await input.press("Enter")}
|
||||
else await page.getByRole("button",{name:"Моковые",exact:true}).click()
|
||||
await page.getByRole("link",{name:/^Карта сети/}).click()
|
||||
if(change==="backend"){await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Новая карта",{exact:true})).toBeVisible();await expect(page.getByText(/NetFlow · 5 мин · ответ/)).toBeVisible()}
|
||||
else await expect(page.getByText("Демо · mock",{exact:true})).toBeVisible()
|
||||
if(change==="backend"){await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Новая карта",{exact:true})).toBeVisible();await expect(page.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible()}
|
||||
else await expect(page.getByText("Демонстрационные данные",{exact:true})).toBeVisible()
|
||||
const before=newReads;release();await expect.poll(()=>completed).toBe(true)
|
||||
await page.evaluate(()=>new Promise<void>(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))))
|
||||
await expect(page.getByText("Старая ошибка карты",{exact:false})).toHaveCount(0)
|
||||
|
||||
@@ -9,7 +9,6 @@ test("Карта: PostgreSQL даты не скрывают JumpHost и Exit Nod
|
||||
const map=page.getByRole("group",{name:"Интерактивная карта сети"})
|
||||
await expect(map.getByText("Узел JH",{exact:true})).toBeVisible()
|
||||
await expect(map.getByText("Узел EN",{exact:true})).toBeVisible()
|
||||
await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
|
||||
await expect(page.getByRole("alert").filter({hasText:"Первоначальная загрузка карты"})).toHaveCount(0)
|
||||
})
|
||||
for(const part of ["servers","gre","probes"] as const)for(const malformed of [false,true])test("Карта: первоначальный отказ и повтор "+part+"/"+malformed,async({page})=>{
|
||||
@@ -28,10 +27,10 @@ for(const part of ["servers","gre","probes"] as const)test("Карта: част
|
||||
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill(failing&&p===paths[part]?{status:503,json:{error:"Источник недоступен"}}:{json:body(p,failing?"Новый роутер":"Последний роутер")})})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Последний роутер",{exact:true})).toBeVisible()
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByRole("button",{name:"Устройство Последний роутер",exact:true})).toBeVisible()
|
||||
failing=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByRole("alert").filter({hasText:"Последний полный снимок"})).toBeVisible()
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Последний роутер",{exact:true})).toBeVisible()
|
||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByRole("button",{name:"Устройство Последний роутер",exact:true})).toBeVisible()
|
||||
await expect(page.getByText("Новый роутер",{exact:true})).toHaveCount(0)
|
||||
})
|
||||
|
||||
@@ -39,8 +38,10 @@ test("Карта: неизвестный статус не становится
|
||||
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;const data=body(p);return r.fulfill({json:p===paths.servers?[{...(data as object[])[0],status:null}]:data})})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.getByText("1 неизвестно",{exact:true})).toBeVisible()
|
||||
await page.getByText("Сводка сети", {exact:true}).click()
|
||||
await expect(page.getByRole("button",{name:"Неизвестно 1",exact:true})).toBeVisible()
|
||||
await expect(page.getByRole("button",{name:"Оффлайн 0",exact:true})).toBeVisible()
|
||||
await page.keyboard.press("Escape")
|
||||
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click()
|
||||
await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
|
||||
await page.getByRole("button",{name:/^Фильтр/}).click();await page.getByRole("button",{name:"Неизвестно",exact:true}).click()
|
||||
@@ -52,8 +53,9 @@ for(const polled of [false,true])test("Карта: реальные и неиз
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;const data=body(p);return r.fulfill({json:p===paths.servers?[{...(data as object[])[0],...(polled?{cpuLoad:0,totalMemory:1048576,freeMemory:1048576,uptime:"0s",polledAt:"2020-01-01T00:00:00Z"}:{})}]:data})})
|
||||
await page.goto("/network-map");await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click()
|
||||
const panel=page.getByText("Ресурсы",{exact:true}).locator("..")
|
||||
await panel.locator("summary").click()
|
||||
await expect(panel.getByText("История CPU и диск API не передаются.",{exact:false})).toBeVisible()
|
||||
await expect(panel.locator("svg")).toHaveCount(0)
|
||||
await expect(panel.locator("svg polyline")).toHaveCount(0)
|
||||
await expect(panel.getByText("HDD",{exact:true})).toBeVisible()
|
||||
await expect(panel.getByText("— / —",{exact:true})).toHaveCount(polled?1:2)
|
||||
if(polled){await expect(panel.getByText("0%",{exact:true})).toBeVisible();await expect(panel.getByText("0 МБ / 1 МБ",{exact:true})).toBeVisible();await expect(panel.getByText("0м",{exact:true})).toBeVisible()}
|
||||
|
||||
@@ -9,15 +9,21 @@ test("Карта: открытые детали обновляются вмес
|
||||
let changed=false
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...jh,name:changed?"Новый Jump":"Jump",status:changed?null:"online",cpuLoad:changed?0:20}]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map");await page.getByRole("button",{name:"Устройство Jump",exact:true}).click()
|
||||
await expect(page.getByText("20%",{exact:true})).toBeVisible()
|
||||
const metrics=page.getByText("CPU · RAM",{exact:true}).locator("..")
|
||||
await expect(metrics).toContainText("20% · —")
|
||||
await page.getByText("Ресурсы",{exact:true}).click()
|
||||
const sessions=page.getByText("Сессий",{exact:true}).locator("..");await expect(sessions).toHaveText("Сессий—")
|
||||
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByText("0%",{exact:true})).toBeVisible();await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
|
||||
await expect(metrics).toContainText("0% · —");await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
|
||||
await expect(page.getByText("Jump",{exact:true})).toHaveCount(0);await expect(page.getByText("Новый Jump",{exact:true}).last()).toBeVisible()
|
||||
})
|
||||
test("Карта: модель WAN не утверждает активный маршрут и RTT линии",async({page})=>{
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[home,jh]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map");await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible()
|
||||
await page.goto("/network-map")
|
||||
const legend = page.getByRole("button", {name:"Легенда",exact:true})
|
||||
await legend.click()
|
||||
await expect(page.getByText("WAN → JH · модель связности",{exact:true})).toBeVisible()
|
||||
await legend.click()
|
||||
await expect(page.locator("svg text").filter({hasText:/^5 мс$/})).toHaveCount(0)
|
||||
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click()
|
||||
await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click();await expect(page.getByText("Аплинк каталога",{exact:true})).toBeVisible();await expect(page.getByText("Модель связей с JH · Ping модели",{exact:true})).toBeVisible()
|
||||
@@ -31,7 +37,7 @@ test("Карта: выбранный GRE обновляется и неизве
|
||||
await expect(page.getByText("gre-home",{exact:true}).last()).toBeVisible();await expect(page.getByText("Ping неизвестен",{exact:true})).toBeVisible()
|
||||
changed=true;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByText("gre-new",{exact:true}).last()).toBeVisible();await expect(page.getByText("Недоступен",{exact:true})).toBeVisible()
|
||||
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1");await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:/^GRE/}).click();await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click();await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:/^GRE/}).click();await expect(page.getByText("IPsec неизвестен",{exact:true})).toBeVisible()
|
||||
})
|
||||
|
||||
test("Карта: GRE сохраняет частичное измерение, ноль Ping и дату пробы",async({page})=>{
|
||||
@@ -44,3 +50,72 @@ test("Карта: GRE сохраняет частичное измерение,
|
||||
await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("2020")
|
||||
await expect(page.getByText("Проба measured-probe",{exact:false}).last()).toContainText("время TX/RX неизвестно")
|
||||
})
|
||||
|
||||
test("Карточки Exit, JumpHost и сервиса показывают измерения и обрабатывают действия", async ({ page }, info) => {
|
||||
const exit = { ...jh, id: 3, type: "exit-node", name: "fra-exit02", host: "fra-exit02.rtnt.top", country: "DE", latency: 31, cpuLoad: 18, uptime: "23d9h", totalMemory: 100, freeMemory: 64, os: "7.16.1", polledAt: "2026-11-25T09:02:11Z" }
|
||||
const jump = { ...exit, id: 2, name: "nov-gw01", host: "nov-gw01.rtnt.top", type: "jump-host", status: "degraded", country: "RU" }
|
||||
const service = { id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 0.29 }
|
||||
const edge = { fromId: "3", toId: service.id, bytes: service.bytes, bps: service.bps, bpsFwd: 8000, bpsRev: 16000 }
|
||||
const path = { clientId: "u1", clientName: "msk-hr01", viaId: "2", viaName: jump.name, enId: "3", enName: exit.name, serviceId: service.id, bytes: edge.bytes, bps: edge.bps }
|
||||
const record = {serverId:"3",serverName:exit.name,src:"10.20.4.18",dst:"142.250.74.14",proto:6,protoName:"TCP",srcPort:45000,dstPort:443,bytes:1000,packets:1,bps:8000,inIface:"gre1",service:"YouTube",dstAsn:15169}
|
||||
const country = {...service, id:"cc:other", label:"Прочее", category:"Страна"}
|
||||
const dns = {...service, id:"cc:other|svc:dns", label:"DNS", category:"DNS"}
|
||||
const rows = [13,17,15,27,51,55,48,33,16,12,15,18]
|
||||
const sample = { rxNow: 15, txNow: 12, rxPeak: 55, txPeak: 55, rxTotal: 1, txTotal: 1, rxSeries: rows, txSeries: rows, observations: { rxNow: true, txNow: true, rxSeries: rows.map(() => true), txSeries: rows.map(() => true), sampledAt: "2026-11-25T09:02:11Z" } }
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url()), endpoint = url.pathname
|
||||
const daily = url.searchParams.get("range") === "24h"
|
||||
const data = endpoint === "/api/servers" ? [exit, jump]
|
||||
: endpoint === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] }
|
||||
: endpoint === "/api/uptime/speed-probes" ? {probes: []}
|
||||
: endpoint === "/api/traffic/flow/map-hops" ? {...empty,rangeMinutes:daily?1440:5,windowSec:daily?86400:300,totalBytes:daily?4100000000:3103448,namedBytes:daily?4100000000:service.bytes,services:[{...service,bytes:daily?4100000000:service.bytes}],servicePaths:[path],serviceEdges:[edge],countries:[country],countryServiceGroups:[{countryId:country.id,services:[dns],paths:[{...path,serviceId:dns.id,bytes:100000,bps:100000*8/300}],edges:[]}]}
|
||||
: endpoint === "/api/traffic/flow/analytics" ? {bpsNow:8000,bytes:1000,packets:1,conversations:3,uniqueSrc:1,uniqueDst:3,topProto:"TCP",rxSeries:[],txSeries:[],applications:[],protocols:[],sources:[],destinations:[],interfaces:[],conversationsList:[record,...["unknown","US"].map(dstCountry=>({...record,service:"Прочее",category:"DNS",dstCountry,dst:dstCountry==="US"?"192.0.2.53":"198.51.100.53",dstPort:53}))],ifaces:[],live:true}
|
||||
: endpoint === "/api/traffic/servers/3" ? {server:{...sample,id:"3"}}
|
||||
: endpoint === "/api/traffic/servers/2" ? {server:{...sample,id:"2",observations:{...sample.observations,currentState:"error",error:"RouterOS API 401 на /interface",lastAttemptAt:"2026-11-25T09:31:08Z"}}}
|
||||
: endpoint === "/api/auth/config" ? {required:false} : {}
|
||||
return route.fulfill({json:data})
|
||||
})
|
||||
await page.goto("/network-map?server=3")
|
||||
const card = page.getByRole("complementary",{name:"Детали объекта карты"})
|
||||
await expect(card.getByRole("img",{name:"История измерений"})).toBeVisible()
|
||||
await card.getByRole("button",{name:"Закрепить",exact:true}).click()
|
||||
await expect(card.getByText("Закреплён",{exact:true}).locator("..")).toContainText("да")
|
||||
await card.getByRole("button",{name:"Открепить",exact:true}).click()
|
||||
await card.screenshot({path:info.outputPath("exit.png")})
|
||||
await card.getByRole("button",{name:/YouTube/}).click()
|
||||
await expect(card.getByText("Объём · 24 ч",{exact:true}).locator("..")).toContainText("4.10 ГБ")
|
||||
await expect(card.getByText("10.20.4.18 → 142.250.74.14",{exact:true})).toBeVisible()
|
||||
await expect(card.getByText("TCP/443",{exact:true})).toBeVisible()
|
||||
await card.screenshot({path:info.outputPath("service.png")})
|
||||
await card.getByRole("button",{name:"Фильтр по сервису"}).click()
|
||||
await expect(page.getByText(/фильтр: YouTube/)).toBeVisible()
|
||||
await card.getByRole("button",{name:"Снять фильтр"}).click()
|
||||
await page.goto("/network-map?server=2")
|
||||
await expect(card.getByText(/RouterOS API 401 на \/interface/)).toBeVisible()
|
||||
await card.screenshot({path:info.outputPath("jump.png")})
|
||||
await card.getByRole("button",{name:/fra-exit02/}).click()
|
||||
await expect(card.getByRole("heading",{name:exit.name})).toBeVisible()
|
||||
await page.getByRole("button",{name:"Страны",exact:true}).click()
|
||||
await page.getByRole("button",{name:"Страна Прочее",exact:true}).press("Enter")
|
||||
await card.getByRole("button",{name:/DNS/}).click()
|
||||
await expect(card.getByText("Выход не определён", {exact:true})).toBeVisible()
|
||||
await expect(card.getByText(/198\.51\.100\.53/)).toBeVisible()
|
||||
await expect(card.getByText(/192\.0\.2\.53/)).toHaveCount(0)
|
||||
})
|
||||
|
||||
test("Обновление NetFlow отображается внутри кнопки", async ({page}) => {
|
||||
let release!: () => void
|
||||
const wait = new Promise<void>(resolve => { release = resolve })
|
||||
await page.route("**/api/**", async route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
if (path === "/api/traffic/flow/map-hops") await wait
|
||||
return route.fulfill({json:path === "/api/traffic/flow/map-hops" ? empty : path === "/api/servers" ? [jh] : path === "/api/filters/gre-tunnels" ? {tunnels:[],failures:[]} : path === "/api/uptime/speed-probes" ? {probes:[]} : path === "/api/auth/config" ? {required:false} : {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const refresh = page.getByRole("button",{name:"Обновить",exact:true})
|
||||
await expect(refresh.locator("[data-slot=spinner]")).toBeVisible()
|
||||
await expect(page.getByText("Обновление NetFlow…",{exact:true})).toHaveCount(0)
|
||||
release()
|
||||
await expect(refresh).toBeEnabled()
|
||||
await expect(refresh.locator("[data-slot=spinner]")).toHaveCount(0)
|
||||
})
|
||||
@@ -1,15 +1,86 @@
|
||||
import {test,expect} from "@playwright/test"
|
||||
import { installOpenLiveStream } from "./live-stream-fixture"
|
||||
import { observedTrafficFixturePayload } from "./traffic-observation-fixture"
|
||||
const empty={"hops":[],"live":false,"rangeMinutes":5,"windowSec":300,"totalBytes":0,"namedBytes":0,"unclassifiedBytes":0,"asnLoaded":false,"countryLoaded":false,"services":[],"serviceEdges":[],"servicePaths":[],"countries":[],"countryEdges":[],"countryPaths":[],"countryServiceGroups":[],"mapServiceMinSharePct":5,"dedupApplied":false,"excludeMeshApplied":false,"excludeOverlayApplied":false}
|
||||
const flowPath="/api/traffic/flow/map-hops"
|
||||
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
|
||||
const server={id:1,name:"Router",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online"}
|
||||
|
||||
test("Карта и трафик сохраняют пользователя и сервис, IX остаётся отдельным", async ({page}) => {
|
||||
const clientId = "alice"
|
||||
const timestamps = { createdAt: "2026-11-26T12:00:00Z", updatedAt: "2026-11-26T12:00:00Z" }
|
||||
const binding = { ...timestamps, userId: clientId, id: "a1", serverId: 1,
|
||||
serverName: "Вход", serverSite: "MSK", serverCountry: "RU", interfaceName: "gre-alice", interfaceType: "gre", comment: "" }
|
||||
const user = { ...timestamps, id: clientId, name: "Алиса", login: "alice", email: "[email protected]", role: "viewer", active: true,
|
||||
avatar: "A", lastSeen: null, sections: [], servers: [], bindings: [binding, {...binding, id: "a2", interfaceName: "gre-alice-2"}] }
|
||||
const counters = ["a1", "a2"].map(bindingId => ({bindingId, status: "online", rxNow: 4, txNow: 6, rxPeak: 4, txPeak: 6, rxTotal: 0, txTotal: 0, rxSeries: [4], txSeries: [6]}))
|
||||
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1}
|
||||
const path = {clientId, clientName: "Алиса", viaId: "1", viaName: "Вход", enId: "", enName: "", serviceId: dns.id, bytes: dns.bytes, bps: dns.bps}
|
||||
const requests: string[] = []
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url())
|
||||
requests.push(url.pathname + url.search)
|
||||
const clientCard = { id: clientId, name: "Алиса", subtitle: "alice", site: "MSK", country: "RU", status: "online", rxNow: 0, txNow: 0, sessions: 1, bytes: dns.bytes, rxSeries: [], txSeries: [] }
|
||||
const replies: Record<string, unknown> = {
|
||||
"/api/auth/config": {required: false},
|
||||
"/api/servers": [{...server, name: "Вход", type: "jump-host"}, {...server, id: 9, name: "Изолированный IX", host: "192.0.2.9", type: "ix-node"}],
|
||||
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
|
||||
"/api/ix/topology": {links: []}, "/api/ix/segments": {items: [{id: "segment", appliedRevision: 1}]},
|
||||
"/api/ix/segments/segment/linux": {items: [{serverId: 9, interfaceName: "wg-linux", kind: "wireguard", name: "Linux VPS", enabled: true}]},
|
||||
"/api/users": {users: [user]},
|
||||
[`/api/traffic/users/${clientId}`]: observedTrafficFixturePayload({user: {...counters[0], rxNow: 8, txNow: 12, interfaces: counters}}),
|
||||
"/api/traffic/flow/exporters": {exporters: []}, "/api/traffic/flow/clients": {clients: [clientCard]},
|
||||
"/api/traffic/flows": {exportersOnline: 0, bytesPerMin: 0, uniqueSrc: 0, uniqueDst: 0, topProto: "TCP", talkers: [], listenerBound: true},
|
||||
[flowPath]: {...empty, totalBytes: dns.bytes, namedBytes: dns.bytes, services: [dns], servicePaths: [path],
|
||||
serviceEdges: [{fromId: "1", toId: dns.id, observedOnly: true, bytes: dns.bytes, bps: dns.bps, bpsFwd: 0, bpsRev: dns.bps}]},
|
||||
}
|
||||
return route.fulfill({json: replies[url.pathname] ?? {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const map = page.getByRole("group", {name: "Интерактивная карта сети"})
|
||||
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
|
||||
await expect(page.getByRole("button", {name: "Выбрать пользователя", exact: true})).toBeVisible()
|
||||
await expect(map.getByRole("button", {name: "Устройство Изолированный IX"})).toHaveCount(0)
|
||||
await map.getByRole("button", {name: "Сервис DNS", exact: true}).press("Enter")
|
||||
await panel.getByRole("button", {name: "Фильтр по сервису"}).click()
|
||||
await page.getByRole("button", {name: "Пользователи", exact: true}).click()
|
||||
await page.getByRole("combobox", {name: "Поиск пользователей"}).fill("Вход")
|
||||
await expect(page.getByRole("option", {name:/Алиса.*Вход/})).toBeVisible()
|
||||
await page.getByRole("option", {name: /Алиса/}).click()
|
||||
await expect.poll(() => requests.some(request => request === `${flowPath}?range=1m&userId=${clientId}`)).toBe(true)
|
||||
await expect(panel.getByRole("heading", {name: "Алиса", exact: true})).toBeVisible()
|
||||
await expect(panel.getByText(/gre-alice · gre, gre-alice-2/)).toBeVisible()
|
||||
await expect(panel.getByText(/RX 8.*TX 12.*2\/2/)).toBeVisible()
|
||||
await expect(panel.getByRole("region", {name: "Трафик пользователя"})).toContainText("RX 8.00 Мбит/с · TX 12.0 Мбит/с")
|
||||
await expect(map.getByRole("button", {name: "Пользователь Алиса"}).locator('rect[fill="var(--card)"]')).toHaveAttribute("stroke", "var(--border)")
|
||||
await panel.getByRole("button", {name: /DNS/}).click()
|
||||
await panel.getByRole("link", {name: "Открыть в «Трафике»"}).click()
|
||||
await expect(page).toHaveURL(/\/traffic\?.*user=alice/)
|
||||
await expect(page.getByRole("button", {name: "Клиенты", exact: true}).last()).toBeVisible()
|
||||
await page.getByRole("link", {name: "Вернуться на карту"}).click()
|
||||
await expect(panel.getByRole("heading", {name: "DNS", exact: true})).toBeVisible()
|
||||
await page.getByRole("button", {name: "IX и клиенты"}).click()
|
||||
await expect(map.getByRole("button", {name: "Устройство Вход"})).toHaveCount(0)
|
||||
await expect(map.getByRole("button", {name: "Устройство Изолированный IX"})).toBeVisible()
|
||||
await page.getByRole("button", {name: "Linux-клиенты", exact: true}).click()
|
||||
await page.getByRole("option", {name: /Linux VPS/}).click()
|
||||
await expect(panel.getByText("wg-linux · wireguard")).toBeVisible()
|
||||
await expect(panel.getByText("Нет потоков с подтверждённой привязкой к пользователю.")).toBeVisible()
|
||||
})
|
||||
|
||||
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => {
|
||||
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1}
|
||||
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1,
|
||||
trafficTypes: [{transport: "UDP", application: "QUIC", bytes: 900000}],
|
||||
serviceEvidence: [{basis: "heuristic", bytes: 900000}], lastBucketAt: "2026-11-26T18:30:00.000Z"}
|
||||
const edge = {fromId: "1", toId: service.id, bytes: 300000, bps: 8000, bpsFwd: 2000, bpsRev: 6000}
|
||||
let known = false
|
||||
await page.route("**/api/**", route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
const url = new URL(route.request().url())
|
||||
const path = url.pathname
|
||||
if (path === flowPath && url.searchParams.get("range") === "24h") {
|
||||
return route.fulfill({ json: { ...empty, rangeMinutes: 1440, windowSec: 86400, totalBytes: service.bytes, namedBytes: service.bytes, services: [service] } })
|
||||
}
|
||||
if (path === flowPath) expect(url.searchParams.get("range")).toBe("1m")
|
||||
const responses: Record<string, unknown> = {
|
||||
"/api/auth/config": {required: false}, "/api/servers": [{...server, type: "exit-node", name: "ARN"}],
|
||||
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
|
||||
@@ -19,8 +90,12 @@ test("Карта не приписывает весь YouTube единствен
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
await page.getByRole("button", {name: "Сервис YouTube", exact: true}).press("Enter")
|
||||
const composition = page.getByRole("region", {name: "Состав трафика IPFIX"})
|
||||
await expect(composition.getByText("Оценка по сети и порту")).toBeVisible()
|
||||
await expect(composition.locator("time")).toHaveAttribute("datetime", service.lastBucketAt)
|
||||
await expect(page.getByText("IPFIX · среднее за 5 мин")).toBeVisible()
|
||||
const unknown = page.getByText("Выход не определён", {exact: true}).locator("..")
|
||||
const badges = page.getByRole("button", {name: "Поток NetFlow между узлами"})
|
||||
const badges = page.locator("[data-map-ribbon] > title")
|
||||
await expect(unknown).toContainText("24 Кбит/с")
|
||||
await expect(badges).toHaveCount(0)
|
||||
known = true
|
||||
@@ -31,6 +106,58 @@ test("Карта не приписывает весь YouTube единствен
|
||||
await expect(badges).toContainText("↓6 Кбит/с ↑2 Кбит/с")
|
||||
})
|
||||
|
||||
test("Карта: DNS виден от экспортёра, пользователи разбиты в обеих карточках", async ({page}) => {
|
||||
const router = {...server, name: "MSK", type: "jump-host"}
|
||||
const dns = {id: "svc:dns", label: "DNS", category: "DNS", bytes: 300000, bps: 8000, share: 1,
|
||||
trafficTypes: [{transport: "UDP", application: "DNS", bytes: 225000}, {transport: "TCP", application: "DNS over TLS", bytes: 75000}],
|
||||
serviceEvidence: [{basis: "port", bytes: 300000}]}
|
||||
const users = [
|
||||
{clientId: "u1", clientName: "Алиса", bytes: 225000, bps: 6000},
|
||||
{clientId: "—", clientName: "—", bytes: 75000, bps: 2000},
|
||||
]
|
||||
const servicePaths = users.map(u => ({...u, viaId: "1", viaName: "MSK", viaIface: "ether1", enId: "", enName: "", serviceId: dns.id}))
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url())
|
||||
const path = url.pathname
|
||||
return route.fulfill({json: path === "/api/auth/config" ? {required: false}
|
||||
: path === "/api/servers" ? [router] : path === "/api/filters/gre-tunnels" ? {tunnels: [], failures: []}
|
||||
: path === "/api/uptime/speed-probes" ? {probes: []} : path === flowPath ? {
|
||||
...empty,
|
||||
...(url.searchParams.get("range") === "24h" ? {rangeMinutes: 1440, windowSec: 86400} : {}),
|
||||
totalBytes: dns.bytes, services: [dns], servicePaths, nodeUsers: {"1": users},
|
||||
serviceEdges: [{fromId: "1", toId: dns.id, observedOnly: true, bytes: dns.bytes, bps: dns.bps, bpsFwd: 0, bpsRev: dns.bps}],
|
||||
} : {}})
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.locator("[data-map-ribbon][data-observation] > title")).toContainText("MSK → DNS")
|
||||
await page.getByRole("button", {name: "Слои", exact: true}).click()
|
||||
const auxiliary = page.getByRole("button", {name: "Вспомогательные серые линии"})
|
||||
await auxiliary.click()
|
||||
await expect(auxiliary).toHaveAttribute("aria-pressed", "false")
|
||||
await expect(page.locator("[data-map-ribbon][data-observation]")).toHaveCount(0)
|
||||
await auxiliary.press("Escape")
|
||||
await expect(page.getByRole("button", {name: "Сервис DNS", exact: true})).toBeVisible()
|
||||
await page.getByRole("button", {name: "Слои", exact: true}).click()
|
||||
await auxiliary.click()
|
||||
await expect(page.locator("[data-map-ribbon][data-observation]")).toHaveCount(1)
|
||||
await auxiliary.press("Escape")
|
||||
await page.getByRole("button", {name: "Сервис DNS", exact: true}).press("Enter")
|
||||
const panel = page.getByRole("complementary", {name: "Детали объекта карты"})
|
||||
const composition = panel.getByRole("region", {name: "Состав трафика IPFIX"})
|
||||
await expect(composition.getByText("DNS · UDP").locator("..")).toContainText("75")
|
||||
await expect(composition.getByText("DNS over TLS · TCP").locator("..")).toContainText("25")
|
||||
await expect(composition.getByText("По протоколу / порту")).toBeVisible()
|
||||
const breakdown = panel.getByRole("region", {name: "Трафик по пользователям"})
|
||||
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("6 Кбит/с")
|
||||
await expect(breakdown.getByText("Без привязки к пользователю")).toBeVisible()
|
||||
await expect(panel.getByText("Экспортёр", {exact: true})).toBeVisible()
|
||||
await expect(panel.getByText(/интерфейс ether1 · выход не подтверждён/i).first()).toBeVisible()
|
||||
await panel.getByRole("button").filter({hasText: /Алиса.*Наблюдение IPFIX/}).click()
|
||||
await expect(panel.getByRole("button", {pressed: true}).filter({hasText: "Наблюдение IPFIX"})).toHaveCount(1)
|
||||
await page.getByRole("button", {name: "Устройство MSK", exact: true}).press("Enter")
|
||||
await expect(breakdown.getByText("Алиса", {exact: true}).locator("..")).toContainText("75%")
|
||||
})
|
||||
|
||||
for (const reverse of [false, true]) test(`Карта: малый NetFlow и текущие RX/TX GRE показаны отдельно, reverse=${reverse}`, async ({ page }) => {
|
||||
const exit = { ...server, name: "ARN", type: "exit-node" }
|
||||
const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" }
|
||||
@@ -48,15 +175,20 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
|
||||
const exact = { fromId: String(owner.id), fromLabel: owner.name, toId: "", toLabel: "", kind: "iface", iface: tunnel.name,
|
||||
bytes: 3_750_000, bps: 100_000, bpsFwd: 100_000, bpsRev: 0 }
|
||||
let exactNetflow = false
|
||||
let nativeAvailable = false
|
||||
let liveReads = 0
|
||||
await page.route("**/api/**", route => {
|
||||
const url = new URL(route.request().url())
|
||||
if (/\/traffic\/servers\/\d+\/live$/.test(url.pathname)) {
|
||||
if (url.pathname === `/api/traffic/servers/${peer.id}/live`) {
|
||||
return route.fulfill({ status: 503, json: { error: "Нет замера" } })
|
||||
}
|
||||
if (url.pathname === `/api/traffic/servers/${owner.id}/live`) {
|
||||
expect(url.pathname).toBe(`/api/traffic/servers/${owner.id}/live`)
|
||||
expect(url.searchParams.get("iface")).toBe(tunnel.name)
|
||||
expect(url.searchParams.get("once")).toBe("1")
|
||||
liveReads++
|
||||
return route.fulfill({ json: { rxMbps: 0.16168, txMbps: 0.119224, at: "2026-11-23T07:20:36Z", timestampKind: "backend-receipt" } })
|
||||
return nativeAvailable ? route.fulfill({ json: { rxMbps: 80, txMbps: 1, at: new Date().toISOString(), timestampKind: "backend-receipt" } })
|
||||
: route.fulfill({ status: 503, json: { error: "Нет замера" } })
|
||||
}
|
||||
const json = {
|
||||
"/api/auth/config": { required: false },
|
||||
@@ -71,43 +203,88 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
|
||||
return route.fulfill({ json })
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const badge = page.getByRole("button", { name: "Поток NetFlow между узлами" })
|
||||
await expect(badge).toContainText("Нет записей")
|
||||
expect(liveReads).toBe(0)
|
||||
const badge = page.getByRole("button", { name: /^Связь / })
|
||||
await expect(badge.locator("text")).toHaveText("—")
|
||||
await expect.poll(() => liveReads).toBeGreaterThan(0)
|
||||
await badge.click()
|
||||
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
|
||||
await expect(panel.getByText("Нет записей", { exact: true })).toBeVisible()
|
||||
const live = page.getByText("Live GRE · RX/TX сейчас", {exact: true}).locator("..")
|
||||
await expect(live).toContainText("↓162 Кбит/с ↑119 Кбит/с")
|
||||
await expect(live).toContainText("Нет замера")
|
||||
await expect(page.getByText(/Последняя минута с данными/)).toBeVisible()
|
||||
exactNetflow = true
|
||||
await expect(badge).toContainText("14 бит/с", {timeout: 12000})
|
||||
await expect(live).toContainText("↓162 Кбит/с ↑119 Кбит/с")
|
||||
await expect(badge).toContainText("↓14 бит/с ↑0 Кбит/с")
|
||||
await expect(badge).toHaveAccessibleName(/14 бит\/с/, {timeout: 12000})
|
||||
await expect(panel.getByText("↓14 бит/с ↑0 Кбит/с", { exact: true })).toBeVisible()
|
||||
await expect(page.getByText("За интервал · 525 Б · 3 пак.")).toBeVisible()
|
||||
await expect(badge).not.toContainText("Live GRE")
|
||||
|
||||
nativeAvailable = true
|
||||
await expect(badge).toHaveAccessibleName(/81[.,]0 Мбит\/с/, {timeout: 18000})
|
||||
await page.getByRole("button", {name:"Сводка сети", exact:true}).click()
|
||||
await expect(page.getByText("Макс. из замеров · Live", {exact: true}).locator("..")).toContainText("81")
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(live).toContainText("↓80")
|
||||
await expect(panel.getByText("↓14 бит/с ↑0 Кбит/с", { exact: true })).toBeVisible()
|
||||
})
|
||||
|
||||
test("Карта: два GRE одного роутера к одному узлу сохраняют отдельные счётчики", async ({ page }) => {
|
||||
test("Карта: параллельные GRE с разными владельцами суммируются один раз", async ({ page }) => {
|
||||
const peer = { ...server, id: 2, name: "Exit", host: "192.0.2.2", type: "exit-node" }
|
||||
const tunnels = ["gre-low", "gre-other"].map(name => ({
|
||||
const forward = ["gre-low", "gre-other"].map((name, i) => ({
|
||||
name, id: name, serverId: "1", enabled: true, status: "up", localAddress: server.host, remoteAddress: peer.host,
|
||||
localInnerIp: "", remoteInnerIp: "", poolId: "", ipsec: null, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3,
|
||||
localInnerIp: `10.0.${i}.1`, remoteInnerIp: `10.0.${i}.2`, poolId: "", ipsec: null, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3,
|
||||
dscp: "inherit", clampTcpMss: true, allowFastPath: false, comment: "",
|
||||
}))
|
||||
const interfaceTraffic = tunnels.map(({name}, i) => ({ serverId: "1", iface: name, rxBytes: 600 * (i + 1), txBytes: 0,
|
||||
const reverse = forward.map(t => ({ ...t, name: t.name + "-peer", id: t.id + "-peer", serverId: "2",
|
||||
localAddress: peer.host, remoteAddress: server.host, localInnerIp: t.remoteInnerIp, remoteInnerIp: t.localInnerIp }))
|
||||
const tunnels = [forward[0], reverse[0], reverse[1], forward[1]]
|
||||
const interfaceTraffic = forward.map(({name}, i) => ({ serverId: "1", iface: name, rxBytes: 600 * (i + 1), txBytes: 0,
|
||||
rxPackets: i + 1, txPackets: 0, inWindow: true, lastBucketAt: "2026-11-23T07:00:00Z" }))
|
||||
const sample = (rxMbps: number) => ({ rxMbps, txMbps: 0, at: new Date().toISOString(), timestampKind: "backend-receipt" })
|
||||
let liveReads = 0
|
||||
await page.route("**/api/**", route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
const url = new URL(route.request().url())
|
||||
const path = url.pathname
|
||||
if (path === "/api/traffic/servers/1/live" && url.searchParams.get("once") === "1") {
|
||||
expect(url.searchParams.get("ifaces")?.split(",").sort()).toEqual(["gre-low", "gre-other"])
|
||||
liveReads++
|
||||
return route.fulfill({ json: { interfaces: {
|
||||
"gre-low": { ...sample(180), at: "2026-11-23T07:20:36Z" }, "gre-other": sample(10),
|
||||
} } })
|
||||
}
|
||||
if (path === "/api/traffic/servers/2/live" && url.searchParams.get("once") === "1") {
|
||||
expect(url.searchParams.get("ifaces")?.split(",").sort()).toEqual(["gre-low-peer", "gre-other-peer"])
|
||||
return route.fulfill({ json: { interfaces: { "gre-low-peer": sample(80), "gre-other-peer": sample(10) } } })
|
||||
}
|
||||
return route.fulfill({ json: path === "/api/servers" ? [{ ...server, type: "jump-host" }, peer]
|
||||
: path === "/api/filters/gre-tunnels" ? { tunnels, failures: [] }
|
||||
: path === flowPath ? { ...empty, live: true, interfaceTraffic }
|
||||
: path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} })
|
||||
})
|
||||
await page.goto("/network-map")
|
||||
const badges = page.getByRole("button", { name: "Поток NetFlow между узлами" })
|
||||
await expect(badges).toHaveCount(2)
|
||||
await expect(badges.filter({hasText: "↓16 бит/с"})).toHaveCount(1)
|
||||
await expect(badges.filter({hasText: "↓32 бит/с"})).toHaveCount(1)
|
||||
await expect(page.getByRole("button", { name: /^Связь Router → Exit: 90.*GRE ×2$/ })).toHaveCount(1)
|
||||
expect(liveReads).toBeGreaterThan(0)
|
||||
await page.getByRole("button", { name: "Устройство Router", exact: true }).click()
|
||||
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
|
||||
await panel.getByRole("tab", { name: "Интерфейсы" }).click()
|
||||
await expect(panel.getByText("gre-low", { exact: true }).locator("..")).toContainText("↓ 16 бит/с")
|
||||
await expect(panel.getByText("gre-other", { exact: true }).locator("..")).toContainText("↓ 32 бит/с")
|
||||
})
|
||||
|
||||
test("Карта: карточка узла показывает отдельно фактические RX/TX RouterOS", async ({ page }) => {
|
||||
await page.route("**/api/**", route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
return route.fulfill({ json: path === "/api/servers" ? [server] : path === flowPath ? empty
|
||||
: path === "/api/filters/gre-tunnels" ? { tunnels: [], failures: [] }
|
||||
: path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} })
|
||||
})
|
||||
await installOpenLiveStream(page, "/api/traffic/servers/1/live", { rxMbps: 80, txMbps: 1, at: new Date().toISOString(), timestampKind: "backend-receipt" })
|
||||
await page.goto("/network-map")
|
||||
await page.getByRole("button", { name: "Устройство Router", exact: true }).click()
|
||||
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
|
||||
await expect(panel.getByText("Входящий · Live")).toBeVisible()
|
||||
await expect(panel.getByText("80.0 Мбит/с")).toBeVisible()
|
||||
await expect(panel.getByText("Исходящий · Live")).toBeVisible()
|
||||
await expect(panel.getByText("1.00 Мбит/с")).toBeVisible()
|
||||
await page.clock.fastForward(15_001)
|
||||
await expect(panel.getByText("Входящий · Live")).toHaveCount(0)
|
||||
})
|
||||
|
||||
for(const malformed of [false,true])test("Карта: NetFlow отказ и повтор "+malformed,async({page})=>{
|
||||
@@ -118,7 +295,7 @@ for(const malformed of [false,true])test("Карта: NetFlow отказ и по
|
||||
await expect(page.getByRole("alert").filter({hasText:"Первоначальная загрузка NetFlow"})).toBeVisible()
|
||||
await expect(page.getByText("Данные NetFlow неизвестны",{exact:true})).toBeVisible()
|
||||
failing=false;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
await expect(page.getByText(malformed?/NetFlow · 2 мин из 5 запрошенных · ответ/:/NetFlow · 5 мин · ответ/)).toContainText("приёмник выключен")
|
||||
await expect(page.getByTitle(malformed?/NetFlow · 2 мин из 5 запрошенных · ответ/:/NetFlow · 5 мин · ответ/)).toContainText("приёмник выключен")
|
||||
await expect(page.getByRole("alert").filter({hasText:"NetFlow:"})).toHaveCount(0)
|
||||
})
|
||||
test("Карта: NetFlow сохраняет сервис при фоновом сбое",async({page})=>{
|
||||
@@ -143,5 +320,5 @@ for(const result of ["missing","foreign","unresolved","success"])test("Карт
|
||||
await page.route("**/api/**",async r=>{const p=new URL(r.request().url()).pathname;if(p===flowPath){requests++;await gate;return r.fulfill({json:empty})}return r.fulfill({json:p==="/api/servers"?[server]:p==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/auth/config"?{required:false}:{}})})
|
||||
await page.goto("/network-map");await expect.poll(()=>requests).toBe(1)
|
||||
await page.clock.runFor(5000);expect(requests).toBe(1)
|
||||
release();await expect(page.getByText(/NetFlow · 5 мин · ответ/)).toBeVisible()
|
||||
release();await expect(page.getByTitle(/NetFlow · 5 мин · ответ/)).toBeVisible()
|
||||
})
|
||||
@@ -8,20 +8,20 @@ test.beforeEach(async({page})=>{
|
||||
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
|
||||
await page.route("**/api/**",r=>{const p=new URL(r.request().url()).pathname;return r.fulfill({json:p==="/api/servers"?[{...home,name:"Домашний роутер с очень длинным названием и описанием устройства"},{...jh,name:"Промежуточный узел с длинной подписью"}]:p==="/api/filters/gre-tunnels"?{tunnels:[tunnel],failures:[]}:p==="/api/uptime/speed-probes"?{probes:[]}:p==="/api/traffic/flow/map-hops"?empty:p==="/api/auth/config"?{required:false}:{}})})
|
||||
})
|
||||
for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page})=>{
|
||||
for(const width of [1440,390,320])test("Карта: доступные детали и адаптивная оболочка "+width,async({page},testInfo)=>{
|
||||
await page.setViewportSize({width,height:900});await page.goto("/network-map")
|
||||
await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
|
||||
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
|
||||
await page.screenshot({path:"docs/ux-ui/screens/network-map-overview-"+(width===1440?"desktop":width===390?"mobile":"narrow")+".png"})
|
||||
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1")
|
||||
await page.screenshot({path:testInfo.outputPath("network-map-overview.png")})
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
|
||||
const panel=page.getByRole("complementary",{name:"Детали объекта карты"})
|
||||
await expect(panel).toBeVisible();await expect(panel.getByText("Ресурсы",{exact:true})).toBeVisible()
|
||||
const bounds=await panel.boundingBox(),map=width>=1024?await page.getByRole("group",{name:"Интерактивная карта сети"}).boundingBox():null
|
||||
const bounds=await panel.boundingBox(),map=await page.getByRole("group",{name:"Интерактивная карта сети"}).boundingBox()
|
||||
expect(bounds!.width).toBeGreaterThan(250);expect(bounds!.height).toBeGreaterThan(350)
|
||||
if(width<1024)await expect(page.getByRole("group",{name:"Интерактивная карта сети"})).toBeHidden()
|
||||
else expect(map!.height).toBeGreaterThan(0)
|
||||
expect(map!.height).toBeGreaterThanOrEqual(390)
|
||||
if(width>=1024)expect(bounds!.x).toBeGreaterThan(map!.x+map!.width/2)
|
||||
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
|
||||
await page.screenshot({path:"docs/ux-ui/screens/network-map-detail-"+(width===1440?"desktop":width===390?"mobile":"narrow")+".png"})
|
||||
await page.screenshot({path:testInfo.outputPath("network-map-detail.png")})
|
||||
await panel.getByRole("button",{name:"Закрыть детали устройства"}).click()
|
||||
await expect(panel).toHaveCount(0)
|
||||
const node=page.getByRole("button",{name:/^Устройство Домашний/});await node.focus();await node.press("Enter");await expect(panel).toBeVisible()
|
||||
@@ -34,6 +34,26 @@ for(const width of [1440,390,320])test("Карта: доступные дета
|
||||
await page.getByRole("button",{name:"Слои",exact:true}).click();await expect(page.getByRole("dialog",{name:"Слои карты"})).toBeVisible()
|
||||
await page.keyboard.press("Escape");await expect(page.getByRole("button",{name:"Слои",exact:true})).toBeFocused();await expect(page).toHaveURL(/server=1/)
|
||||
})
|
||||
test("Карта: шкала и рабочая панель фокусируют сбой устройства",async({page})=>{
|
||||
const now = new Date().toISOString()
|
||||
await page.route("**/api/events?*", route => route.fulfill({json:{events:[
|
||||
{ id:"routine", createdAt:now, level:"info", eventType:"job", sourceModule:"scheduler", title:"Задание завершено", message:"Плановое выполнение", entityType:null, entityId:null },
|
||||
{ id:"probe", createdAt:now, level:"critical", eventType:"device", sourceModule:"alerts", title:"Узел недоступен", message:"Опрос не получил ответа", entityType:"server", entityId:"2" },
|
||||
]}}))
|
||||
await page.goto("/network-map")
|
||||
const timeline = page.getByRole("group",{name:"Инциденты карты за 24 часа"})
|
||||
await expect(timeline.getByRole("button",{name:/Узел недоступен/})).toBeVisible()
|
||||
await expect(timeline.getByRole("button",{name:/Задание завершено/})).toHaveCount(0)
|
||||
await timeline.getByRole("button",{name:/Узел недоступен/}).click()
|
||||
await expect(page.getByRole("link",{name:"Трафик узла"})).toHaveAttribute("href",/server=2/)
|
||||
const analysis = page.getByRole("region",{name:"Рабочая панель карты"})
|
||||
await expect(analysis.getByRole("tab",{name:/События/})).toHaveAttribute("aria-selected","true")
|
||||
await expect(analysis.getByRole("button",{name:"Задание завершено",exact:true})).toHaveCount(0)
|
||||
await analysis.getByRole("button",{name:"Все события",exact:true}).click()
|
||||
await expect(analysis.getByRole("button",{name:"Задание завершено",exact:true})).toBeVisible()
|
||||
await analysis.getByRole("button",{name:"Свернуть рабочую панель"}).click()
|
||||
await expect(analysis.getByRole("button",{name:"Открыть рабочую панель"})).toHaveAttribute("aria-expanded","false")
|
||||
})
|
||||
test("Карта: reduced motion и самостоятельный SVG экспорт",async({page})=>{
|
||||
await page.emulateMedia({reducedMotion:"reduce"});await page.goto("/network-map")
|
||||
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||
@@ -58,7 +78,7 @@ test("Карта: пропорции камеры, ручной масштаб
|
||||
await expect(page.getByRole("button",{name:"Обновить",exact:true})).toBeEnabled();await expect(map).toHaveAttribute("viewBox",manual!)
|
||||
await page.getByRole("button",{name:"Вписать карту",exact:true}).click()
|
||||
expect(await map.getAttribute("viewBox")).not.toBe(manual)
|
||||
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1")
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
|
||||
await page.getByRole("complementary",{name:"Детали объекта карты"}).getByRole("tab",{name:"Интерфейсы"}).click()
|
||||
const wan=page.getByRole("button",{name:"WAN WAN",exact:true});await wan.focus();await wan.press("Enter")
|
||||
await expect(page).toHaveURL(/wan=0/);await expect(wan).toHaveAttribute("aria-pressed","true")
|
||||
@@ -67,11 +87,11 @@ test("Карта: пропорции камеры, ручной масштаб
|
||||
test("Карта: pointer capture, клавиатурный pan и возврат фокуса",async({page})=>{
|
||||
await page.goto("/network-map");const map=page.getByRole("group",{name:"Интерактивная карта сети"}),node=page.getByRole("button",{name:/^Устройство Домашний/})
|
||||
await expect(node).toBeVisible();await map.focus();const before=await map.getAttribute("viewBox");await map.press("ArrowDown");expect(await map.getAttribute("viewBox")).not.toBe(before)
|
||||
await page.getByRole("combobox",{name:"Устройство на карте"}).selectOption("1")
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
|
||||
const transform=await node.getAttribute("transform"),point=await node.evaluate((g:SVGGElement)=>{const matrix=g.getScreenCTM()!;return {x:matrix.e,y:matrix.f}})
|
||||
await page.mouse.move(point.x,point.y);await page.mouse.down();await page.mouse.move(point.x+80,point.y+25,{steps:5});await page.mouse.up()
|
||||
expect(await node.getAttribute("transform")).not.toBe(transform);await expect(page).toHaveURL(/server=1/)
|
||||
await page.getByRole("button",{name:"Закрыть детали устройства"}).click();await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeFocused()
|
||||
await page.getByRole("button",{name:"Закрыть детали устройства"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла или назначения"})).toBeFocused()
|
||||
const box=(await map.boundingBox())!,pan=await map.getAttribute("viewBox")
|
||||
await page.mouse.move(box.x+15,box.y+box.height-50);await page.mouse.down();await page.mouse.move(box.x-30,box.y+box.height-80,{steps:5});await page.mouse.up()
|
||||
expect(await map.getAttribute("viewBox")).not.toBe(pan)
|
||||
@@ -79,7 +99,7 @@ test("Карта: pointer capture, клавиатурный pan и возвра
|
||||
})
|
||||
test("Карта: touch pan и отмена жеста без залипания",async({page})=>{
|
||||
await page.setViewportSize({width:390,height:900});await page.goto("/network-map")
|
||||
const map=page.getByRole("group",{name:"Интерактивная карта сети"});await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
|
||||
const map=page.getByRole("group",{name:"Интерактивная карта сети"});await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||
expect(await map.evaluate(e=>getComputedStyle(e).touchAction)).toBe("none")
|
||||
const box=(await map.boundingBox())!,before=await map.getAttribute("viewBox"),session=await page.context().newCDPSession(page)
|
||||
await session.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x:box.x+20,y:box.y+box.height-70,id:1}]})
|
||||
@@ -90,9 +110,9 @@ test("Карта: touch pan и отмена жеста без залипания
|
||||
await page.getByRole("button",{name:/^Устройство Домашний/}).click();await expect(page.getByRole("complementary",{name:"Детали объекта карты"})).toBeVisible()
|
||||
})
|
||||
test("Карта: пустой источник отличается от пустого среза",async({page})=>{
|
||||
await page.goto("/network-map");await expect(page.getByRole("combobox",{name:"Устройство на карте"})).toBeEnabled()
|
||||
await page.getByRole("textbox",{name:"Поиск узла"}).fill("нет такого узла");await expect(page.getByRole("status").filter({hasText:"Узлы по заданным условиям"})).toBeVisible()
|
||||
await page.getByRole("button",{name:"Сбросить срез карты"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла"})).toHaveValue("")
|
||||
await page.goto("/network-map");await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("нет такого узла");await expect(page.getByRole("status").filter({hasText:"Узлы по заданным условиям"})).toBeVisible()
|
||||
await page.getByRole("button",{name:"Сбросить срез карты"}).click();await expect(page.getByRole("textbox",{name:"Поиск узла или назначения"})).toHaveValue("")
|
||||
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||
await page.route("**/api/servers",r=>r.fulfill({json:[]}));await page.route("**/api/filters/gre-tunnels",r=>r.fulfill({json:{tunnels:[],failures:[]}}))
|
||||
await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
||||
|
||||
@@ -17,19 +17,30 @@ test.beforeEach(async ({ page }) => {
|
||||
|
||||
test("Карта: раскрытая легенда объясняет статусы, типы, линии и неизвестные измерения", async ({ page }) => {
|
||||
await page.goto("/network-map")
|
||||
const trigger = page.getByRole("button", { name: "Легенда", exact: true })
|
||||
const legend = page.getByRole("region", { name: "Легенда карты" })
|
||||
await expect(legend).not.toBeVisible()
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await trigger.click()
|
||||
await expect(legend).toBeVisible()
|
||||
for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Поток NetFlow"]) await expect(legend.getByText(text, { exact: true })).toBeVisible()
|
||||
const firstStatus = legend.getByText("Онлайн", { exact: true })
|
||||
await expect.poll(() => firstStatus.evaluate(element => {
|
||||
const { x, y, width, height } = element.getBoundingClientRect()
|
||||
const hit = document.elementFromPoint(x + width / 2, y + height / 2)
|
||||
return hit !== null && element.contains(hit)
|
||||
})).toBe(true)
|
||||
for (const text of ["Онлайн", "Внимание", "Оффлайн", "Неизвестно", "JumpHost", "Exit Node", "Home Router", "GRE + IPsec", "Связь с сервисом"]) await expect(legend.getByText(text, { exact: true })).toBeVisible()
|
||||
await expect(legend).toContainText("нет измерения")
|
||||
await expect(legend).toContainText("не пропускная способность канала")
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS")
|
||||
await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX")
|
||||
await trigger.click()
|
||||
await expect(legend).not.toBeVisible()
|
||||
await page.locator("[data-map-legend] summary").press("Enter")
|
||||
await trigger.press("Enter")
|
||||
await expect(legend).toBeVisible()
|
||||
await legend.getByText("Онлайн", { exact: true }).click()
|
||||
await page.screenshot({ path: "tmp/map270-desktop.png" })
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(legend).not.toBeVisible()
|
||||
await expect(trigger).toBeFocused()
|
||||
})
|
||||
|
||||
test("Карта: мышь не рисует прямоугольную рамку, клавиатурный фокус остаётся видимым", async ({ page }) => {
|
||||
@@ -51,15 +62,16 @@ test("Карта: мышь не рисует прямоугольную рамк
|
||||
test("Карта: легенда помещается на телефоне и сворачивается", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.goto("/network-map")
|
||||
const trigger = page.getByRole("button", { name: "Легенда", exact: true })
|
||||
const legend = page.getByRole("region", { name: "Легенда карты" })
|
||||
await expect(page.locator("[data-map-legend]")).not.toHaveAttribute("open", "")
|
||||
await expect(trigger).toHaveAttribute("aria-expanded", "false")
|
||||
await page.screenshot({ path: "tmp/map270-mobile.png" })
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await trigger.click()
|
||||
await expect(legend).toBeVisible()
|
||||
const bounds = await legend.boundingBox()
|
||||
expect(bounds!.x).toBeGreaterThanOrEqual(0)
|
||||
expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390)
|
||||
await page.locator("[data-map-legend] summary").click()
|
||||
await trigger.click()
|
||||
await expect(legend).not.toBeVisible()
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { test, expect, type Page } from "@playwright/test"
|
||||
|
||||
// Подписи и карточки холста не наезжают друг на друга: проверяем видимые тела (data-map-box), а не фоновые полосы.
|
||||
const empty = { hops: [], live: true, rangeMinutes: 5, windowSec: 300, totalBytes: 0, namedBytes: 0, unclassifiedBytes: 0, asnLoaded: false, countryLoaded: false, services: [], serviceEdges: [], servicePaths: [], countries: [], countryEdges: [], countryPaths: [], countryServiceGroups: [], mapServiceMinSharePct: 0, dedupApplied: false, excludeMeshApplied: false, excludeOverlayApplied: false }
|
||||
const srv = (id: number, name: string, type: string, country = "RU", status = "online") =>
|
||||
({ id, name, host: `192.0.2.${id}`, type, country, enabled: true, status, latency: 10 + id })
|
||||
const gre = (id: string, owner: number, peer: number, status = "up") => ({
|
||||
id, serverId: String(owner), name: id, localAddress: `192.0.2.${owner}`, remoteAddress: `192.0.2.${peer}`, localInnerIp: "", remoteInnerIp: "",
|
||||
poolId: "", ipsec: null, mtu: 1400, keepaliveInterval: 10, keepaliveRetries: 3, dscp: "inherit", clampTcpMss: true, allowFastPath: false, comment: "", enabled: true, status,
|
||||
})
|
||||
|
||||
async function serve(page: Page, servers: unknown[], tunnels: ReturnType<typeof gre>[], flow: Record<string, unknown>) {
|
||||
await page.route("**/health", (r) => r.fulfill({ json: { ok: true } }))
|
||||
await page.route("**/api/**", (r) => {
|
||||
const p = new URL(r.request().url()).pathname
|
||||
const json = p === "/api/servers" ? servers : p === "/api/filters/gre-tunnels" ? { tunnels, failures: [] }
|
||||
: p === "/api/uptime/speed-probes" ? { probes: [] } : p === "/api/traffic/flow/map-hops" ? { ...empty, ...flow }
|
||||
: p === "/api/ix/topology" ? { links: [] } : p === "/api/auth/config" ? { required: false } : {}
|
||||
return r.fulfill({ json })
|
||||
})
|
||||
}
|
||||
|
||||
async function overlaps(page: Page) {
|
||||
return page.getByRole("group", { name: "Интерактивная карта сети" }).evaluate((svg) => {
|
||||
const boxes = [...svg.querySelectorAll("[data-map-box]")].map((el) => ({ kind: el.getAttribute("data-map-box")!, label: el.closest("[aria-label]")?.getAttribute("aria-label") ?? el.parentElement?.textContent ?? "", text: el.parentElement?.querySelector(":scope > text")?.textContent ?? "", r: el.getBoundingClientRect() }))
|
||||
// Панель масштаба и миникарта лежат поверх холста — они тоже не должны закрывать карточки и подписи.
|
||||
const overlays = [...document.querySelectorAll("[data-map-overlay]")].map((el) => ({ kind: el.getAttribute("data-map-overlay")!, label: "", r: el.getBoundingClientRect() }))
|
||||
const hits: string[] = []
|
||||
const pairs = [...boxes.flatMap((a, i) => boxes.slice(i + 1).map((b) => [a, b] as const)), ...overlays.flatMap((o) => boxes.map((b) => [o, b] as const))]
|
||||
for (const [a, b] of pairs) {
|
||||
const ix = Math.min(a.r.right, b.r.right) - Math.max(a.r.left, b.r.left), iy = Math.min(a.r.bottom, b.r.bottom) - Math.max(a.r.top, b.r.top)
|
||||
if (ix > 1 && iy > 1) hits.push(`${a.kind} «${a.label}» × ${b.kind} «${b.label}»`)
|
||||
}
|
||||
return { overlays: overlays.length, rates: boxes.filter((b) => b.kind === "pill" && /бит\/с/.test(b.text)).length, pills: boxes.filter((b) => b.kind === "pill").length, cards: boxes.filter((b) => b.kind === "card").length, hits }
|
||||
})
|
||||
}
|
||||
|
||||
test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 сервисов без наложений", async ({ page }) => {
|
||||
const servers = [
|
||||
srv(1, "msk-gw01.example.net", "jump-host"), srv(2, "msk-gw02.example.net", "jump-host"), srv(3, "nov-gw01.example.net", "jump-host"),
|
||||
srv(4, "arn-gw01.example.net", "exit-node", "SE"), srv(5, "chr-ix.example.net", "ix-node", "PL"),
|
||||
]
|
||||
// У каждого JH два туннеля до выхода и запись встречного конца на выходе; один JH ещё и до IX.
|
||||
const tunnels = [1, 2, 3].flatMap((jh) => [gre(`gre-${jh}a`, jh, 4), gre(`gre-${jh}b`, jh, 4, jh === 3 ? "down" : "up"), gre(`gre-4-${jh}`, 4, jh)])
|
||||
tunnels.push(gre("gre-ix", 1, 5))
|
||||
const names = ["Прочее", "YouTube", "Cloudflare", "main", "AWS", "Akamai", "Google", "Telegram"]
|
||||
const services = names.map((label, i) => ({ id: "svc:" + i, label, category: "Веб", bytes: 9e6 - i * 1e6, bps: 6e6 - i * 7e5, share: 0.2 - i * 0.02 }))
|
||||
const serviceEdges = services.map((s) => ({ fromId: "4", toId: s.id, bytes: s.bytes, bps: s.bps, bpsFwd: s.bps / 4, bpsRev: (s.bps * 3) / 4 }))
|
||||
const interfaceTraffic = tunnels.map((t, i) => ({ serverId: t.serverId, iface: t.name, rxBytes: 4e6 + i * 1e5, txBytes: 1e6, rxPackets: 10, txPackets: 5, inWindow: true, lastBucketAt: "2026-11-23T07:00:00Z" }))
|
||||
await serve(page, servers, tunnels, { services, serviceEdges, interfaceTraffic, totalBytes: 5e7, namedBytes: 5e7 })
|
||||
await page.goto("/network-map")
|
||||
await page.getByRole("button", { name: /^Остальные сервисы \(/ }).first().click()
|
||||
await expect(page.getByRole("button", { name: "Сервис Telegram", exact: true })).toBeVisible()
|
||||
await expect.poll(async () => (await overlaps(page)).cards).toBe(5)
|
||||
const result = await overlaps(page)
|
||||
expect(result.cards).toBe(5)
|
||||
expect(result.overlays).toBe(2)
|
||||
expect(result.hits).toEqual([])
|
||||
// Скорость NetFlow пары не теряется: она на подписи или, если не влезла между карточками, — в title линии.
|
||||
expect(result.rates + await page.locator("path > title", { hasText: /^Связь .*бит\/с/ }).count()).toBeGreaterThan(0)
|
||||
// Имя хоста без домена, параллельные туннели — одной подписью.
|
||||
await expect(page.getByRole("group", { name: "Интерактивная карта сети" }).getByText("msk-gw01", { exact: true })).toBeVisible()
|
||||
const pair = /^Связь msk-gw01\.example\.net → arn-gw01\.example\.net: .*GRE ×2/
|
||||
expect(await page.getByRole("button", { name: pair }).count()).toBeLessThanOrEqual(1)
|
||||
expect(await page.locator("path > title", { hasText: pair }).count()).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
test("Карта: группа сервисов сворачивается на холсте, IPFIX огибает карточки", async ({ page }, info) => {
|
||||
await page.setViewportSize({ width: 867, height: 914 })
|
||||
const servers = [srv(1, "Узел доступа", "jump-host"), srv(2, "Интернет-выход", "exit-node", "DE")]
|
||||
const major = { id: "svc:dns", label: "DNS", category: "DNS", bytes: 9_500, bps: 760, share: 0.95 }
|
||||
const minor = { id: "svc:ntp", label: "NTP", category: "NTP", bytes: 500, bps: 40, share: 0.05 }
|
||||
const serviceEdges = [major, minor].map(service => ({ fromId: "1", toId: service.id,
|
||||
bytes: service.bytes, bps: service.bps, bpsFwd: service.bps, bpsRev: 0, observedOnly: true }))
|
||||
await serve(page, servers, [gre("gre-exit", 1, 2)], { services: [major, minor], serviceEdges, namedBytes: 10_000, totalBytes: 10_000 })
|
||||
await page.goto("/network-map")
|
||||
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
|
||||
const group = map.getByRole("button", { name: /^Остальные сервисы/ })
|
||||
const closeGroup = map.getByRole("button", { name: "Свернуть остальные", exact: true })
|
||||
const ntp = map.getByRole("button", { name: "Сервис NTP" })
|
||||
await expect(group).toHaveAttribute("aria-expanded", "false")
|
||||
await expect(ntp).toHaveCount(0)
|
||||
await group.press("Enter")
|
||||
await expect(closeGroup).toHaveAttribute("aria-expanded", "true")
|
||||
await expect(ntp).toBeVisible()
|
||||
await expect(map.locator('[data-map-route="observation"]')).toHaveCount(2)
|
||||
const intersectsCards = await map.evaluate(svg => {
|
||||
const cards = [...svg.querySelectorAll('[data-map-box="card"], [data-map-box="dest"]')].map(card => card.getBoundingClientRect())
|
||||
return [...svg.querySelectorAll<SVGPathElement>('[data-map-route="observation"]')].some(path => {
|
||||
const length = path.getTotalLength()
|
||||
const transform = path.getScreenCTM()!
|
||||
for (let distance = 1; distance < length; distance += 2) {
|
||||
const p = path.getPointAtLength(distance).matrixTransform(transform)
|
||||
if (cards.some(rect => p.x > rect.left + 1 && p.x < rect.right - 1 && p.y > rect.top + 1 && p.y < rect.bottom - 1)) return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
})
|
||||
expect(intersectsCards).toBe(false)
|
||||
await closeGroup.press("Enter")
|
||||
await expect(group).toHaveAttribute("aria-expanded", "false")
|
||||
await expect(ntp).toHaveCount(0)
|
||||
await expect.poll(async () => (await map.boundingBox())!.y + (await map.boundingBox())!.height).toBeLessThan(915)
|
||||
await expect(page.getByRole("button", { name: "Открыть рабочую панель" })).toBeInViewport()
|
||||
await page.screenshot({path:info.outputPath("карта-сети.png")})
|
||||
})
|
||||
|
||||
test("Карта: сетка JH × Exit и аплинки WAN без наложений подписей", async ({ page }) => {
|
||||
const wan = (i: number) => ({ id: "w" + i, name: "WAN" + i, iface: "ether" + i, isp: "ISP-" + i, ip: `198.51.100.${i}`, maxDl: 100, maxUl: 50 })
|
||||
const servers = [
|
||||
{ ...srv(1, "home-msk", "home-router"), wanUplinks: [wan(1), wan(2)] }, { ...srv(2, "home-spb", "home-router"), wanUplinks: [wan(3), wan(4)] },
|
||||
srv(3, "mt-msk-core-01", "jump-host"), srv(4, "mt-msk-lab-01", "jump-host"), srv(5, "mt-ams-test-01", "jump-host", "NL"),
|
||||
srv(6, "mt-fra-edge-01", "exit-node", "DE"), srv(7, "mt-sgp-edge-01", "exit-node", "SG", "offline"), srv(8, "mt-spb-edge-01", "exit-node"), srv(9, "mt-ams-edge-01", "exit-node", "NL", "degraded"),
|
||||
]
|
||||
const tunnels = [3, 4, 5].flatMap((jh) => [6, 7, 8, 9].map((en) => gre(`gre-${jh}-${en}`, jh, en, en === 7 ? "down" : "up")))
|
||||
await serve(page, servers, tunnels, {})
|
||||
await page.goto("/network-map")
|
||||
await expect(page.getByRole("button", { name: /^Устройство mt-ams-edge-01/ })).toBeVisible()
|
||||
await expect.poll(async () => (await overlaps(page)).pills).toBeGreaterThan(2)
|
||||
expect((await overlaps(page)).hits).toEqual([])
|
||||
})
|
||||
@@ -8,12 +8,12 @@ test.beforeEach(async({page})=>{
|
||||
test("Карта URL: устройство/WAN, фильтр, поиск, назначения, reload и история",async({page})=>{
|
||||
await page.goto("/network-map?server=1&wan=0&filter=unknown&q=Router&dest=countries&tag=keep#anchor")
|
||||
await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible()
|
||||
await expect(page.getByRole("textbox",{name:"Поиск узла",exact:true})).toHaveValue("Router")
|
||||
await expect(page.getByRole("textbox",{name:"Поиск узла или назначения",exact:true})).toHaveValue("Router")
|
||||
await page.reload();await expect(page.getByText("Ресурсы",{exact:true})).toBeVisible()
|
||||
await page.getByRole("button",{name:/^Фильтр/}).click();await page.getByRole("button",{name:"Онлайн",exact:true}).click()
|
||||
await expect(page).toHaveURL(/filter=online/);await page.goBack();await expect(page).toHaveURL(/filter=unknown/)
|
||||
await page.getByRole("button",{name:"Сервисы",exact:true}).click();await expect(page).not.toHaveURL(/dest=countries/);await page.goBack();await expect(page).toHaveURL(/dest=countries/)
|
||||
await page.getByRole("textbox",{name:"Поиск узла",exact:true}).fill("Router URL");await expect.poll(()=>new URL(page.url()).searchParams.get("q")).toBe("Router URL")
|
||||
await page.getByRole("textbox",{name:"Поиск узла или назначения",exact:true}).fill("Router URL");await expect.poll(()=>new URL(page.url()).searchParams.get("q")).toBe("Router URL")
|
||||
await expect(page).toHaveURL(/tag=keep/);await expect(page).toHaveURL(/#anchor$/)
|
||||
await page.getByRole("button",{name:"Устройство Router URL",exact:true}).focus();await page.keyboard.press("Escape");await expect(page).not.toHaveURL(/server=/);await expect(page).not.toHaveURL(/wan=/)
|
||||
await page.getByRole("button",{name:"Устройство Router URL",exact:true}).click();await expect(page).toHaveURL(/server=1/)
|
||||
|
||||
@@ -32,10 +32,10 @@ for (const width of [320, 390, 1024, 1440]) {
|
||||
})
|
||||
expect(visibleBounds.filter(control => !control.inside)).toEqual([])
|
||||
expect(await header.locator("ol").evaluate(list => [...list.children].every(child => child.tagName === "LI"))).toBe(true)
|
||||
const apps = header.getByRole("button", { name: "Приложения", exact: true })
|
||||
const apps = header.getByRole("button", { name: /^Состояние системы/ })
|
||||
await apps.focus()
|
||||
await page.keyboard.press("Enter")
|
||||
await expect(page.getByRole("menu")).toBeVisible()
|
||||
await expect(page.locator('[data-slot="popover-content"]')).toBeVisible()
|
||||
await page.keyboard.press("Escape")
|
||||
await expect(apps).toBeFocused()
|
||||
if (width < 768) {
|
||||
|
||||
@@ -9,7 +9,8 @@ for(const width of [1440,320])test(`Меню приложений использ
|
||||
path==='/api/servers'?[]:path==='/api/evobgp/settings'?{enabled:false,baseUrl:'',secretConfigured:false}:{}})
|
||||
})
|
||||
await page.goto('/servers')
|
||||
await page.getByRole('button',{name:'Приложения',exact:true}).click()
|
||||
if(width<768)await page.getByRole('button',{name:'Боковое меню',exact:true}).click()
|
||||
await page.getByRole('button',{name:/^Переключатель приложений/}).click()
|
||||
await expect(page.getByRole('menuitem',{name:'Настроить на портале',exact:true})).toHaveAttribute('href','https://runtime.example.test/admin/apps')
|
||||
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1)).toBe(true)
|
||||
})
|
||||
@@ -2,11 +2,5 @@ import {test,expect,type Page} from "@playwright/test"
|
||||
import {emptyAlerts,emptyOutbox} from "./fixtures/alerts"
|
||||
const counts={servers:4,filterRules:0,uptimeProbes:0,uptimeSpeedProbes:0,monitoringItems:0,recursiveRoutes:0}
|
||||
async function setup(page:Page,reply:(path:string)=>{status?:number;json:unknown}){await page.route("**/health",r=>r.fulfill({json:{status:"ok"}}));await page.route("**/api/**",r=>{const path=new URL(r.request().url()).pathname;return r.fulfill(path==="/api/auth/config"?{json:{required:false}}:path==="/api/alerts"?{json:emptyAlerts}:path==="/api/alerts/outbox"?{json:emptyOutbox}:reply(path))});await page.goto("/alerts")}
|
||||
const badge=(page:Page,name:string)=>page.getByRole("navigation",{name:"Основная навигация"}).getByRole("link",{name:new RegExp(name)}).locator("span").last()
|
||||
test("Sidebar missing optional counts remain unknown; confirmed zero is displayed",async({page})=>{await setup(page,path=>({json:path==="/api/sidebar-counts"?counts:path==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:[]}));await expect(badge(page,"Серверы")).toHaveText("4");await expect(badge(page,"GRE-туннели")).toHaveText("0");await expect(badge(page,"Пользователи")).toHaveText("Пользователи")})
|
||||
test("Sidebar partial GRE refresh retains last complete count, other counts update independently",async({page})=>{await page.clock.install();let partial=false;await setup(page,path=>({json:path==="/api/sidebar-counts"?{...counts,servers:partial?5:4}:path==="/api/filters/gre-tunnels"?{tunnels:partial?[]:[{name:"g",serverId:"1"}],failures:partial?[{error:"offline"}]:[]}:[]}));await expect(badge(page,"GRE-туннели")).toHaveText("1");partial=true;await page.clock.fastForward(120001);await expect(badge(page,"Серверы")).toHaveText("5");await expect(badge(page,"GRE-туннели")).toHaveText("1")})
|
||||
test("Sidebar GRE does not wait for unavailable summary reader",async({page})=>{await setup(page,path=>path==="/api/sidebar-counts"?{status:503,json:{error:"counts unavailable"}}:{json:path==="/api/filters/gre-tunnels"?{tunnels:[{name:"g",serverId:"1"}],failures:[]}:[]});await expect(badge(page,"GRE-туннели")).toHaveText("1");await expect(badge(page,"Серверы")).toHaveText("Серверы")})
|
||||
|
||||
test("Sidebar GRE arrives while summary request is pending",async({page})=>{let started=false,release!:()=>void;const gate=new Promise<void>(resolve=>release=resolve);await page.route("**/health",r=>r.fulfill({json:{status:"ok"}}));await page.route("**/api/**",async r=>{const path=new URL(r.request().url()).pathname;if(path==="/api/sidebar-counts"){started=true;await gate;try{await r.fulfill({json:counts})}catch{};return}return r.fulfill({json:path==="/api/auth/config"?{required:false}:path==="/api/alerts"?emptyAlerts:path==="/api/alerts/outbox"?emptyOutbox:path==="/api/filters/gre-tunnels"?{tunnels:[{name:"g",serverId:"1"}],failures:[]}:[]})});try{await page.goto("/alerts");await expect.poll(()=>started).toBe(true);await expect(badge(page,"GRE-туннели")).toHaveText("1");await expect(badge(page,"Серверы")).toHaveText("Серверы");release();await expect(badge(page,"Серверы")).toHaveText("4")}finally{release()}})
|
||||
|
||||
test("System monitor summary failure preserves API health and last confirmed counts",async({page})=>{await page.clock.install();let fail=false;await setup(page,path=>path==="/api/sidebar-counts"&&fail?{status:503,json:{error:"summary unavailable"}}:{json:path==="/api/sidebar-counts"?counts:path==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:[]});const button=page.getByRole("button",{name:"Монитор системы"});await expect(button).toContainText("API доступен");await button.click();const popover=page.locator('[data-slot="popover-content"]');await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();fail=true;await page.clock.fastForward(30001);await expect(popover.getByRole("status")).toContainText("Сводка не обновлена");await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();await expect(button).toContainText("API доступен")})
|
||||
test("System monitor summary failure preserves API health and last confirmed counts",async({page})=>{await page.clock.install();let fail=false;await setup(page,path=>path==="/api/sidebar-counts"&&fail?{status:503,json:{error:"summary unavailable"}}:{json:path==="/api/sidebar-counts"?counts:path==="/api/filters/gre-tunnels"?{tunnels:[],failures:[]}:[]});const button=page.getByRole("button",{name:/^Состояние системы/});await expect(button).toContainText("Норма");await button.click();const popover=page.locator('[data-slot="popover-content"]');await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();fail=true;await page.clock.fastForward(30001);await expect(popover.getByRole("status")).toContainText("Сводка не обновлена");await expect(popover.getByText("4шт.",{exact:true})).toBeVisible();await expect(button).toContainText("Внимание");await expect(popover.getByText("OK",{exact:true})).toBeVisible()})
|
||||
@@ -30,6 +30,10 @@ async function setup(page: Page) {
|
||||
|
||||
test('Детали трафика: поздний период не заменяет текущий', async ({ page }) => {
|
||||
const control = await setup(page)
|
||||
const reading = page.getByRole('slider', {name: 'Точка на графике'})
|
||||
await expect(reading).toHaveAttribute('aria-valuetext', /сейчас · RX 2.* · TX 3/)
|
||||
await reading.press('Home')
|
||||
await expect(reading).toHaveAttribute('aria-valuetext', /RX 1.* · TX 2/)
|
||||
control.holdRange = '24h'
|
||||
const started = page.waitForRequest(r => new URL(r.url()).pathname === '/api/traffic/servers/1' && r.url().includes('range=24h'))
|
||||
await page.getByRole('button', { name: '24ч', exact: true }).click()
|
||||
|
||||
@@ -41,15 +41,39 @@ test('Список трафика: поздний период не заменя
|
||||
await started
|
||||
await expect(page.getByText('Загрузка списка трафика…', { exact: true })).toBeVisible()
|
||||
await expect(page.getByRole('button').filter({ hasText: 'Список 1h' })).toHaveCount(0)
|
||||
const cancelled = page.waitForEvent('requestfailed', {predicate: r => new URL(r.url()).pathname === '/api/traffic/servers' && r.url().includes('range=24h')})
|
||||
await page.getByRole('button', { name: '15м', exact: true }).click()
|
||||
await expect(page.getByRole('button').filter({ hasText: 'Список 15m' })).toBeVisible()
|
||||
const late = page.waitForResponse(r => new URL(r.url()).pathname === '/api/traffic/servers' && r.url().includes('range=24h'))
|
||||
control.release()
|
||||
await late
|
||||
await cancelled
|
||||
await expect(page.getByRole('button').filter({ hasText: 'Список 15m' })).toBeVisible()
|
||||
await expect(page.getByRole('button').filter({ hasText: 'Список 24h' })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test("Трафик клиента обновляет счётчики без перезагрузки", async ({page}) => {
|
||||
await page.clock.install()
|
||||
let txNow = 12
|
||||
await page.route("**/health", route => route.fulfill({json: {ok: true}}))
|
||||
await page.route("**/api/**", route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
const rates = {rxNow: 8, txNow, rxPeak: 20, txPeak: 30, rxTotal: 1, txTotal: 1, rxSeries: [8], txSeries: [txNow]}
|
||||
const iface = {id: "alice-gre", bindingId: "alice-gre", userId: "alice", interfaceName: "gre-alice",
|
||||
serverId: "1", serverName: "MSK", interfaceType: "gre", status: "online", ...rates}
|
||||
const user = {id: "alice", login: "alice", displayName: "Алиса", role: "viewer", active: true, interfaces: [iface], ...rates}
|
||||
const json = path === "/api/auth/config" ? {required: false}
|
||||
: path === "/api/traffic/users" ? {users: [user]}
|
||||
: path === "/api/traffic/servers" ? {servers: []}
|
||||
: path === "/api/traffic/bound-interfaces" ? {interfaces: []} : {}
|
||||
return route.fulfill({json: observedTrafficFixturePayload(json)})
|
||||
})
|
||||
await page.goto("/traffic?user=alice")
|
||||
const card = page.getByRole("button").filter({hasText: "Алиса"})
|
||||
await expect(card).toContainText("12.0 Мбит/с")
|
||||
txNow = 26
|
||||
await page.clock.fastForward(16_000)
|
||||
await expect(card).toContainText("26.0 Мбит/с")
|
||||
})
|
||||
|
||||
test('Список трафика: ошибка обновления скрывает сводку; повтор восстанавливает список', async ({ page }) => {
|
||||
const control = await setup(page)
|
||||
control.failList = true
|
||||
|
||||
@@ -2,6 +2,26 @@ import { observedTrafficFixturePayload } from "./traffic-observation-fixture"
|
||||
import { installOpenLiveStream, resumeLiveStream, sendLiveHeartbeat } from "./live-stream-fixture"
|
||||
import { test, expect } from '@playwright/test'
|
||||
|
||||
test("Трафик открывает сервер из ссылки карты", async ({ page }) => {
|
||||
const second = { id: "2", name: "Выбранный Exit", site: "TEST", country: "RU", status: "online", rxNow: 2, txNow: 3,
|
||||
rxPeak: 5, txPeak: 6, rxTotal: 100, txTotal: 200, sessions: 1, rxSeries: [1, 2], txSeries: [2, 3] }
|
||||
const first = { ...second, id: "1", name: "Первый роутер" }
|
||||
const requested: string[] = []
|
||||
await page.route("**/health", route => route.fulfill({ json: { ok: true } }))
|
||||
await page.route("**/api/**", route => {
|
||||
const { pathname } = new URL(route.request().url())
|
||||
if (/\/traffic\/servers\/\d+\/live$/.test(pathname)) requested.push(pathname)
|
||||
const data = pathname === "/api/auth/config" ? { required: false }
|
||||
: pathname === "/api/traffic/servers" ? { servers: [first, second] }
|
||||
: pathname === "/api/traffic/servers/2" ? { server: second }
|
||||
: pathname === "/api/traffic/users" ? { users: [] } : { interfaces: [] }
|
||||
return route.fulfill({ json: observedTrafficFixturePayload(data) })
|
||||
})
|
||||
await page.goto("/traffic?server=2")
|
||||
await expect(page.getByLabel("Скорость выбранного сервера")).toBeVisible()
|
||||
await expect.poll(() => requested).toEqual(["/api/traffic/servers/2/live"])
|
||||
})
|
||||
|
||||
for (const variant of ['closed', 'invalid', 'http-error', 'silent', 'awaiting'] as const) {
|
||||
test(`Трафик: SSE ${variant} не выдаёт старое измерение за live`, async ({ page }) => {
|
||||
const server = { id: '1', name: 'Тестовый сервер', site: 'TEST', country: 'RU', status: 'online', rxNow: 2, txNow: 3, rxPeak: 5, txPeak: 6, rxTotal: 100, txTotal: 200, sessions: 1, rxSeries: [1, 2], txSeries: [2, 3] }
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { test } from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { MAP_CARD_H, MAP_CARD_W, MAP_PILL_H, mapLinkPath, mapLinkPoint, mapRibbons, placeMapLinkLabels, type MapBox } from "../../lib/network-map-layout"
|
||||
|
||||
const card = (x: number, y: number): MapBox => ({ x: x - MAP_CARD_W / 2, y: y - MAP_CARD_H / 2, w: MAP_CARD_W, h: MAP_CARD_H })
|
||||
const hit = (a: MapBox, b: MapBox) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
|
||||
const pill = (p: { x: number; y: number; w: number }): MapBox => ({ x: p.x - p.w / 2, y: p.y - MAP_PILL_H / 2, w: p.w, h: MAP_PILL_H })
|
||||
|
||||
test("кривая связи проходит через концы и середину", () => {
|
||||
const l = mapLinkPath({ x: 0, y: 0 }, 10, { x: 200, y: 100 }, 10)
|
||||
assert.deepEqual(mapLinkPoint(l, 0), { x: 10, y: 0 })
|
||||
assert.deepEqual(mapLinkPoint(l, 1), { x: 190, y: 100 })
|
||||
assert.deepEqual(mapLinkPoint(l, 0.5), { x: 100, y: 50 })
|
||||
})
|
||||
|
||||
test("подписи не наезжают на карточки и друг на друга, длинная — укорачивается или пропадает", () => {
|
||||
// Три JH слева сходятся в один EN справа; у каждой пары — длинный и короткий вариант подписи.
|
||||
const jh = [100, 180, 260].map((y) => ({ x: 542, y }))
|
||||
const en = { x: 780, y: 180 }
|
||||
const obstacles = [...jh.map((p) => card(p.x, p.y)), card(en.x, en.y)]
|
||||
const labels = jh.map((p, i) => ({
|
||||
id: "jh" + i,
|
||||
link: mapLinkPath(p, MAP_CARD_W / 2, en, MAP_CARD_W / 2),
|
||||
texts: ["24 мс · 86 Мбит/с", "24 мс"],
|
||||
}))
|
||||
// Горизонтальная связь в узком зазоре: длинной подписи места нет нигде.
|
||||
labels.push({ id: "flat", link: mapLinkPath({ x: 542, y: 400 }, MAP_CARD_W / 2, { x: 780, y: 400 }, MAP_CARD_W / 2), texts: ["очень длинная подпись связи"] })
|
||||
obstacles.push(card(542, 400), card(780, 400))
|
||||
const placed = placeMapLinkLabels(labels, obstacles)
|
||||
assert.ok(placed.length >= 3, "подписи трёх сходящихся связей размещены")
|
||||
assert.equal(placed.find((p) => p.id === "flat"), undefined, "не влезающая подпись не рисуется")
|
||||
for (const [i, a] of placed.entries()) {
|
||||
for (const o of obstacles) assert.equal(hit(pill(a), o), false, a.id + " поверх карточки")
|
||||
for (const b of placed.slice(i + 1)) assert.equal(hit(pill(a), pill(b)), false, a.id + " поверх " + b.id)
|
||||
}
|
||||
})
|
||||
|
||||
test("ленты NetFlow уложены стопкой у узла и толще у большей скорости", () => {
|
||||
const exit = { x: 780, y: 300 }
|
||||
const flows = [
|
||||
{ id: "a", from: exit, fromHalfW: 80, to: { x: 1080, y: 200 }, toHalfW: 140, bps: 300 },
|
||||
{ id: "b", from: exit, fromHalfW: 80, to: { x: 1080, y: 400 }, toHalfW: 140, bps: 100 },
|
||||
]
|
||||
const [a, b] = mapRibbons(flows, 40)
|
||||
assert.equal(a.w, 30)
|
||||
assert.equal(b.w, 10)
|
||||
// У выхода ленты лежат вплотную по центру карточки (стопка 40 px при пике 400 — сумма у выхода).
|
||||
assert.match(a.d, /^M 860 295\.0 /)
|
||||
assert.match(b.d, /^M 860 315\.0 /)
|
||||
assert.match(a.d, / 940 200\.0$/)
|
||||
})
|
||||
|
||||
test("совпадающие середины двух связей разводятся по своим кривым", () => {
|
||||
const a = mapLinkPath({ x: 0, y: 0 }, 0, { x: 300, y: 200 }, 0)
|
||||
const b = mapLinkPath({ x: 0, y: 200 }, 0, { x: 300, y: 0 }, 0)
|
||||
const placed = placeMapLinkLabels([{ id: "a", link: a, texts: ["12 мс"] }, { id: "b", link: b, texts: ["14 мс"] }], [])
|
||||
assert.equal(placed.length, 2)
|
||||
assert.equal(hit(pill(placed[0]), pill(placed[1])), false)
|
||||
})
|
||||