Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4097e1a6fc | ||
|
|
7cf17c7283 | ||
|
|
4eafc78c8e | ||
|
|
d174bca5d6 | ||
|
|
2ca40fbb4d |
No files matched your search
+499
-218
File diff suppressed because it is too large.
Load diff
+132
-59
@@ -1,6 +1,8 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState, useMemo, useEffect, useRef, 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 { Alert, AlertTitle, AlertDescription } from "@/components/reui/alert"
|
||||||
import { peakOfCombinedTraffic, projectTrafficObservations, sumObservedTraffic, type TrafficObservationMeta } from "@/lib/traffic-observations"
|
import { peakOfCombinedTraffic, projectTrafficObservations, sumObservedTraffic, type TrafficObservationMeta } from "@/lib/traffic-observations"
|
||||||
import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status"
|
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 { KpiStatGrid } from "@/components/reui-kit/kpi-stat-grid"
|
||||||
import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart"
|
import { TrafficMiniChart } from "@/components/reui-kit/traffic-mini-chart"
|
||||||
import { TrafficRxTxChart } from "@/components/reui-kit/traffic-rx-tx-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 { Sparkline } from "@/components/sparkline"
|
||||||
import { StatusDot } from "@/components/status-dot"
|
import { StatusDot } from "@/components/status-dot"
|
||||||
import { Flag } from "@/components/flag"
|
import { Flag } from "@/components/flag"
|
||||||
import {
|
import {
|
||||||
RefreshCwIcon, TrendingUpIcon, ChartPieIcon,
|
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"
|
} from "lucide-react"
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
import { fmtGiB, fmtRate } from "@/lib/fmt-rate"
|
import { fmtGiB, fmtRate } from "@/lib/fmt-rate"
|
||||||
@@ -37,6 +39,7 @@ import { Badge } from "@/components/reui/badge"
|
|||||||
import {
|
import {
|
||||||
IFACE_TYPE_LABEL,
|
IFACE_TYPE_LABEL,
|
||||||
INIT_USERS,
|
INIT_USERS,
|
||||||
|
MOCK_IFACE_CATALOG,
|
||||||
ROLE_LABEL,
|
ROLE_LABEL,
|
||||||
type InterfaceType,
|
type InterfaceType,
|
||||||
} from "@/lib/users"
|
} 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 GroupMode = "servers" | "users" | "ifaces" | "flows"
|
||||||
type FlowScope = "servers" | "users"
|
type FlowScope = "servers" | "users"
|
||||||
|
const ALL_EXPORTERS = "__all_exporters__"
|
||||||
type SortField = "rx" | "tx" | "name" | "sessions"
|
type SortField = "rx" | "tx" | "name" | "sessions"
|
||||||
type SortDir = "asc" | "desc"
|
type SortDir = "asc" | "desc"
|
||||||
|
|
||||||
@@ -671,7 +675,7 @@ function ServerDetail({
|
|||||||
</div>
|
</div>
|
||||||
</DetailHeader>
|
</DetailHeader>
|
||||||
<TrafficObservationStatus observations={sel.observations} unknown={sel.rxNow == null || sel.txNow == null} />
|
<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
|
<KvStats
|
||||||
label="Скорость выбранного сервера"
|
label="Скорость выбранного сервера"
|
||||||
items={[
|
items={[
|
||||||
@@ -703,7 +707,7 @@ function UserDetail({ sel, range, setRange }: { sel: UserTraffic; range: Range;
|
|||||||
<OfflinePlaceholder text="Нет привязанных интерфейсов у этого пользователя" />
|
<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
|
<KvStats
|
||||||
label="Скорость выбранного клиента"
|
label="Скорость выбранного клиента"
|
||||||
items={[
|
items={[
|
||||||
@@ -742,7 +746,7 @@ function IfaceDetail({ sel, range, setRange }: { sel: BoundIfaceTraffic; range:
|
|||||||
<Flag code={sel.serverCountry} />{sel.serverSite}
|
<Flag code={sel.serverCountry} />{sel.serverSite}
|
||||||
</span>
|
</span>
|
||||||
</DetailHeader>
|
</DetailHeader>
|
||||||
<TrafficRxTxChart rx={sel.rxSeries} tx={sel.txSeries} range={range} />
|
<TrafficRxTxChart key={range} rx={sel.rxSeries} tx={sel.txSeries} range={range} scrub embedded />
|
||||||
<KvStats
|
<KvStats
|
||||||
label="Скорость выбранного интерфейса"
|
label="Скорость выбранного интерфейса"
|
||||||
items={[
|
items={[
|
||||||
@@ -818,6 +822,38 @@ const toLiveUser = (u: UserTraffic & { interfaces?: BoundIfaceTraffic[] }): User
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function TrafficPage() {
|
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 { mode, backendUrl } = useDataSource()
|
||||||
const isLive = mode === "live"
|
const isLive = mode === "live"
|
||||||
const [trafficClock, setTrafficClock] = useState(() => Date.now())
|
const [trafficClock, setTrafficClock] = useState(() => Date.now())
|
||||||
@@ -828,12 +864,13 @@ export default function TrafficPage() {
|
|||||||
}, [isLive])
|
}, [isLive])
|
||||||
const apiFetch = useMemo(() => makeApiFetch(backendUrl), [backendUrl])
|
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 [sortField, setSortField] = useState<SortField>("rx")
|
||||||
const [sortDir, setSortDir] = useState<SortDir>("desc")
|
const [sortDir, setSortDir] = useState<SortDir>("desc")
|
||||||
const [selectedId, setSelectedId] = useState("srv1")
|
const linkedId = view === "servers" ? server : user ?? server
|
||||||
const initialServerApplied = useRef(false)
|
const [selectedId, setSelectedId] = useState(linkedId ?? (view === "flows" ? mapExporters ? "" : ALL_EXPORTERS : "srv1"))
|
||||||
const [range, setRange] = useState<Range>("1h")
|
const keptLink = groupMode === view && selectedId === linkedId
|
||||||
|
const [range, setRange] = useState<Range>(view === "flows" ? "5m" : "1h")
|
||||||
const [search, setSearch] = useState("")
|
const [search, setSearch] = useState("")
|
||||||
const [trafficRetry, setTrafficRetry] = useState(0)
|
const [trafficRetry, setTrafficRetry] = useState(0)
|
||||||
const [liveRetry, setLiveRetry] = useState(0)
|
const [liveRetry, setLiveRetry] = useState(0)
|
||||||
@@ -855,7 +892,7 @@ export default function TrafficPage() {
|
|||||||
const [detailResult, setDetailResult] = useState<{ key: string; server: ServerTraffic | null; receivedAt?: number; error: string | null } | null>(null)
|
const [detailResult, setDetailResult] = useState<{ key: string; server: ServerTraffic | null; receivedAt?: number; error: string | null } | null>(null)
|
||||||
const [liveUsers, setLiveUsers] = useState<UserTraffic[]>([])
|
const [liveUsers, setLiveUsers] = useState<UserTraffic[]>([])
|
||||||
const [liveBoundIfaces, setLiveBoundIfaces] = useState<BoundIfaceTraffic[]>([])
|
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 [flowRetry, setFlowRetry] = useState(0)
|
||||||
const flowKey = JSON.stringify([isLive, groupMode, backendUrl, range, flowScope, flowRetry])
|
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)
|
const [flowResult, setFlowResult] = useState<{ key: string; receivedAt?: number; monthlyServers?: ServerRead[]; stats?: FlowStatsDto; exporters?: FlowEntityCard[]; clients?: FlowEntityCard[]; cardWindow?: FlowStatsDto["sourceWindow"]; error?: string } | null>(null)
|
||||||
@@ -869,7 +906,7 @@ export default function TrafficPage() {
|
|||||||
&& trafficClock - collectorReading.receivedAt > 35_000
|
&& trafficClock - collectorReading.receivedAt > 35_000
|
||||||
? { ...collectorReading.status, listenerBound: false, collectorCountersSource: "last-known" }
|
? { ...collectorReading.status, listenerBound: false, collectorCountersSource: "last-known" }
|
||||||
: collectorReading.status
|
: 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 flowClients = useMemo(() => currentFlows?.clients ?? [], [currentFlows])
|
||||||
const [flowMonth, setFlowMonth] = useState(() => new Date().toISOString().slice(0, 7))
|
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)
|
const flowMonthValid = /^(?!0000)\d{4}-(0[1-9]|1[0-2])$/.test(flowMonth) && flowMonth <= new Date().toISOString().slice(0, 7)
|
||||||
@@ -885,6 +922,7 @@ export default function TrafficPage() {
|
|||||||
const [overlayOpen, setOverlayOpen] = useState(false)
|
const [overlayOpen, setOverlayOpen] = useState(false)
|
||||||
const [catalogServers, setCatalogServers] = useState<ServerRead[]>([])
|
const [catalogServers, setCatalogServers] = useState<ServerRead[]>([])
|
||||||
const effectiveMode: GroupMode = groupMode
|
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 detailKey = JSON.stringify([isLive, backendUrl, effectiveMode, selectedId, range, selectedIface, detailRetry])
|
||||||
const currentDetail = detailResult?.key === detailKey ? detailResult : null
|
const currentDetail = detailResult?.key === detailKey ? detailResult : null
|
||||||
const detailBusy = isLive && effectiveMode === "servers" && Boolean(selectedId) && currentDetail === null
|
const detailBusy = isLive && effectiveMode === "servers" && Boolean(selectedId) && currentDetail === null
|
||||||
@@ -899,7 +937,7 @@ export default function TrafficPage() {
|
|||||||
range === "30d"
|
range === "30d"
|
||||||
? /^[1-9]\d*$/.test(selectedId) && Number.isSafeInteger(Number(selectedId)) && Boolean(currentFlows?.monthlyServers?.some(server => String(server.id) === selectedId))
|
? /^[1-9]\d*$/.test(selectedId) && Number.isSafeInteger(Number(selectedId)) && Boolean(currentFlows?.monthlyServers?.some(server => String(server.id) === selectedId))
|
||||||
: flowScope === "servers"
|
: 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)
|
: Boolean(selectedId) && flowClients.some(card => card.id === selectedId)
|
||||||
)
|
)
|
||||||
const flowLiveEnabled = confirmedFlowSelection && effectiveMode === "flows" && range === "5m"
|
const flowLiveEnabled = confirmedFlowSelection && effectiveMode === "flows" && range === "5m"
|
||||||
@@ -907,7 +945,7 @@ export default function TrafficPage() {
|
|||||||
enabled: flowLiveEnabled,
|
enabled: flowLiveEnabled,
|
||||||
backendUrl,
|
backendUrl,
|
||||||
range,
|
range,
|
||||||
serverId: flowScope === "servers" ? selectedId : undefined,
|
serverId: flowScope === "servers" && !allExporters ? selectedId : undefined,
|
||||||
userId: flowScope === "users" ? selectedId : undefined,
|
userId: flowScope === "users" ? selectedId : undefined,
|
||||||
iface: flowIface,
|
iface: flowIface,
|
||||||
dedup: flowDedup,
|
dedup: flowDedup,
|
||||||
@@ -917,17 +955,32 @@ export default function TrafficPage() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isLive || groupMode === "flows") return
|
if (!isLive || groupMode === "flows") return
|
||||||
let cancelled = false
|
const controller = new AbortController()
|
||||||
const loadLiveTraffic = async (targetRange: Range) => {
|
const init = { signal: controller.signal }
|
||||||
const key = JSON.stringify([isLive, backendUrl, targetRange, groupMode, trafficRetry])
|
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 {
|
try {
|
||||||
const q = encodeURIComponent(targetRange === "30d" ? "24h" : targetRange)
|
|
||||||
const [srvRes, usersRes, ifacesRes] = await Promise.all([
|
const [srvRes, usersRes, ifacesRes] = await Promise.all([
|
||||||
apiFetch<{ servers: LiveTrafficServer[]; peaks?: { rx: number | null; tx: number | null } }>(`/api/traffic/servers?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}`),
|
apiFetch<{ users: UserTraffic[] }>(`/api/traffic/users?range=${q}`, init),
|
||||||
apiFetch<{ interfaces: BoundIfaceTraffic[] }>(`/api/traffic/bound-interfaces?range=${q}`),
|
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 liveIfaces = ifacesRes.interfaces.map(toLiveBound)
|
||||||
const mapped: ServerTraffic[] = srvRes.servers.map((s) => {
|
const mapped: ServerTraffic[] = srvRes.servers.map((s) => {
|
||||||
const base = toLiveServer(s)
|
const base = toLiveServer(s)
|
||||||
@@ -938,23 +991,21 @@ export default function TrafficPage() {
|
|||||||
setLiveServerOwner(JSON.stringify([isLive, backendUrl]))
|
setLiveServerOwner(JSON.stringify([isLive, backendUrl]))
|
||||||
setLiveUsers(mappedUsers)
|
setLiveUsers(mappedUsers)
|
||||||
setLiveBoundIfaces(liveIfaces)
|
setLiveBoundIfaces(liveIfaces)
|
||||||
setTrafficState({ key, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
|
setTrafficState({ key: trafficKey, status: "ready", receivedAt: Date.now(), peaks: srvRes.peaks })
|
||||||
const requestedServer = groupMode === "servers" && mapped.length && !initialServerApplied.current
|
if (groupMode === "users") timer = setTimeout(() => { void refreshUsers() }, 15_000)
|
||||||
? new URLSearchParams(window.location.search).get("server") : null
|
|
||||||
if (groupMode === "servers" && mapped.length) initialServerApplied.current = true
|
|
||||||
setSelectedId((prev) => {
|
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 === "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 ?? "")
|
if (groupMode === "ifaces") return liveIfaces.some((x) => x.id === prev) ? prev : (liveIfaces[0]?.id ?? "")
|
||||||
if (requestedServer && mapped.some((x) => x.id === requestedServer)) return requestedServer
|
|
||||||
return mapped.some((x) => x.id === prev) ? prev : (mapped[0]?.id ?? "")
|
return mapped.some((x) => x.id === prev) ? prev : (mapped[0]?.id ?? "")
|
||||||
})
|
})
|
||||||
} catch (e) {
|
} 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)
|
void loadLiveTraffic()
|
||||||
return () => { cancelled = true }
|
return () => { controller.abort(); clearTimeout(timer) }
|
||||||
}, [apiFetch, isLive, groupMode, backendUrl, trafficRetry, range])
|
}, [apiFetch, isLive, groupMode, backendUrl, trafficKey, range, view, linkedId])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isLive || groupMode !== "flows" || range === "30d") return
|
if (!isLive || groupMode !== "flows" || range === "30d") return
|
||||||
@@ -984,8 +1035,9 @@ export default function TrafficPage() {
|
|||||||
if (range === "30d") {
|
if (range === "30d") {
|
||||||
void listServers(backendUrl).then(servers => {
|
void listServers(backendUrl).then(servers => {
|
||||||
if (cancelled) return
|
if (cancelled) return
|
||||||
setFlowResult({ key: flowKey, receivedAt: Date.now(), monthlyServers: servers })
|
const available = mapExporters ? servers.filter(server => mapExporters.includes(String(server.id))) : servers
|
||||||
setSelectedId(prev => servers.some(server => String(server.id) === prev) ? prev : String(servers[0]?.id ?? ""))
|
setFlowResult({ key: flowKey, receivedAt: Date.now(), monthlyServers: available })
|
||||||
|
setSelectedId(prev => available.some(server => String(server.id) === prev) ? prev : String(available[0]?.id ?? ""))
|
||||||
}).catch(error => {
|
}).catch(error => {
|
||||||
if (!cancelled) setFlowResult({ key: flowKey, error: error instanceof Error ? error.message : "Не удалось загрузить каталог серверов" })
|
if (!cancelled) setFlowResult({ key: flowKey, error: error instanceof Error ? error.message : "Не удалось загрузить каталог серверов" })
|
||||||
})
|
})
|
||||||
@@ -1002,7 +1054,9 @@ export default function TrafficPage() {
|
|||||||
setFlowResult({ key: flowKey, receivedAt: Date.now(), stats, exporters: exporters.exporters, clients: clients.clients,
|
setFlowResult({ key: flowKey, receivedAt: Date.now(), stats, exporters: exporters.exporters, clients: clients.clients,
|
||||||
cardWindow: flowScope === "users" ? clients.sourceWindow : exporters.sourceWindow })
|
cardWindow: flowScope === "users" ? clients.sourceWindow : exporters.sourceWindow })
|
||||||
setSelectedId(prev => {
|
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 ?? "")
|
return list.some(x => x.id === prev) ? prev : (list[0]?.id ?? "")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1010,7 +1064,7 @@ export default function TrafficPage() {
|
|||||||
if (!cancelled) setFlowResult({ key: flowKey, error: e instanceof Error ? e.message : "Не удалось загрузить потоки" })
|
if (!cancelled) setFlowResult({ key: flowKey, error: e instanceof Error ? e.message : "Не удалось загрузить потоки" })
|
||||||
})
|
})
|
||||||
return () => { cancelled = true }
|
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 analyticsKey = JSON.stringify([flowKey, selectedId, flowIface, flowDedup, flowExcludeMesh, flowExcludeOverlay, analyticsRetry, range === "30d" ? flowMonth : null])
|
||||||
const currentAnalytics = analyticsResult?.key === analyticsKey ? analyticsResult : null
|
const currentAnalytics = analyticsResult?.key === analyticsKey ? analyticsResult : null
|
||||||
@@ -1021,7 +1075,7 @@ export default function TrafficPage() {
|
|||||||
const request = range === "30d"
|
const request = range === "30d"
|
||||||
? getFlowMonthly(backendUrl, { month: flowMonth, serverId: flowScope === "servers" ? selectedId : undefined }).then(monthly => ({ monthly }))
|
? getFlowMonthly(backendUrl, { month: flowMonth, serverId: flowScope === "servers" ? selectedId : undefined }).then(monthly => ({ monthly }))
|
||||||
: getFlowAnalytics(backendUrl, {
|
: getFlowAnalytics(backendUrl, {
|
||||||
range, serverId: flowScope === "servers" ? selectedId : undefined,
|
range, serverId: flowScope === "servers" && !allExporters ? selectedId : undefined,
|
||||||
userId: flowScope === "users" ? selectedId : undefined,
|
userId: flowScope === "users" ? selectedId : undefined,
|
||||||
iface: flowIface, dedup: flowDedup, excludeMesh: flowExcludeMesh, excludeOverlay: flowExcludeOverlay,
|
iface: flowIface, dedup: flowDedup, excludeMesh: flowExcludeMesh, excludeOverlay: flowExcludeOverlay,
|
||||||
}).then(data => ({ data }))
|
}).then(data => ({ data }))
|
||||||
@@ -1031,7 +1085,7 @@ export default function TrafficPage() {
|
|||||||
if (!cancelled) setAnalyticsResult({ key: analyticsKey, error: e instanceof Error ? e.message : "Не удалось загрузить аналитику" })
|
if (!cancelled) setAnalyticsResult({ key: analyticsKey, error: e instanceof Error ? e.message : "Не удалось загрузить аналитику" })
|
||||||
})
|
})
|
||||||
return () => { cancelled = true }
|
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(() => {
|
useEffect(() => {
|
||||||
if (!isLive) return
|
if (!isLive) return
|
||||||
@@ -1041,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 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 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 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(
|
const ifaceCatalog = isLive ? serverIfaces : MOCK_IFACE_CATALOG[selectedId] ?? []
|
||||||
() => hideDisabledIfaces ? serverIfaces.filter((i) => !i.disabled && i.running) : serverIfaces,
|
const visibleIfaces = hideDisabledIfaces ? ifaceCatalog.filter(i => !i.disabled && i.running) : ifaceCatalog
|
||||||
[serverIfaces, hideDisabledIfaces],
|
|
||||||
)
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!confirmedLiveServer || effectiveMode !== "servers") {
|
if (!isLive || !confirmedLiveServer || effectiveMode !== "servers") {
|
||||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
setServerIfaces([])
|
setServerIfaces([])
|
||||||
setSelectedIface("__all__")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
setServerIfaces([])
|
setServerIfaces([])
|
||||||
setSelectedIface("__all__")
|
|
||||||
apiFetch<{ interfaces: LiveTrafficInterface[] }>(`/api/traffic/servers/${encodeURIComponent(selectedId)}/interfaces`)
|
apiFetch<{ interfaces: LiveTrafficInterface[] }>(`/api/traffic/servers/${encodeURIComponent(selectedId)}/interfaces`)
|
||||||
.then((res) => { if (!cancelled) setServerIfaces(res.interfaces) })
|
.then((res) => { if (!cancelled) setServerIfaces(res.interfaces) })
|
||||||
.catch(() => { if (!cancelled) setServerIfaces([]) })
|
.catch(() => { if (!cancelled) setServerIfaces([]) })
|
||||||
return () => { cancelled = true }
|
return () => { cancelled = true }
|
||||||
}, [confirmedLiveServer, selectedId, effectiveMode, apiFetch])
|
}, [isLive, confirmedLiveServer, selectedId, effectiveMode, apiFetch])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!confirmedLiveServer || effectiveMode !== "servers") {
|
if (!confirmedLiveServer || effectiveMode !== "servers") {
|
||||||
@@ -1083,6 +1133,7 @@ export default function TrafficPage() {
|
|||||||
|
|
||||||
const handleModeChange = (next: GroupMode) => {
|
const handleModeChange = (next: GroupMode) => {
|
||||||
setGroupMode(next)
|
setGroupMode(next)
|
||||||
|
setSelectedIface("__all__")
|
||||||
if (next === "servers") {
|
if (next === "servers") {
|
||||||
setSelectedId(activeServerTraffic[0]?.id ?? "srv1")
|
setSelectedId(activeServerTraffic[0]?.id ?? "srv1")
|
||||||
if (range === "30d") setRange("1h")
|
if (range === "30d") setRange("1h")
|
||||||
@@ -1170,12 +1221,15 @@ export default function TrafficPage() {
|
|||||||
const monthlyServer = monthlyServers.find(server => String(server.id) === selectedId)
|
const monthlyServer = monthlyServers.find(server => String(server.id) === selectedId)
|
||||||
const selFlowCard = range === "30d"
|
const selFlowCard = range === "30d"
|
||||||
? (monthlyServer ? { id: String(monthlyServer.id), name: monthlyServer.name, country: monthlyServer.country, site: monthlyServer.site } : null)
|
? (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 displayedFlow = currentFlows && !liveError ? (flowLiveSample ?? currentAnalytics?.data ?? null) : null
|
||||||
|
|
||||||
const selServer = useMemo(() => activeServerTraffic.find(s => s.id === selectedId) ?? activeServerTraffic[0], [selectedId, activeServerTraffic])
|
const selServer = activeServerTraffic.find(s => s.id === selectedId) ?? (keptLink ? undefined : activeServerTraffic[0])
|
||||||
const detailServer = isLive ? (currentDetail?.server ? { ...currentDetail.server, ...projectTrafficObservations(currentDetail.server, trafficClock), boundIfaces: currentDetail.server.boundIfaces.map(toLiveBound) } : null) : selServer
|
const demoIfaceRows = !isLive && selectedIface !== "__all__" ? selServer?.boundIfaces.filter(row => row.interfaceName === selectedIface && !row.peerPublicKey) ?? [] : []
|
||||||
const selUser = useMemo(() => activeUserTraffic.find(u => u.id === selectedId) ?? activeUserTraffic[0], [selectedId, activeUserTraffic])
|
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 selIface = useMemo(() => activeBoundIfaces.find(c => c.id === selectedId) ?? activeBoundIfaces[0], [selectedId, activeBoundIfaces])
|
||||||
|
|
||||||
const kpiSource = effectiveMode === "users"
|
const kpiSource = effectiveMode === "users"
|
||||||
@@ -1275,7 +1329,7 @@ export default function TrafficPage() {
|
|||||||
ifaces: (isLive ? liveBoundIfaces : boundIfaces).length,
|
ifaces: (isLive ? liveBoundIfaces : boundIfaces).length,
|
||||||
flows: null,
|
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 listTitle = effectiveMode === "servers" ? "Серверы" : effectiveMode === "users" ? "Клиенты" : "Интерфейсы"
|
||||||
const listShown = effectiveMode === "servers" ? sortedServers.length : effectiveMode === "users" ? sortedUsers.length : sortedIfaces.length
|
const listShown = effectiveMode === "servers" ? sortedServers.length : effectiveMode === "users" ? sortedUsers.length : sortedIfaces.length
|
||||||
|
|
||||||
@@ -1291,14 +1345,19 @@ export default function TrafficPage() {
|
|||||||
description="Счётчики интерфейсов и потоки IPFIX по серверам, клиентам и интерфейсам"
|
description="Счётчики интерфейсов и потоки IPFIX по серверам, клиентам и интерфейсам"
|
||||||
actions={
|
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" variant="outline" onClick={() => { handleModeChange("flows"); setRange("30d") }}>Месячный отчёт</Button>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (effectiveMode === "flows") setFlowRetry(value => value + 1)
|
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}
|
disabled={refreshBusy}
|
||||||
|
aria-busy={refreshBusy}
|
||||||
>
|
>
|
||||||
<RefreshCwIcon className={cn("size-4", refreshBusy && "animate-spin")} />Обновить
|
<RefreshCwIcon className={cn("size-4", refreshBusy && "animate-spin")} />Обновить
|
||||||
</Button>
|
</Button>
|
||||||
@@ -1320,6 +1379,12 @@ export default function TrafficPage() {
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</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
|
{!(effectiveMode === "flows" && range === "30d") && (!isLive || !(effectiveMode === "flows" ? liveError : trafficError)) && <KpiStatGrid
|
||||||
isLoading={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)}
|
isLoading={isLive && (effectiveMode === "flows" ? liveBusy : trafficLoading)}
|
||||||
aria-label="Сводка трафика"
|
aria-label="Сводка трафика"
|
||||||
@@ -1367,6 +1432,7 @@ export default function TrafficPage() {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
aria-pressed={flowScope === "users"}
|
aria-pressed={flowScope === "users"}
|
||||||
|
disabled={Boolean(mapExporters)}
|
||||||
onClick={() => { setFlowScope("users"); setFlowIface("__all__"); if (range === "30d") setRange("1h") }}
|
onClick={() => { setFlowScope("users"); setFlowIface("__all__"); if (range === "30d") setRange("1h") }}
|
||||||
className={cn(
|
className={cn(
|
||||||
"text-xs px-2 py-0.5 rounded border transition-colors",
|
"text-xs px-2 py-0.5 rounded border transition-colors",
|
||||||
@@ -1408,6 +1474,8 @@ export default function TrafficPage() {
|
|||||||
</div>
|
</div>
|
||||||
{range === "30d" && <p className="text-xs text-muted-foreground">Серверы из каталога, включая неактивные. Удалённые серверы в список не входят.</p>}
|
{range === "30d" && <p className="text-xs text-muted-foreground">Серверы из каталога, включая неактивные. Удалённые серверы в список не входят.</p>}
|
||||||
<div className="flex flex-col gap-2">
|
<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) => (
|
{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
|
<FlowEntityCardView
|
||||||
key={card.id}
|
key={card.id}
|
||||||
@@ -1447,6 +1515,9 @@ export default function TrafficPage() {
|
|||||||
excludeOverlay={flowExcludeOverlay}
|
excludeOverlay={flowExcludeOverlay}
|
||||||
onExcludeOverlay={setFlowExcludeOverlay}
|
onExcludeOverlay={setFlowExcludeOverlay}
|
||||||
liveHint={flowLiveHint}
|
liveHint={flowLiveHint}
|
||||||
|
initialService={view === "flows" ? service : undefined}
|
||||||
|
initialCountry={country}
|
||||||
|
mapNodes={mapNodes}
|
||||||
emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)}
|
emptyHint={analyticsLoading ? "Загрузка аналитики…" : currentAnalytics?.error ? "Не удалось получить данные выбранного среза" : flowEmptyHint(collectorStatus)}
|
||||||
/>
|
/>
|
||||||
</FramePanel>
|
</FramePanel>
|
||||||
@@ -1461,7 +1532,7 @@ export default function TrafficPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</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 ── */}
|
{/* ── left panel ── */}
|
||||||
<div className="flex min-w-0 flex-col gap-4">
|
<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">
|
<SectionFrame title={listTitle} description={`${listShown} из ${modeCount[effectiveMode] ?? listShown} · сортировка и поиск`} panelClassName="flex flex-col gap-3 p-2.5">
|
||||||
@@ -1499,9 +1570,9 @@ export default function TrafficPage() {
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{/* entity list */}
|
{/* 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 => (
|
{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 => (
|
{effectiveMode === "users" && sortedUsers.map(u => (
|
||||||
<UserCard key={u.id} u={u} selected={u.id === selectedId} onClick={() => setSelectedId(u.id)} />
|
<UserCard key={u.id} u={u} selected={u.id === selectedId} onClick={() => setSelectedId(u.id)} />
|
||||||
@@ -1518,13 +1589,13 @@ export default function TrafficPage() {
|
|||||||
<div className="flex min-w-0 flex-col gap-4">
|
<div className="flex min-w-0 flex-col gap-4">
|
||||||
<SectionFrame bare className="w-full min-w-0">
|
<SectionFrame bare className="w-full min-w-0">
|
||||||
<FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
|
<FramePanel className="flex-1 min-w-0 p-3 sm:p-5">
|
||||||
{isLive && effectiveMode === "servers" && (
|
{effectiveMode === "servers" && (
|
||||||
<div className="mb-3 pb-3 border-b">
|
<div role="group" aria-label="Интерфейсы выбранного сервера" className="mb-3 pb-3 border-b">
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
<span className="text-xs text-muted-foreground mr-1">Интерфейс:</span>
|
<span className="text-xs text-muted-foreground mr-1">Интерфейс:</span>
|
||||||
<button
|
<button
|
||||||
type="button" aria-pressed={hideDisabledIfaces}
|
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(
|
className={cn(
|
||||||
"inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium transition-all",
|
"inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium transition-all",
|
||||||
hideDisabledIfaces
|
hideDisabledIfaces
|
||||||
@@ -1570,6 +1641,7 @@ export default function TrafficPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{!isLive && effectiveMode === "servers" && selectedIface !== "__all__" && !detailServer && <OfflinePlaceholder text="В демоснимке нет замеров этого интерфейса" />}
|
||||||
{isLive && effectiveMode === "servers" && !detailServer && <>
|
{isLive && effectiveMode === "servers" && !detailServer && <>
|
||||||
<DetailHeader range={range} setRange={setRange}><h2 className="text-base font-semibold">{selServer?.name ?? "Трафик сервера"}</h2></DetailHeader>
|
<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>}
|
{detailBusy && <p role="status" className="text-sm text-muted-foreground">Загрузка выбранного периода и интерфейса…</p>}
|
||||||
@@ -1588,6 +1660,7 @@ export default function TrafficPage() {
|
|||||||
</>}
|
</>}
|
||||||
{effectiveMode === "servers" && detailServer && (
|
{effectiveMode === "servers" && detailServer && (
|
||||||
<ServerDetail
|
<ServerDetail
|
||||||
|
key={selectedId + ":" + selectedIface}
|
||||||
sel={detailServer}
|
sel={detailServer}
|
||||||
range={range}
|
range={range}
|
||||||
setRange={setRange}
|
setRange={setRange}
|
||||||
@@ -1599,8 +1672,8 @@ export default function TrafficPage() {
|
|||||||
: liveSample ? "live" : isLive ? "История · ожидание live" : undefined}
|
: liveSample ? "live" : isLive ? "История · ожидание live" : undefined}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{effectiveMode === "users" && selUser && <UserDetail sel={selUser} range={range} setRange={setRange} />}
|
{effectiveMode === "users" && selUser && <UserDetail key={selUser.id} sel={selUser} range={range} setRange={setRange} />}
|
||||||
{effectiveMode === "ifaces" && selIface && <IfaceDetail sel={selIface} range={range} setRange={setRange} />}
|
{effectiveMode === "ifaces" && selIface && <IfaceDetail key={selIface.id} sel={selIface} range={range} setRange={setRange} />}
|
||||||
</FramePanel>
|
</FramePanel>
|
||||||
</SectionFrame>
|
</SectionFrame>
|
||||||
{effectiveMode === "servers" && detailServer && detailServer.boundIfaces.length > 0 ? <ServerIfacesFrame server={detailServer} /> : null}
|
{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",
|
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)),
|
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,
|
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 }
|
backgroundEnrichmentStarted: false, collectorStarted: false }
|
||||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ аналитики превышает 1 МиБ; уменьшите страницу", 409)
|
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ аналитики превышает 1 МиБ; уменьшите страницу", 409)
|
||||||
return withCurrentFlowReadQuality(output,context)
|
return withCurrentFlowReadQuality(output,context)
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ export function registerFlowCatalogActions(register: typeof add) {
|
|||||||
for (const server of selected) await assertTrafficHistorySource(context, server)
|
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,
|
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),
|
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)
|
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,
|
historicalOwnershipVerified: false, currentTrafficVerified: false,
|
||||||
rateSemantics: "REST live rates: filtered or overlay-inclusive rates use the latest complete retained minute with a window-average fallback",
|
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",
|
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 }
|
collectorStarted: false, backgroundEnrichmentStarted: false }
|
||||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ live превышает 1 МиБ; уменьшите страницу или число samples", 409)
|
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ live превышает 1 МиБ; уменьшите страницу или число samples", 409)
|
||||||
await authorize()
|
await authorize()
|
||||||
|
|||||||
@@ -49,11 +49,11 @@ export function registerFlowMapActions(register: typeof add) {
|
|||||||
await authorize()
|
await authorize()
|
||||||
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow,
|
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,
|
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,
|
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
|
||||||
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
|
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
|
||||||
rowSumIsNetworkTotal: false, historicalOwnershipVerified: 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 }
|
collectorStarted: false, backgroundEnrichmentStarted: false, tracerouteExecuted: false }
|
||||||
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ карты превышает 1 МиБ; уменьшите страницы", 409)
|
if (Buffer.byteLength(JSON.stringify(output)) > 1048576) throw new McpError("STATE_UNAVAILABLE", "Ответ карты превышает 1 МиБ; уменьшите страницы", 409)
|
||||||
return withCurrentFlowReadQuality(output,context)
|
return withCurrentFlowReadQuality(output,context)
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import { getEnabledServerById } from "../services/wireguard-live.js"
|
|||||||
import { readTrafficCollectionContext } from "../services/traffic-collection-state.js"
|
import { readTrafficCollectionContext } from "../services/traffic-collection-state.js"
|
||||||
import { readServerTrafficHistory, readServerTrafficHistoryWithSeries, readServerTrafficInterfaces } from "../services/traffic-history-read.js"
|
import { readServerTrafficHistory, readServerTrafficHistoryWithSeries, readServerTrafficInterfaces } from "../services/traffic-history-read.js"
|
||||||
import { mergeBuiltTraffic } from "../services/traffic-rate.js"
|
import { mergeBuiltTraffic } from "../services/traffic-rate.js"
|
||||||
|
import { getUserById } from "../modules/users/service/users-service.js"
|
||||||
import {
|
import {
|
||||||
buildBoundInterfaceTraffic,
|
buildBoundInterfaceTraffic,
|
||||||
buildUserTrafficList,
|
buildUserTrafficList,
|
||||||
@@ -236,9 +237,9 @@ const trafficRoutes: FastifyPluginAsyncZod = async (app) => {
|
|||||||
const minutes = rangeToMinutes(q.range)
|
const minutes = rangeToMinutes(q.range)
|
||||||
const rangeEndMs = Date.now()
|
const rangeEndMs = Date.now()
|
||||||
const rangeStartMs = rangeEndMs - minutes * 60_000
|
const rangeStartMs = rangeEndMs - minutes * 60_000
|
||||||
const users = await buildUserTrafficList(rangeStartMs, rangeEndMs)
|
const source = await getUserById(id)
|
||||||
const user = users.find((u) => u.id === id)
|
if (!source) return reply.status(404).send({ error: "Пользователь не найден" })
|
||||||
if (!user) return reply.status(404).send({ error: "Пользователь не найден" })
|
const [user] = await buildUserTrafficList(rangeStartMs, rangeEndMs, { users: [source] })
|
||||||
return reply.send({ user })
|
return reply.send({ user })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -37,7 +37,8 @@ import {
|
|||||||
getServerCatalog,
|
getServerCatalog,
|
||||||
latestWireBps,
|
latestWireBps,
|
||||||
loadFlowTopology,
|
loadFlowTopology,
|
||||||
resolveClient,
|
flowClientInterfaces,
|
||||||
|
resolveFlowClient,
|
||||||
resolveEn,
|
resolveEn,
|
||||||
} from "./traffic-flow-topology.js"
|
} from "./traffic-flow-topology.js"
|
||||||
|
|
||||||
@@ -95,18 +96,6 @@ function bump(
|
|||||||
map.set(id, prev)
|
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()) {
|
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 slots = Math.min(60, Math.max(5, minutes))
|
||||||
const slotMs = (minutes * 60_000) / slots
|
const slotMs = (minutes * 60_000) / slots
|
||||||
@@ -241,7 +230,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
|||||||
const excludeOverlay = q.excludeOverlay !== false
|
const excludeOverlay = q.excludeOverlay !== false
|
||||||
await authorize()
|
await authorize()
|
||||||
const topo = await loadFlowTopology(scope?.serverIds, 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 && q.userId && !allow?.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||||
|
|
||||||
if (!scope) refreshFlowCatalogInBackground()
|
if (!scope) refreshFlowCatalogInBackground()
|
||||||
@@ -253,7 +242,8 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
|||||||
const ingress = matchesIngress(row), egress = matchesEgress(row)
|
const ingress = matchesIngress(row), egress = matchesEgress(row)
|
||||||
return ingress === egress ? null : ingress ? "rx" : "tx"
|
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 { rows, espDirections } = collapseGreEspRows(selected, ifaceFilter ? interfaceDirection : serverDirection)
|
||||||
const previousMinute = new Date(Math.floor(now / 60_000) * 60_000 - 60_000).toISOString()
|
const previousMinute = new Date(Math.floor(now / 60_000) * 60_000 - 60_000).toISOString()
|
||||||
const ifacesForWire = new Set<string>()
|
const ifacesForWire = new Set<string>()
|
||||||
@@ -370,7 +360,7 @@ async function buildFlowAnalyticsUncached(q: FlowAnalyticsQuery, scope?: ScopedF
|
|||||||
inIface: resolved.name,
|
inIface: resolved.name,
|
||||||
outIface: outResolved.name,
|
outIface: outResolved.name,
|
||||||
}, topo.plane)
|
}, 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 en = resolveEn(topo, r.nextHop, outResolved.name)
|
||||||
const outIface = outResolved.name === "—" ? "" : outResolved.name
|
const outIface = outResolved.name === "—" ? "" : outResolved.name
|
||||||
const pathKey = JSON.stringify([client?.userId ?? "unknown", r.serverId, en?.id ?? "", dst, resolved.name, outIface,
|
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
|
const bpsNow = ring
|
||||||
? (!fromBuckets.undirectedBytes && (ring.rxNow + ring.txNow) * 1_000_000) || (totalBytes * 8) / windowSec
|
? (!fromBuckets.undirectedBytes && (ring.rxNow + ring.txNow) * 1_000_000) || (totalBytes * 8) / windowSec
|
||||||
: (recentBytes * 8) / 60 || (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()
|
await authorize()
|
||||||
const wire = ringServer ? await latestWireBps(ringServer, greNames, Boolean(scope)) : { bps: 0, bytes: 0 }
|
const wire = ringServer ? await latestWireBps(ringServer, greNames, Boolean(scope)) : { bps: 0, bytes: 0 }
|
||||||
await authorize()
|
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; }[]; }> {
|
export async function listFlowClients(minutes: number): Promise<{ clients: FlowEntityCard[] }> {
|
||||||
const inputs = await readFlowClientInputs(minutes)
|
const [inputs, topo] = await Promise.all([readFlowClientInputs(minutes), loadFlowTopology()])
|
||||||
const users = inputs.users
|
const byUser = new Map<string, PendingFlowRow[]>()
|
||||||
const binds = users.flatMap(user => user.bindings.map(binding => ({ ...binding, userId: user.id })))
|
for (const row of inputs.window.rows) {
|
||||||
const byUser = new Map<string, typeof binds>()
|
const inIface = resolveIfaceName(row.serverId, row.inIface).name
|
||||||
for (const b of binds) {
|
const outIface = resolveIfaceName(row.serverId, row.outIface).name
|
||||||
const list = byUser.get(b.userId) ?? []
|
const client = resolveFlowClient(topo, row.serverId, inIface, outIface)
|
||||||
list.push(b)
|
if (!client || classifyFlowPlane({ ...row, inIface, outIface }, topo.plane) !== "payload") continue
|
||||||
byUser.set(b.userId, list)
|
const rows = byUser.get(client.userId) ?? []
|
||||||
|
rows.push(row)
|
||||||
|
byUser.set(client.userId, rows)
|
||||||
}
|
}
|
||||||
const rows = inputs.window.rows
|
|
||||||
const clients: FlowEntityCard[] = []
|
const clients: FlowEntityCard[] = []
|
||||||
for (const u of users) {
|
for (const u of inputs.users) {
|
||||||
const userBinds = byUser.get(u.id) ?? []
|
const allow = flowClientInterfaces(topo, u.id)
|
||||||
if (userBinds.length === 0) continue
|
const namedBindings = u.bindings.filter(binding => allow.get(binding.serverId)?.has(binding.interfaceName)).length
|
||||||
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)
|
|
||||||
}
|
|
||||||
const bound = (id: number, iface: string) => {
|
const bound = (id: number, iface: string) => {
|
||||||
const names = allow.get(id)
|
return allow.get(id)?.has(resolveIfaceName(id, iface).name)
|
||||||
return names?.has(iface) || names?.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 => {
|
const rates = seriesFromRows(matched, minutes, r => {
|
||||||
if (!bound(r.serverId, r.inIface)) return "rx"
|
if (!bound(r.serverId, r.inIface)) return "rx"
|
||||||
return bound(r.serverId, r.outIface) ? "both" : "tx"
|
return bound(r.serverId, r.outIface) ? "both" : "tx"
|
||||||
@@ -694,18 +678,18 @@ export async function listFlowClients(minutes: number): Promise<{ clients: { id:
|
|||||||
id: u.id,
|
id: u.id,
|
||||||
name: u.login,
|
name: u.login,
|
||||||
subtitle: u.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",
|
country: "UN",
|
||||||
status: u.active ? "online" : "offline",
|
status: u.active ? "online" : "offline",
|
||||||
rxNow: rates.rxNow,
|
rxNow: matched.length ? rates.rxNow : null,
|
||||||
txNow: rates.txNow,
|
txNow: matched.length ? rates.txNow : null,
|
||||||
sessions: matched.length,
|
sessions: matched.length,
|
||||||
rxSeries: rates.rx,
|
rxSeries: matched.length ? rates.rx : [],
|
||||||
txSeries: rates.tx,
|
txSeries: matched.length ? rates.tx : [],
|
||||||
bytes: matched.reduce((sum, row) => sum + row.bytes, 0),
|
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 }
|
return { clients }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ const WELL_KNOWN: Record<string, string> = {
|
|||||||
"17:853": "DNS",
|
"17:853": "DNS",
|
||||||
"6:853": "DNS",
|
"6:853": "DNS",
|
||||||
"17:51820": "WireGuard",
|
"17:51820": "WireGuard",
|
||||||
|
"17:13231": "WireGuard",
|
||||||
"17:13232": "WireGuard",
|
"17:13232": "WireGuard",
|
||||||
"17:51821": "WireGuard",
|
"17:51821": "WireGuard",
|
||||||
"17:4789": "VXLAN",
|
"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 || "—"}`
|
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 {
|
export interface FlowMatchQuery {
|
||||||
serverId?: number
|
serverId?: number
|
||||||
userId?: string
|
userId?: string
|
||||||
|
|||||||
@@ -89,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, "", 17, 443, 50000)?.service, "YouTube")
|
||||||
assert.equal(resolveFlowBrand("64.233.161.1", 0, "", 6, 80, 50000)?.service, "Google")
|
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, 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(brandByAsn(32934)?.service, "Meta")
|
||||||
assert.equal(lookupBrand("157.240.12.52", 0)?.service, "Meta")
|
assert.equal(lookupBrand("157.240.12.52", 0)?.service, "Meta")
|
||||||
@@ -100,12 +105,12 @@ assert.equal(isNamedInternetService("Instagram", "Видео / стриминг"
|
|||||||
assert.equal(
|
assert.equal(
|
||||||
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 443, 51234)?.service,
|
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 443, 51234)?.service,
|
||||||
"Instagram",
|
"Instagram",
|
||||||
"HTTPS на Meta front → Instagram, как YouTube на Google",
|
"HTTPS в сети Meta",
|
||||||
)
|
)
|
||||||
assert.equal(
|
assert.equal(
|
||||||
resolveFlowBrand("57.144.22.192", 0, "", 17, 443, 50000)?.service,
|
resolveFlowBrand("57.144.22.192", 0, "", 17, 443, 50000)?.service,
|
||||||
"Instagram",
|
"Instagram",
|
||||||
"cdninstagram CIDR :443 без ASN → Instagram",
|
"QUIC в префиксе Meta без ASN",
|
||||||
)
|
)
|
||||||
assert.equal(
|
assert.equal(
|
||||||
resolveFlowBrand("157.240.12.52", 32934, "FACEBOOK", 6, 80, 50000)?.service,
|
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 const OTHER_SERVICE = "Прочее"
|
||||||
|
|
||||||
export interface BrandHit {
|
export interface BrandHit {
|
||||||
service: string
|
service: string
|
||||||
category: string
|
category: string
|
||||||
|
operator?: string
|
||||||
|
heuristic?: true
|
||||||
}
|
}
|
||||||
|
|
||||||
const CDN = { category: "CDN" } as const
|
const CDN = { category: "CDN" } as const
|
||||||
@@ -12,6 +14,7 @@ const WEB = { category: "Веб" } as const
|
|||||||
const VIDEO = { category: "Видео / стриминг" } as const
|
const VIDEO = { category: "Видео / стриминг" } as const
|
||||||
const GAMES = { category: "Игры" } as const
|
const GAMES = { category: "Игры" } as const
|
||||||
const VOICE = { category: "Голос" } as const
|
const VOICE = { category: "Голос" } as const
|
||||||
|
const MESSAGING = { category: "Мессенджеры" } as const
|
||||||
const AI = { category: "ИИ" } as const
|
const AI = { category: "ИИ" } as const
|
||||||
const DNS = { category: "DNS" } 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 BEGET: BrandHit = { service: "Beget", ...CDN }
|
||||||
const DDOS_GUARD: BrandHit = { service: "DDoS-Guard", ...CDN }
|
const DDOS_GUARD: BrandHit = { service: "DDoS-Guard", ...CDN }
|
||||||
const META: BrandHit = { service: "Meta", ...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 GOOGLE: BrandHit = { service: "Google", ...WEB }
|
||||||
const GITHUB: BrandHit = { service: "GitHub", ...WEB }
|
const GITHUB: BrandHit = { service: "GitHub", ...WEB }
|
||||||
@@ -54,7 +57,9 @@ const WIKIPEDIA: BrandHit = { service: "Wikipedia", ...WEB }
|
|||||||
const PAYPAL: BrandHit = { service: "PayPal", ...WEB }
|
const PAYPAL: BrandHit = { service: "PayPal", ...WEB }
|
||||||
const SALESFORCE: BrandHit = { service: "Salesforce", ...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 NETFLIX: BrandHit = { service: "Netflix", ...VIDEO }
|
||||||
const TWITCH: BrandHit = { service: "Twitch", ...VIDEO }
|
const TWITCH: BrandHit = { service: "Twitch", ...VIDEO }
|
||||||
const TIKTOK: BrandHit = { service: "TikTok", ...VIDEO }
|
const TIKTOK: BrandHit = { service: "TikTok", ...VIDEO }
|
||||||
@@ -69,7 +74,7 @@ const ROBLOX: BrandHit = { service: "Roblox", ...GAMES }
|
|||||||
const UBISOFT: BrandHit = { service: "Ubisoft", ...GAMES }
|
const UBISOFT: BrandHit = { service: "Ubisoft", ...GAMES }
|
||||||
|
|
||||||
const DISCORD: BrandHit = { service: "Discord", ...VOICE }
|
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 ZOOM: BrandHit = { service: "Zoom", ...VOICE }
|
||||||
|
|
||||||
const CHATGPT: BrandHit = { service: "ChatGPT", ...AI }
|
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 NON_ISO = new Set(["EU", "AP", "ZZ", "XX", "A1", "A2", "O1"])
|
||||||
|
|
||||||
const STEAM_ASN = 32590
|
const STEAM_ASN = 32590
|
||||||
const GOOGLE_FRONT_ASN = new Set([15169, 396982])
|
const GOOGLE_DNS_V6 = new Set([ipv6ToInt("2001:4860:4860::8888")!, ipv6ToInt("2001:4860:4860::8844")!])
|
||||||
/** AS32934 / AS63293 — Meta front (Facebook + Instagram CDN). AS54115 — WhatsApp, не Instagram. */
|
|
||||||
const META_FRONT_ASN = new Set([32934, 63293])
|
|
||||||
const WHATSAPP_ASN = 54115
|
|
||||||
|
|
||||||
function isGooglePublicDns(ip: string): boolean {
|
function isGooglePublicDns(ip: string): boolean {
|
||||||
return ipInCidrV4(ip, "8.8.8.0/24") || ipInCidrV4(ip, "8.8.4.0/24")
|
const host = canonicalIp(ip)
|
||||||
}
|
if (host === "8.8.8.8" || host === "8.8.4.4") return true
|
||||||
|
const ipv6 = host.includes(":") ? ipv6ToInt(host) : null
|
||||||
function isHttpsOrQuic(proto: number, dstPort: number, srcPort: number): boolean {
|
return ipv6 !== null && GOOGLE_DNS_V6.has(ipv6)
|
||||||
if (proto !== 6 && proto !== 17) return false
|
|
||||||
return dstPort === 443 || srcPort === 443
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isIsoCountry(code: string): boolean {
|
export function isIsoCountry(code: string): boolean {
|
||||||
@@ -295,19 +295,10 @@ export function lookupBrand(ip: string, asn: number): BrandHit | null {
|
|||||||
return brandByCidr(ip) || brandByAsn(asn)
|
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).
|
* Cloudflare CIDR бьёт holder (витрина на CF не становится Steam).
|
||||||
* Holder (YouTube / Instagram и др.) бьёт остальные CIDR/ASN.
|
* 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.
|
* Порты Steam — только AS32590 и не выше Cloudflare CIDR.
|
||||||
*/
|
*/
|
||||||
export function resolveFlowBrand(
|
export function resolveFlowBrand(
|
||||||
@@ -323,13 +314,12 @@ export function resolveFlowBrand(
|
|||||||
const holderBrand = brandByHolder(holder)
|
const holderBrand = brandByHolder(holder)
|
||||||
if (holderBrand) return holderBrand
|
if (holderBrand) return holderBrand
|
||||||
const asnBrand = brandByAsn(asn)
|
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
|
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 (fromLookup) return fromLookup
|
||||||
if (asn === STEAM_ASN && isSteamGamePort(proto, dstPort, srcPort)) return STEAM
|
if (asn === STEAM_ASN && isSteamGamePort(proto, dstPort, srcPort)) return STEAM
|
||||||
return null
|
return null
|
||||||
|
|||||||
@@ -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.equal(flowCounter("0"), 0); assert.equal(flowCounterSum([0, 5, 10]), 15)
|
||||||
assert.throws(() => flowCounterSum([Number.MAX_SAFE_INTEGER, 1]))
|
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 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)
|
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.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.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(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)
|
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)
|
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")
|
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 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)
|
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"
|
export { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.js"
|
||||||
import { listStoredFlowRows, type PendingFlowRow } from "./traffic-flow-ingest.js"
|
import { listStoredFlowRows, type PendingFlowRow } from "./traffic-flow-ingest.js"
|
||||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.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"
|
import { observeFlowRing } from "./traffic-flow-engine.js"
|
||||||
|
|
||||||
const fail = (message: string) => Object.assign(new Error(message), { statusCode: 502 })
|
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 {
|
export interface FlowClientInput {
|
||||||
id: string; login: string; name: string; active: boolean; bindingCount: number; selectedBindingCount: number;
|
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
|
/** Eligibility, hidden-binding exclusion, paging and selected bindings use one
|
||||||
* SQL statement/snapshot. No hidden user or binding is deserialized in Node. */
|
* 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 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) 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",
|
(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 (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
|
FROM page p
|
||||||
) SELECT (SELECT count(*) FROM eligible) AS total,COALESCE(jsonb_agg(to_jsonb(projected)),'[]'::jsonb) AS users FROM projected
|
) 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")
|
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)
|
const bindingCount = flowCounter(user.bindingCount), selectedBindingCount = flowCounter(user.selectedBindingCount)
|
||||||
if (options && user.bindings.length > 1000 || user.bindings.length !== selectedBindingCount) throw fail("Превышен предел привязок клиента NetFlow")
|
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 { 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) }
|
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) {
|
export function observeFlowClient(user: FlowClientInput, rows: PendingFlowRow[], minutes: number) {
|
||||||
const interfaces = new Map<number, Set<string>>()
|
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 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 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 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",
|
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,
|
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.peerSpecific) && ifIndexRowsNotAttributed === 0,
|
completeSourceSet: user.bindingCount === user.selectedBindingCount, completeAttribution: user.bindingCount === user.selectedBindingCount && user.bindings.every(binding => binding.attributable) && ifIndexRowsNotAttributed === 0,
|
||||||
ifIndexRowsNotAttributed, historicalOwnershipVerified: false, attribution: "current-named-whole-interface-bindings",
|
ifIndexRowsNotAttributed, historicalOwnershipVerified: false, attribution: "current exclusive interface bindings, including confirmed single-peer WireGuard",
|
||||||
ingressNamedRowsBytes: bytes, ingressNamedRowCount: attributable ? matched.length : null,
|
ingressNamedRowsBytes: bytes, ingressNamedRowCount: attributable ? matched.length : null,
|
||||||
ingressNamedRowsMeanMbps: bytes === null ? null : bytes * 8 / (minutes * 60) / 1000000,
|
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,
|
serverContextFlowRing: user.bindings.length ? { serverId: user.bindings[0].serverId, scope: "server-payload; not per-client", ...observeFlowRing(user.bindings[0].serverId) } : null,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import assert from "node:assert/strict"
|
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"
|
import { classifyFlowDst, disableCatalogFetchForTests, resetFlowCatalogForTests, seedFlowCatalogForTests } from "./traffic-flow-classify.js"
|
||||||
|
|
||||||
disableCatalogFetchForTests()
|
disableCatalogFetchForTests()
|
||||||
@@ -7,12 +7,17 @@ resetFlowCatalogForTests()
|
|||||||
seedFlowCatalogForTests({
|
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.0/25", purpose: "Игры" },
|
||||||
{ cidr: "198.51.100.128/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)
|
const hit = classifyFlowDst("192.0.2.10", 6, 443, 50000, null)
|
||||||
assert.equal(hit.category, "Игры")
|
assert.equal(hit.category, "Игры")
|
||||||
assert.equal(hit.service, "steam-gaming")
|
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.10", 6, 443, 50000, null).category, "Игры")
|
||||||
assert.equal(classifyFlowDst("198.51.100.150", 6, 443, 50000, null).category, "Видео / стриминг")
|
assert.equal(classifyFlowDst("198.51.100.150", 6, 443, 50000, null).category, "Видео / стриминг")
|
||||||
|
|
||||||
@@ -37,11 +42,11 @@ const google = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
|||||||
ok: true,
|
ok: true,
|
||||||
fetchedAt: Date.now(),
|
fetchedAt: Date.now(),
|
||||||
})
|
})
|
||||||
assert.equal(google.service, "YouTube")
|
assert.deepEqual(google, { service: "YouTube", category: "Видео / стриминг", basis: "heuristic" })
|
||||||
assert.equal(google.category, "Видео / стриминг")
|
assert.equal(classifyFlowDst("173.194.1.1", 17, 443, 50000, null).service, "Work")
|
||||||
|
|
||||||
const googleCidr = classifyFlowDst("173.194.151.65", 6, 80, 50000, null)
|
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, "Веб")
|
assert.equal(googleCidr.category, "Веб")
|
||||||
|
|
||||||
const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
||||||
@@ -56,6 +61,8 @@ const youtube = classifyFlowDst("173.194.160.163", 6, 443, 1, {
|
|||||||
})
|
})
|
||||||
assert.equal(youtube.service, "YouTube")
|
assert.equal(youtube.service, "YouTube")
|
||||||
assert.equal(youtube.category, "Видео / стриминг")
|
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, {
|
const valve = classifyFlowDst("203.0.113.40", 17, 27015, 50000, {
|
||||||
prefix: "203.0.113.0/24",
|
prefix: "203.0.113.0/24",
|
||||||
@@ -119,8 +126,8 @@ const googleCloud = classifyFlowDst("203.0.113.43", 6, 443, 1, {
|
|||||||
ok: true,
|
ok: true,
|
||||||
fetchedAt: Date.now(),
|
fetchedAt: Date.now(),
|
||||||
})
|
})
|
||||||
assert.equal(googleCloud.service, "YouTube")
|
assert.equal(googleCloud.service, "Google")
|
||||||
assert.equal(googleCloud.category, "Видео / стриминг")
|
assert.equal(googleCloud.category, "Веб")
|
||||||
|
|
||||||
const gre = classifyFlowDst("198.51.100.1", 47, 0, 0, null)
|
const gre = classifyFlowDst("198.51.100.1", 47, 0, 0, null)
|
||||||
assert.equal(gre.service, "GRE")
|
assert.equal(gre.service, "GRE")
|
||||||
@@ -146,8 +153,10 @@ const dnsGoogle = classifyFlowDst("8.8.8.8", 17, 53, 53000, {
|
|||||||
ok: true,
|
ok: true,
|
||||||
fetchedAt: Date.now(),
|
fetchedAt: Date.now(),
|
||||||
})
|
})
|
||||||
assert.equal(dnsGoogle.service, "Google")
|
assert.equal(dnsGoogle.service, "DNS")
|
||||||
assert.notEqual(dnsGoogle.service, "Прочее")
|
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, {
|
const ipv6Yt = classifyFlowDst("2001:4860:4860::8888", 17, 443, 50000, {
|
||||||
prefix: "2001:4860:4860::8888/128",
|
prefix: "2001:4860:4860::8888/128",
|
||||||
asn: 15169,
|
asn: 15169,
|
||||||
@@ -158,7 +167,7 @@ const ipv6Yt = classifyFlowDst("2001:4860:4860::8888", 17, 443, 50000, {
|
|||||||
ok: true,
|
ok: true,
|
||||||
fetchedAt: Date.now(),
|
fetchedAt: Date.now(),
|
||||||
})
|
})
|
||||||
assert.equal(ipv6Yt.service, "YouTube")
|
assert.equal(ipv6Yt.service, "Google")
|
||||||
|
|
||||||
const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
|
const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
|
||||||
prefix: "157.240.0.0/16",
|
prefix: "157.240.0.0/16",
|
||||||
@@ -170,9 +179,7 @@ const instagram = classifyFlowDst("157.240.12.52", 6, 443, 62598, {
|
|||||||
ok: true,
|
ok: true,
|
||||||
fetchedAt: Date.now(),
|
fetchedAt: Date.now(),
|
||||||
})
|
})
|
||||||
assert.equal(instagram.service, "Instagram")
|
assert.deepEqual(instagram, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
|
||||||
assert.equal(instagram.category, "Видео / стриминг")
|
|
||||||
assert.notEqual(instagram.service, "Meta")
|
|
||||||
|
|
||||||
const metaHttp = classifyFlowDst("157.240.12.52", 6, 80, 50000, {
|
const metaHttp = classifyFlowDst("157.240.12.52", 6, 80, 50000, {
|
||||||
prefix: "157.240.0.0/16",
|
prefix: "157.240.0.0/16",
|
||||||
@@ -198,14 +205,17 @@ const igHolder = classifyFlowDst("203.0.113.80", 6, 443, 1, {
|
|||||||
fetchedAt: Date.now(),
|
fetchedAt: Date.now(),
|
||||||
})
|
})
|
||||||
assert.equal(igHolder.service, "Instagram")
|
assert.equal(igHolder.service, "Instagram")
|
||||||
|
assert.equal(igHolder.basis, "network")
|
||||||
|
|
||||||
const igCidr = classifyFlowDst("57.144.22.192", 17, 443, 50000, null)
|
const igCidr = classifyFlowDst("57.144.22.192", 17, 443, 50000, null)
|
||||||
assert.equal(igCidr.service, "Instagram")
|
assert.deepEqual(igCidr, { service: "Instagram", category: "Видео / стриминг", basis: "heuristic" })
|
||||||
assert.equal(igCidr.category, "Видео / стриминг")
|
|
||||||
|
|
||||||
const esp = classifyFlowDst("198.51.100.1", 50, 0, 0, null)
|
const esp = classifyFlowDst("198.51.100.1", 50, 0, 0, null)
|
||||||
assert.equal(esp.category, "Туннель")
|
assert.equal(esp.category, "Туннель")
|
||||||
assert.equal(applicationName(17, 443, 50000), "QUIC")
|
assert.equal(applicationName(17, 443, 50000), "QUIC")
|
||||||
assert.equal(applicationName(17, 853, 50000), "DNS")
|
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")
|
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 { ipInCidrV4, parseCidrV4 } from "./traffic-flow-ip.js"
|
||||||
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
|
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
|
||||||
import { applicationName } from "./traffic-flow-apps.js"
|
import { applicationName } from "./traffic-flow-apps.js"
|
||||||
|
import type { FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
|
||||||
|
|
||||||
export interface FlowClassification {
|
export interface FlowClassification {
|
||||||
service: string
|
service: string
|
||||||
category: string
|
category: string
|
||||||
|
basis: FlowServiceBasis
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CatalogCidr {
|
interface CatalogCidr {
|
||||||
@@ -54,6 +56,7 @@ export function categoryFromPurpose(purpose: string, proto: number, dstPort: num
|
|||||||
if (/игры|gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры"
|
if (/игры|gaming|steam|epic|riot|playstation|roblox|ubisoft/.test(p)) return "Игры"
|
||||||
if (/видео|стриминг|streaming|youtube|netflix|twitch|video|spotify|instagram/.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 (/cdn|cloudflare|akamai|fastly|hetzner|ovh|apple/.test(p)) return "CDN"
|
||||||
|
if (/мессенджер|telegram/.test(p)) return "Мессенджеры"
|
||||||
if (/голос|voip|discord|zoom/.test(p)) return "Голос"
|
if (/голос|voip|discord|zoom/.test(p)) return "Голос"
|
||||||
if (p === "ии" || /openai|chatgpt|\bai\b/.test(p)) return "ИИ"
|
if (p === "ии" || /openai|chatgpt|\bai\b/.test(p)) return "ИИ"
|
||||||
if (/quad9|opendns/.test(p)) return "DNS"
|
if (/quad9|opendns/.test(p)) return "DNS"
|
||||||
@@ -71,6 +74,11 @@ function matchCidr(ip: string,rows=cidrs): CatalogCidr | null {
|
|||||||
return 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(
|
export function classifyFlowDst(
|
||||||
dst: string,
|
dst: string,
|
||||||
proto: number,
|
proto: number,
|
||||||
@@ -80,20 +88,23 @@ export function classifyFlowDst(
|
|||||||
opts?: { ignoreTunnelProto?: boolean;catalog?:{cidrs:CatalogCidr[];asnPurpose:Map<number,string>} },
|
opts?: { ignoreTunnelProto?: boolean;catalog?:{cidrs:CatalogCidr[];asnPurpose:Map<number,string>} },
|
||||||
): FlowClassification {
|
): FlowClassification {
|
||||||
if (!opts?.ignoreTunnelProto) {
|
if (!opts?.ignoreTunnelProto) {
|
||||||
if (proto === 47) return { service: "GRE", category: "Туннель" }
|
if (proto === 47) return { service: "GRE", category: "Туннель", basis: "port" }
|
||||||
if (proto === 50) return { service: "ESP", category: "Туннель" }
|
if (proto === 50) return { service: "ESP", category: "Туннель", basis: "port" }
|
||||||
}
|
}
|
||||||
const app = applicationName(proto, dstPort, srcPort)
|
const app = applicationName(proto, dstPort, srcPort)
|
||||||
if (app === "WireGuard") return { service: "WireGuard", category: "Туннель" }
|
if ((proto === 6 || proto === 17) && (dstPort === 53 || dstPort === 853)) return { service: "DNS", category: "DNS", basis: "port" }
|
||||||
const hit = matchCidr(dst,opts?.catalog?.cidrs)
|
if (app === "WireGuard") return { service: "WireGuard", category: "Туннель", basis: "port" }
|
||||||
|
const prefixPurpose = servicePurpose(matchCidr(dst,opts?.catalog?.cidrs)?.purpose)
|
||||||
const holder = ripe?.holder ?? ""
|
const holder = ripe?.holder ?? ""
|
||||||
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, holder, proto, dstPort, srcPort)
|
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, holder, proto, dstPort, srcPort)
|
||||||
const asnName = ripe?.asn ? (opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn) : undefined
|
if (prefixPurpose && prefixPurpose.toLowerCase() !== brand?.operator?.toLowerCase()) {
|
||||||
const service = (hit?.purpose || brand?.service || asnName || OTHER_SERVICE).trim() || OTHER_SERVICE
|
return { service: prefixPurpose, category: categoryFromPurpose(prefixPurpose, proto, dstPort, srcPort), basis: "catalog" }
|
||||||
const category = hit
|
}
|
||||||
? categoryFromPurpose(hit.purpose, proto, dstPort, srcPort)
|
if (brand) return { service: brand.service, category: brand.category, basis: brand.heuristic ? "heuristic" : "network" }
|
||||||
: (brand?.category || categoryFromPurpose(asnName || "", proto, dstPort, srcPort))
|
const asnName = ripe?.asn ? servicePurpose((opts?.catalog?.asnPurpose??asnPurpose).get(ripe.asn)) : undefined
|
||||||
return { service, category }
|
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. */
|
/** Copies already-observed data only; never fetches the EvoBGP catalog. */
|
||||||
|
|||||||
@@ -142,7 +142,7 @@ assert.equal(classifyInternetBrand("8.8.8.8", 6, 443, 51234, {
|
|||||||
fetchedAt: Date.now(),
|
fetchedAt: Date.now(),
|
||||||
})?.service, "Google")
|
})?.service, "Google")
|
||||||
assert.equal(mapInternetBrand("203.0.113.50", 6, 443, 51234, null).service, "Прочее")
|
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" })
|
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", 47, 0, 0, null).service, "Прочее")
|
||||||
assert.equal(mapInternetBrand("8.8.8.8", 6, 443, 51234, {
|
assert.equal(mapInternetBrand("8.8.8.8", 6, 443, 51234, {
|
||||||
prefix: "8.8.8.0/24",
|
prefix: "8.8.8.0/24",
|
||||||
@@ -174,7 +174,7 @@ assert.equal(mapInternetBrand("8.8.8.8", 17, 53, 53000, {
|
|||||||
holder: "GOOGLE",
|
holder: "GOOGLE",
|
||||||
ok: true,
|
ok: true,
|
||||||
fetchedAt: Date.now(),
|
fetchedAt: Date.now(),
|
||||||
}).service, "Google")
|
}).service, "DNS")
|
||||||
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
|
assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
|
||||||
prefix: "2001:4860:4860::8888/128",
|
prefix: "2001:4860:4860::8888/128",
|
||||||
asn: 15169,
|
asn: 15169,
|
||||||
@@ -184,7 +184,7 @@ assert.equal(mapInternetBrand("2001:4860:4860::8888", 17, 443, 50000, {
|
|||||||
holder: "GOOGLE",
|
holder: "GOOGLE",
|
||||||
ok: true,
|
ok: true,
|
||||||
fetchedAt: Date.now(),
|
fetchedAt: Date.now(),
|
||||||
}).service, "YouTube")
|
}).service, "Google")
|
||||||
assert.equal(mapInternetBrand("64.233.161.1", 17, 443, 50000, null).service, "YouTube")
|
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")
|
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 {
|
function isTunnelProto(proto: number, dstPort: number, srcPort: number): boolean {
|
||||||
if (proto === 47 || proto === 50) return true
|
if (proto === 47 || proto === 50) return true
|
||||||
@@ -85,7 +85,7 @@ export function classifyInternetBrand(
|
|||||||
dstPort: number,
|
dstPort: number,
|
||||||
srcPort: number,
|
srcPort: number,
|
||||||
ripe: FlowIpMeta | null,
|
ripe: FlowIpMeta | null,
|
||||||
): FlowClassification | null {
|
): Pick<FlowClassification, "service" | "category"> | null {
|
||||||
if (isTunnelProto(proto, dstPort, srcPort)) return null
|
if (isTunnelProto(proto, dstPort, srcPort)) return null
|
||||||
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, ripe?.holder ?? "", proto, dstPort, srcPort)
|
const brand = resolveFlowBrand(dst, ripe?.asn ?? 0, ripe?.holder ?? "", proto, dstPort, srcPort)
|
||||||
if (brand && isNamedInternetService(brand.service, brand.category)) return brand
|
if (brand && isNamedInternetService(brand.service, brand.category)) return brand
|
||||||
@@ -105,7 +105,7 @@ export function mapInternetBrand(
|
|||||||
if (isTunnelProto(proto, dstPort, srcPort)) return OTHER_BRAND
|
if (isTunnelProto(proto, dstPort, srcPort)) return OTHER_BRAND
|
||||||
const classified = classifyFlowDst(dst, proto, dstPort, srcPort, ripe, { ignoreTunnelProto: true })
|
const classified = classifyFlowDst(dst, proto, dstPort, srcPort, ripe, { ignoreTunnelProto: true })
|
||||||
if (isNamedInternetService(classified.service, classified.category)) return classified
|
if (isNamedInternetService(classified.service, classified.category)) return classified
|
||||||
return { service: classified.category, category: classified.category }
|
return { ...classified, service: classified.category }
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveInternetDest(opts: {
|
export function resolveInternetDest(opts: {
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ setGeoipReadersForTests({
|
|||||||
})
|
})
|
||||||
const v6meta = resolveFlowIp("2001:4860:4860::8888")
|
const v6meta = resolveFlowIp("2001:4860:4860::8888")
|
||||||
assert.equal(v6meta?.asn, 15169)
|
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, "Прочее")
|
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"))
|
const cidrYt = mapInternetBrand("64.233.161.1", 17, 443, 50000, resolveFlowIp("64.233.161.1"))
|
||||||
assert.equal(cidrYt.service, "YouTube")
|
assert.equal(cidrYt.service, "YouTube")
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { mock } from "node:test"
|
|||||||
import { dbQuery } from "../db/index.js"
|
import { dbQuery } from "../db/index.js"
|
||||||
import { configureEngine, flushEngineNow } from "./traffic-flow-engine.js"
|
import { configureEngine, flushEngineNow } from "./traffic-flow-engine.js"
|
||||||
import { parseFlowPacket } from "./traffic-flow-parse.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 { rememberServerIfaces, resetIfaceCacheForTests } from "./traffic-flow-ifindex.js"
|
||||||
import {
|
import {
|
||||||
ingestParsedFlowsForServerForTests,
|
ingestParsedFlowsForServerForTests,
|
||||||
@@ -18,7 +20,7 @@ import {
|
|||||||
resetFlowMapHopsCacheForTests,
|
resetFlowMapHopsCacheForTests,
|
||||||
} from "./traffic-flow-map-hops.js"
|
} from "./traffic-flow-map-hops.js"
|
||||||
import { withPgOrSkip } from "../test/pg.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 { disableCatalogFetchForTests, resetFlowCatalogForTests } from "./traffic-flow-classify.js"
|
||||||
import {
|
import {
|
||||||
disableRipeEnqueueForTests,
|
disableRipeEnqueueForTests,
|
||||||
@@ -460,13 +462,13 @@ try {
|
|||||||
assert.equal(leak.totalBytes, 30_000)
|
assert.equal(leak.totalBytes, 30_000)
|
||||||
assert.equal(leak.namedBytes, 10_000)
|
assert.equal(leak.namedBytes, 10_000)
|
||||||
assert.equal(leak.unclassifiedBytes, 20_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")
|
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.ok(other, "dest без бренда → Прочее")
|
||||||
assert.equal(yt.bytes, 10_000)
|
assert.equal(youtube.bytes, 10_000)
|
||||||
assert.equal(other.bytes, 20_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.ok(Math.abs(other.share - 20 / 30) < 0.01)
|
||||||
assert.equal((leak.serviceEdges ?? []).reduce((n, e) => n + e.bytes, 0), hop.bytes)
|
assert.equal((leak.serviceEdges ?? []).reduce((n, e) => n + e.bytes, 0), hop.bytes)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -656,7 +658,7 @@ ingestClosed(7, [
|
|||||||
try {
|
try {
|
||||||
resetFlowMapHopsCacheForTests()
|
resetFlowMapHopsCacheForTests()
|
||||||
const rev = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
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.services?.some((s) => s.id === "svc:cloudflare"), "реверс Cloudflare:443 → 10.x")
|
||||||
assert.ok(rev.serviceEdges?.some((e) => e.toId === "svc:youtube" && e.fromId === "9"))
|
assert.ok(rev.serviceEdges?.some((e) => e.toId === "svc:youtube" && e.fromId === "9"))
|
||||||
} finally {
|
} finally {
|
||||||
@@ -698,7 +700,7 @@ try {
|
|||||||
const googleEdge = wan.serviceEdges?.find((e) => e.toId === "svc:google")
|
const googleEdge = wan.serviceEdges?.find((e) => e.toId === "svc:google")
|
||||||
assert.ok(googleEdge, "Google с WAN JH")
|
assert.ok(googleEdge, "Google с WAN JH")
|
||||||
assert.equal(googleEdge.fromId, "9", "якорь на EN, не на 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")
|
const viaGre = wan.serviceEdges?.find((e) => e.toId === "svc:google")
|
||||||
assert.ok(viaGre?.clients?.some((c) => c.name === "Alice") || viaGre?.clientName === "Alice")
|
assert.ok(viaGre?.clients?.some((c) => c.name === "Alice") || viaGre?.clientName === "Alice")
|
||||||
} finally {
|
} finally {
|
||||||
@@ -730,15 +732,26 @@ ingestClosed(7, [
|
|||||||
outIface: "1",
|
outIface: "1",
|
||||||
nextHop: "",
|
nextHop: "",
|
||||||
},
|
},
|
||||||
|
{ ...payloadFlow("1.2.3.4", 6000), proto: 17, dstPort: 53, inIface: "gre-client", outIface: "ether1", nextHop: "" },
|
||||||
])
|
])
|
||||||
try {
|
try {
|
||||||
resetFlowMapHopsCacheForTests()
|
resetFlowMapHopsCacheForTests()
|
||||||
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
|
||||||
assert.equal(wanOnly.services?.find(s => s.id === "svc:youtube")?.bytes, 9000)
|
const youtube = wanOnly.services?.find(s => s.id === "svc:youtube")
|
||||||
assert.deepEqual(wanOnly.serviceEdges, [])
|
assert.equal(youtube?.bytes, 9000)
|
||||||
assert.deepEqual(wanOnly.servicePaths, [])
|
assert.deepEqual(youtube.serviceEvidence, [{basis: "heuristic", bytes: 9000}])
|
||||||
assert.deepEqual(wanOnly.countryEdges, [])
|
assert.deepEqual(youtube.trafficTypes, [{transport: "TCP", application: "HTTPS", bytes: 9000}])
|
||||||
assert.ok(wanOnly.countryServiceGroups?.every(group => !group.edges.length && !group.paths.length))
|
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 {
|
} finally {
|
||||||
seedFlowTopologyForTests(null)
|
seedFlowTopologyForTests(null)
|
||||||
@@ -788,6 +801,8 @@ try {
|
|||||||
assert.ok(googleEdge)
|
assert.ok(googleEdge)
|
||||||
assert.equal(googleEdge.bytes, 120_000)
|
assert.equal(googleEdge.bytes, 120_000)
|
||||||
assert.equal(dual.totalBytes, 120_000, "объём крупнейшей копии с атрибуцией маршрута JH")
|
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)
|
assert.equal(googleEdge.bps, googlePaths[0]?.bps)
|
||||||
} finally {
|
} finally {
|
||||||
seedFlowTopologyForTests(null)
|
seedFlowTopologyForTests(null)
|
||||||
@@ -1037,13 +1052,24 @@ try {
|
|||||||
try {
|
try {
|
||||||
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
|
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")?.bytes, 12000)
|
||||||
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes]), [["10", 2000], ["9", 1000]])
|
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.lastBucketAt, new Date(bucket).toISOString())
|
||||||
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 3000)
|
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 })
|
const recent = await buildFlowMapHops({ serverId: 7, minutes: 1, includeCurrentMinute: true, minSharePct: 0 })
|
||||||
assert.equal(recent.windowSec, 90)
|
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.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)
|
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 { clock.mock.restore() }
|
||||||
} finally {
|
} finally {
|
||||||
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
|
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
|
||||||
@@ -1104,12 +1130,58 @@ try {
|
|||||||
ingestClosed(sid, [split], bucket - 60000)
|
ingestClosed(sid, [split], bucket - 60000)
|
||||||
const mixed = await buildFlowMapHops({serverId: sid, minutes: 5, iface: "mixed-lan"})
|
const mixed = await buildFlowMapHops({serverId: sid, minutes: 5, iface: "mixed-lan"})
|
||||||
assert.equal(mixed.totalBytes, 6000)
|
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 })
|
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,
|
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}])
|
[{out_iface: "", next_hop: null}, {out_iface: "", next_hop: null}])
|
||||||
const user = await buildFlowMapHops({serverId: sid, minutes: 5, userId: "no-interface-binding"})
|
const user = await buildFlowMapHops({serverId: sid, minutes: 5, userId: "no-interface-binding"})
|
||||||
assert.equal(user.interfaceTraffic, undefined)
|
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")
|
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 {
|
} finally {
|
||||||
await dbQuery("DELETE FROM servers WHERE id=?", [sid])
|
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 { isDeepStrictEqual } from "node:util"
|
||||||
import { readFlowMapSourceLimits } from "./traffic-flow-source-limits.js"
|
import { readFlowMapSourceLimits } from "./traffic-flow-source-limits.js"
|
||||||
import { flowCounter, flowCounterSum } from "./traffic-flow-observed-values.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 { ScopedFlowAnalyticsRead } from "./traffic-flow-analytics.js"
|
||||||
import type { FlowMapCountryServiceGroup, FlowMapHop, FlowMapHopsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
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 { OTHER_SERVICE, isNamedInternetService, mapCountryNodeId, mapCountryServiceNodeId, mapServiceNodeId, resolveRipeCountry } from "./traffic-flow-brands.js"
|
||||||
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
|
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
|
||||||
import { refreshFlowCatalogInBackground } from "./traffic-flow-classify.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 { getFlowListenerState, listStoredFlowRows } from "./traffic-flow-ingest.js"
|
||||||
import { resolveIfaceName } from "./traffic-flow-ifaces.js"
|
import { resolveIfaceName } from "./traffic-flow-ifaces.js"
|
||||||
import { classifyFlowPlane, shouldKeepPlane } from "./traffic-flow-planes.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 { resolveFlowEndpoints } from "./traffic-flow-ip.js"
|
||||||
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
|
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
|
||||||
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
|
||||||
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
|
import { loadFlowTopology, resolveFlowClient, flowClientInterfaces, getServerCatalog, type FlowClientBinding } from "./traffic-flow-topology.js"
|
||||||
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.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 DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
|
||||||
export const MAP_SERVICE_NODE_CAP = 20
|
export const MAP_SERVICE_NODE_CAP = 20
|
||||||
@@ -64,6 +65,7 @@ interface ClientAcc {
|
|||||||
interface FromAcc {
|
interface FromAcc {
|
||||||
exporterId: string
|
exporterId: string
|
||||||
enId: string
|
enId: string
|
||||||
|
viaIface?: string
|
||||||
reverseBytes: number
|
reverseBytes: number
|
||||||
bytes: number
|
bytes: number
|
||||||
clients: Map<string, ClientAcc>
|
clients: Map<string, ClientAcc>
|
||||||
@@ -72,9 +74,11 @@ interface FromAcc {
|
|||||||
interface DstAcc {
|
interface DstAcc {
|
||||||
dst: string
|
dst: string
|
||||||
bytes: number
|
bytes: number
|
||||||
|
lastBucketAt: string
|
||||||
proto: number
|
proto: number
|
||||||
dstPort: number
|
dstPort: number
|
||||||
srcPort: number
|
srcPort: number
|
||||||
|
application: string | null
|
||||||
fromBytes: Map<string, FromAcc>
|
fromBytes: Map<string, FromAcc>
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,6 +86,9 @@ interface DestTotal {
|
|||||||
label: string
|
label: string
|
||||||
category: string
|
category: string
|
||||||
bytes: number
|
bytes: number
|
||||||
|
lastBucketAt: string
|
||||||
|
trafficTypes?: Map<string, NonNullable<FlowMapService["trafficTypes"]>[number]>
|
||||||
|
serviceEvidence?: Map<FlowServiceBasis, number>
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DestEdgeAcc {
|
interface DestEdgeAcc {
|
||||||
@@ -91,6 +98,7 @@ interface DestEdgeAcc {
|
|||||||
bytesFwd: number
|
bytesFwd: number
|
||||||
bytesRev: number
|
bytesRev: number
|
||||||
clients: Map<string, string>
|
clients: Map<string, string>
|
||||||
|
observedOnly?: true
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DestPathAcc {
|
interface DestPathAcc {
|
||||||
@@ -98,6 +106,7 @@ interface DestPathAcc {
|
|||||||
clientName: string
|
clientName: string
|
||||||
viaId: string
|
viaId: string
|
||||||
viaName: string
|
viaName: string
|
||||||
|
viaIface?: string
|
||||||
enId: string
|
enId: string
|
||||||
enName: string
|
enName: string
|
||||||
serviceId: string
|
serviceId: string
|
||||||
@@ -115,12 +124,12 @@ function bumpClient(clients: Map<string, ClientAcc>, bytes: number, client: { us
|
|||||||
clients.set(id, { name, bytes })
|
clients.set(id, { name, bytes })
|
||||||
}
|
}
|
||||||
|
|
||||||
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, bytes: number, reverse: boolean, client: { userId: string; name: string } | null): void {
|
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, viaIface: string | undefined, bytes: number, reverse: boolean, client: FlowClientBinding | null | undefined): void {
|
||||||
const key = exporterId + "|" + enId
|
const key = JSON.stringify([exporterId, enId, viaIface])
|
||||||
const from = acc.fromBytes.get(key) ?? { exporterId, enId, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
|
const from = acc.fromBytes.get(key) ?? { exporterId, enId, viaIface, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
|
||||||
from.bytes += bytes
|
from.bytes += bytes
|
||||||
if (reverse) from.reverseBytes += bytes
|
if (reverse) from.reverseBytes += bytes
|
||||||
bumpClient(from.clients, bytes, client)
|
bumpClient(from.clients, bytes, client ?? null)
|
||||||
acc.fromBytes.set(key, from)
|
acc.fromBytes.set(key, from)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,13 +161,22 @@ export function pickMapServices(
|
|||||||
.slice(0, cap)
|
.slice(0, cap)
|
||||||
}
|
}
|
||||||
|
|
||||||
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number): void {
|
function bumpDestTotal(totals: Map<string, DestTotal>, id: string, label: string, category: string, bytes: number, lastBucketAt: string,
|
||||||
const prev = totals.get(id)
|
detail?: { transport: string; application: string | null; basis: FlowServiceBasis }): void {
|
||||||
if (prev) {
|
const total = totals.get(id) ?? { label, category, bytes: 0, lastBucketAt }
|
||||||
prev.bytes += bytes
|
total.bytes += bytes
|
||||||
return
|
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(
|
function bumpDestFrom(
|
||||||
@@ -171,7 +189,7 @@ function bumpDestFrom(
|
|||||||
enName: string,
|
enName: string,
|
||||||
viaName: string,
|
viaName: string,
|
||||||
/** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */
|
/** fromId ребра, если отличается от EN (вложенный слой: страна → сервис). */
|
||||||
edgeFromId: string = fromId,
|
edgeFromId: string = fromId || exporterId,
|
||||||
): void {
|
): void {
|
||||||
const edgeKey = `${edgeFromId}|${toId}`
|
const edgeKey = `${edgeFromId}|${toId}`
|
||||||
const prevEdge = edges.get(edgeKey)
|
const prevEdge = edges.get(edgeKey)
|
||||||
@@ -192,10 +210,11 @@ function bumpDestFrom(
|
|||||||
bytesFwd: from.bytes - from.reverseBytes,
|
bytesFwd: from.bytes - from.reverseBytes,
|
||||||
bytesRev: from.reverseBytes,
|
bytesRev: from.reverseBytes,
|
||||||
clients: namedClients,
|
clients: namedClients,
|
||||||
|
...(!fromId && edgeFromId === exporterId ? { observedOnly: true as const } : {}),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
for (const [clientId, c] of from.clients) {
|
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)
|
const prevPath = paths.get(pathKey)
|
||||||
if (prevPath) {
|
if (prevPath) {
|
||||||
prevPath.bytes += c.bytes
|
prevPath.bytes += c.bytes
|
||||||
@@ -206,6 +225,7 @@ function bumpDestFrom(
|
|||||||
clientName: c.name,
|
clientName: c.name,
|
||||||
viaId: exporterId,
|
viaId: exporterId,
|
||||||
viaName,
|
viaName,
|
||||||
|
...(from.viaIface ? { viaIface: from.viaIface } : {}),
|
||||||
enId: fromId,
|
enId: fromId,
|
||||||
enName,
|
enName,
|
||||||
serviceId: toId,
|
serviceId: toId,
|
||||||
@@ -232,8 +252,11 @@ function finalizeDestLayer(
|
|||||||
label: s.label,
|
label: s.label,
|
||||||
category: s.category,
|
category: s.category,
|
||||||
bytes: s.bytes,
|
bytes: s.bytes,
|
||||||
|
...(s.lastBucketAt ? { lastBucketAt: minuteBucketIso(Date.parse(s.lastBucketAt)) } : {}),
|
||||||
bps: (s.bytes * 8) / windowSec,
|
bps: (s.bytes * 8) / windowSec,
|
||||||
share: shareBase > 0 ? s.bytes / shareBase : 0,
|
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),
|
.sort((a, b) => b.bytes - a.bytes),
|
||||||
minSharePct,
|
minSharePct,
|
||||||
@@ -253,6 +276,7 @@ function finalizeDestLayer(
|
|||||||
bps: (e.bytes * 8) / windowSec,
|
bps: (e.bytes * 8) / windowSec,
|
||||||
bpsFwd: (e.bytesFwd * 8) / windowSec,
|
bpsFwd: (e.bytesFwd * 8) / windowSec,
|
||||||
bpsRev: (e.bytesRev * 8) / windowSec,
|
bpsRev: (e.bytesRev * 8) / windowSec,
|
||||||
|
...(e.observedOnly ? { observedOnly: e.observedOnly } : {}),
|
||||||
...(first ? { clientId: first.id, clientName: first.name } : {}),
|
...(first ? { clientId: first.id, clientName: first.name } : {}),
|
||||||
...(clients.length ? { clients } : {}),
|
...(clients.length ? { clients } : {}),
|
||||||
}
|
}
|
||||||
@@ -265,6 +289,7 @@ function finalizeDestLayer(
|
|||||||
clientName: p.clientName,
|
clientName: p.clientName,
|
||||||
viaId: p.viaId,
|
viaId: p.viaId,
|
||||||
viaName: p.viaName,
|
viaName: p.viaName,
|
||||||
|
...(p.viaIface ? { viaIface: p.viaIface } : {}),
|
||||||
enId: p.enId,
|
enId: p.enId,
|
||||||
enName: p.enName,
|
enName: p.enName,
|
||||||
serviceId: p.serviceId,
|
serviceId: p.serviceId,
|
||||||
@@ -341,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 {
|
function ifaceUsable(name: string): boolean {
|
||||||
return Boolean(name) && name !== "—"
|
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 {
|
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 prev = acc.get(key)
|
||||||
const addFwd = dir === "fwd" || dir === "both" ? bytes : 0
|
const addFwd = dir === "fwd" || dir === "both" ? bytes : 0
|
||||||
@@ -499,21 +502,17 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
|||||||
const excludeOverlay = q.excludeOverlay !== false
|
const excludeOverlay = q.excludeOverlay !== false
|
||||||
await authorize()
|
await authorize()
|
||||||
const topo = await loadFlowTopology(scope?.serverIds, authorize)
|
const topo = await loadFlowTopology(scope?.serverIds, authorize)
|
||||||
let allow: Map<number, Set<string>> | null = null
|
const allow = q.userId ? flowClientInterfaces(topo, q.userId) : null
|
||||||
if (q.userId) {
|
if (scope && allow && !allow.size) throw new Error("Пользователь не найден в разрешённой топологии")
|
||||||
if (!scope) allow = await userIfaceAllow(q.userId)
|
|
||||||
else {
|
function rowClient(r: (typeof raw)[number]) {
|
||||||
allow = new Map()
|
return resolveFlowClient(topo, r.serverId, resolveIfaceName(r.serverId, r.inIface).name, resolveIfaceName(r.serverId, r.outIface).name)
|
||||||
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 matches = (serverId: number, iface: string) =>
|
const matches = (serverId: number, iface: string) =>
|
||||||
flowRowMatchesFilter({ serverId, inIface: iface }, resolveIfaceName(serverId, iface).name, q, allow)
|
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 => {
|
const { rows } = collapseGreEspRows(selected, r => {
|
||||||
if (ifaceFilter) {
|
if (ifaceFilter) {
|
||||||
const ingress = matches(r.serverId, r.inIface), egress = matches(r.serverId, r.outIface)
|
const ingress = matches(r.serverId, r.inIface), egress = matches(r.serverId, r.outIface)
|
||||||
@@ -551,16 +550,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
|||||||
}
|
}
|
||||||
await authorize()
|
await authorize()
|
||||||
const peers = await readMapGrePeers(working)
|
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))
|
const enIds = new Set(topo.enNodes.map((n) => n.id))
|
||||||
let totalBytes = 0
|
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) {
|
for (const r of working) {
|
||||||
const inRes = resolveIfaceName(r.serverId, r.inIface)
|
const inRes = resolveIfaceName(r.serverId, r.inIface)
|
||||||
const outRes = resolveIfaceName(r.serverId, r.outIface)
|
const outRes = resolveIfaceName(r.serverId, r.outIface)
|
||||||
@@ -626,7 +623,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
|||||||
const reverse = !!endpoints.internetPeer && (endpoints.internetPeer === endpoints.packetSrc || endpoints.internetPeer === r.natSrc)
|
const reverse = !!endpoints.internetPeer && (endpoints.internetPeer === endpoints.packetSrc || endpoints.internetPeer === r.natSrc)
|
||||||
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : peerId
|
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : peerId
|
||||||
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
|
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) {
|
if (peerId && peerId !== r.serverId) {
|
||||||
const toId = String(peerId)
|
const toId = String(peerId)
|
||||||
const dir = outId === peerId ? "fwd" : "rev"
|
const dir = outId === peerId ? "fwd" : "rev"
|
||||||
@@ -668,33 +672,46 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
|||||||
const payloadBytes = new Map<(typeof working)[number], number>()
|
const payloadBytes = new Map<(typeof working)[number], number>()
|
||||||
const payloadRows = wantDedup
|
const payloadRows = wantDedup
|
||||||
? dedupFlowRowsAcrossExporters(working, (a, b) => {
|
? dedupFlowRowsAcrossExporters(working, (a, b) => {
|
||||||
const aRouted = observed.get(a)?.exitId !== undefined
|
const observationA = observed.get(a)!
|
||||||
const bRouted = observed.get(b)?.exitId !== undefined
|
const observationB = observed.get(b)!
|
||||||
const aCli = Boolean(rowClient(a))
|
const aRouted = observationA.exitId !== undefined
|
||||||
const bCli = Boolean(rowClient(b))
|
const bRouted = observationB.exitId !== undefined
|
||||||
|
const aCli = Boolean(observationA.client)
|
||||||
|
const bCli = Boolean(observationB.client)
|
||||||
const attributed = aRouted !== bRouted ? (aRouted ? a : b)
|
const attributed = aRouted !== bRouted ? (aRouted ? a : b)
|
||||||
: aCli !== bCli ? (aCli ? a : b)
|
: aCli !== bCli ? (aCli ? a : b)
|
||||||
: a.bytes >= b.bytes ? a : b
|
: a.bytes >= b.bytes ? a : b
|
||||||
// Route/client evidence and the largest byte observation can come from different exporters.
|
// 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))
|
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
|
return attributed
|
||||||
})
|
})
|
||||||
: working
|
: working
|
||||||
|
|
||||||
for (const r of payloadRows) {
|
for (const r of payloadRows) {
|
||||||
const inName = resolveIfaceName(r.serverId, r.inIface).name
|
|
||||||
const outName = resolveIfaceName(r.serverId, r.outIface).name
|
|
||||||
const bytes = payloadBytes.get(r) ?? r.bytes
|
const bytes = payloadBytes.get(r) ?? r.bytes
|
||||||
totalBytes += bytes
|
totalBytes += bytes
|
||||||
const { endpoints: ep, exitId, reverse } = observed.get(r)!
|
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 dst = ep.internetPeer
|
||||||
const dstPort = ep.peerPort || r.dstPort
|
const dstPort = ep.peerPort || r.dstPort
|
||||||
const srcPort = ep.otherPort || r.srcPort
|
const srcPort = ep.otherPort || r.srcPort
|
||||||
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
|
const application = flowPortApplication(r.proto, dstPort) ?? flowPortApplication(r.proto, srcPort)
|
||||||
const client = resolveMapClient(topo, r.serverId, inName, outName)
|
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : JSON.stringify([r.proto, application])
|
||||||
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, fromBytes: new Map<string, FromAcc>() }
|
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, lastBucketAt: "", proto: r.proto, dstPort, srcPort, application, fromBytes: new Map<string, FromAcc>() }
|
||||||
acc.bytes += bytes
|
acc.bytes += bytes
|
||||||
if (exitId !== undefined) bumpFrom(acc, String(r.serverId), String(exitId), bytes, reverse, client)
|
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)
|
dstAcc.set(destKey, acc)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -724,13 +741,14 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
|||||||
const ripe = dst ? resolveFlowIp(dst) : null
|
const ripe = dst ? resolveFlowIp(dst) : null
|
||||||
const classified = dst
|
const classified = dst
|
||||||
? mapInternetBrand(dst, acc.proto, acc.dstPort, acc.srcPort, ripe)
|
? mapInternetBrand(dst, acc.proto, acc.dstPort, acc.srcPort, ripe)
|
||||||
: { service: OTHER_SERVICE, category: OTHER_SERVICE }
|
: OTHER_BRAND
|
||||||
const svcId = mapServiceNodeId(classified.service)
|
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)
|
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)
|
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()) {
|
for (const from of acc.fromBytes.values()) {
|
||||||
const { exporterId, enId: fromId } = from
|
const { exporterId, enId: fromId } = from
|
||||||
const enName = nodeName(fromId)
|
const enName = nodeName(fromId)
|
||||||
@@ -767,6 +785,9 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
|
|||||||
await authorize()
|
await authorize()
|
||||||
return {
|
return {
|
||||||
...(interfaceTraffic ? { interfaceTraffic } : {}),
|
...(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()]
|
hops: [...hops.values()]
|
||||||
.map((a) => toHop(a, windowSec))
|
.map((a) => toHop(a, windowSec))
|
||||||
.sort((a, b) => a.bytes === b.bytes ? 0 : b.bytes - a.bytes),
|
.sort((a, b) => a.bytes === b.bytes ? 0 : b.bytes - a.bytes),
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ export const PLANE_LABEL: Record<FlowPlane, string> = {
|
|||||||
mgmt: "mgmt",
|
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])
|
const FLOW_PORTS = new Set([4739, 2055])
|
||||||
|
|
||||||
export function isRfc1918(ip: string): boolean {
|
export function isRfc1918(ip: string): boolean {
|
||||||
|
|||||||
@@ -42,6 +42,27 @@ export interface ServerCatalogEntry {
|
|||||||
|
|
||||||
const CATALOG_TTL_MS = 5_000
|
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 seeded: FlowTopology | null = null
|
||||||
let topologyCache: { at: number; topo: FlowTopology } | null = null
|
let topologyCache: { at: number; topo: FlowTopology } | null = null
|
||||||
let serverCatalogCache: { at: number; list: ServerCatalogEntry[]; byId: Map<number, ServerCatalogEntry> } | 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
|
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])
|
`, [serverIds, serverIds])
|
||||||
await authorize()
|
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 }>(`
|
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" FROM user_interface_bindings b
|
SELECT b.user_id AS "userId",b.server_id AS "serverId",b.interface_name AS "interfaceName",
|
||||||
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
|
(${flowBindingAttributionSql}) AS attributable
|
||||||
LIMIT 1001
|
FROM user_interface_bindings b
|
||||||
`, [serverIds, serverIds])
|
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")
|
if (serverIds !== undefined && (binds.length > 1000 || users.length > 1000)) throw new Error("Превышен предел топологии NetFlow")
|
||||||
const loginById = new Map(users.map((u) => [u.id, u]))
|
const loginById = new Map(users.map((u) => [u.id, u]))
|
||||||
const clientIfaces = new Map<number, Set<string>>()
|
const clientIfaces = new Map<number, Set<string>>()
|
||||||
@@ -139,6 +166,7 @@ export async function loadFlowTopology(serverIds?: readonly number[], authorize:
|
|||||||
set.add(b.interfaceName)
|
set.add(b.interfaceName)
|
||||||
clientIfaces.set(b.serverId, set)
|
clientIfaces.set(b.serverId, set)
|
||||||
allClientNames.add(b.interfaceName)
|
allClientNames.add(b.interfaceName)
|
||||||
|
if (!b.attributable) continue
|
||||||
const user = loginById.get(b.userId)
|
const user = loginById.get(b.userId)
|
||||||
clientByIface.set(ifaceKey(b.serverId, b.interfaceName), {
|
clientByIface.set(ifaceKey(b.serverId, b.interfaceName), {
|
||||||
userId: b.userId,
|
userId: b.userId,
|
||||||
@@ -213,6 +241,24 @@ export function resolveClient(
|
|||||||
return topo.clientByIface.get(ifaceKey(serverId, inIfaceName)) ?? null
|
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(
|
export function resolveEn(
|
||||||
topo: FlowTopology,
|
topo: FlowTopology,
|
||||||
nextHop: string,
|
nextHop: string,
|
||||||
|
|||||||
@@ -1,24 +1,22 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useEffect, useRef } from "react"
|
import { InfoIcon, LockIcon, UsersIcon } from "lucide-react"
|
||||||
import { InfoIcon } 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 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
|
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: статус, роли узлов, виды связей и что значат подписи. */
|
/** Легенда карты макета v3: статус, роли узлов, виды связей и что значат подписи. */
|
||||||
export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
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"
|
const head = "text-muted-foreground mt-1 text-[11px] font-semibold tracking-wider uppercase"
|
||||||
return (
|
return (
|
||||||
<details ref={details} data-map-legend className="relative">
|
<Popover key={compact ? "compact" : "overview"}>
|
||||||
<summary className="border-border bg-background hover:bg-muted/60 text-foreground flex h-8 cursor-pointer list-none items-center gap-1.5 rounded-lg border px-2.5 text-[13px] font-medium transition-colors focus-visible:outline-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden [[open]>&]:bg-muted">
|
<PopoverTrigger render={<Button type="button" variant="outline" className="text-[13px]" />}>
|
||||||
<InfoIcon aria-hidden="true" className="size-4" />Легенда
|
<InfoIcon aria-hidden="true" className="size-4" />Легенда
|
||||||
</summary>
|
</PopoverTrigger>
|
||||||
<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-[310px] max-w-[calc(100vw-2rem)] flex-col gap-2 overflow-y-auto rounded-lg border p-3 text-xs shadow-lg">
|
<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>
|
<p className={head}>Статус</p>
|
||||||
<div className="grid grid-cols-2 gap-x-2.5 gap-y-1.5">
|
<div className="grid grid-cols-2 gap-x-2.5 gap-y-1.5">
|
||||||
{STATUS.map(([color, label]) => (
|
{STATUS.map(([color, label]) => (
|
||||||
@@ -34,18 +32,20 @@ export function NetworkMapLegend({ compact = false }: { compact?: boolean }) {
|
|||||||
))}
|
))}
|
||||||
<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="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"><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>
|
||||||
<p className={head}>Связи</p>
|
<p className={head}>Связи</p>
|
||||||
<div className="flex flex-col gap-1.5">
|
<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"><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"><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" strokeDasharray="8 5" /></svg>GRE + IPsec</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" strokeDasharray="4 5" /></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(--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)" 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)" strokeWidth="2" strokeDasharray="2 6" strokeLinecap="round" /></svg>Пунктир WAN→JH — модель связности; маршрут не подтверждён.</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)" strokeOpacity="0.55" strokeWidth="6" /></svg>Лента NetFlow · толщина = скорость</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>
|
</div>
|
||||||
<p className="text-muted-foreground leading-snug">Live — последний замер RX/TX интерфейса RouterOS. «≈» и ленты NetFlow показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
|
<p className="text-muted-foreground leading-snug">Подпись линии GRE показывает последний замер RX/TX интерфейса RouterOS. Скорость сервиса и знак «≈» показывают среднюю скорость по принятым записям IPFIX. RTT — задержка пробы, «—» означает, что нет измерения.</p>
|
||||||
</div>
|
</PopoverContent>
|
||||||
</details>
|
</Popover>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -3,18 +3,29 @@
|
|||||||
import { useEffect, useState, type ReactNode } from "react"
|
import { useEffect, useState, type ReactNode } from "react"
|
||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
import { ChevronRightIcon, XIcon } from "lucide-react"
|
import { ChevronRightIcon, XIcon } from "lucide-react"
|
||||||
import type { FlowAnalyticsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath } from "@mmapp/contracts/traffic-flow"
|
import type { FlowAnalyticsDto, FlowMapService, FlowMapServiceEdge, FlowMapServicePath, FlowMapUser, FlowServiceBasis } from "@mmapp/contracts/traffic-flow"
|
||||||
import { flowMapHopsDtoSchema } from "@mmapp/contracts/traffic-flow"
|
import { flowMapHopsDtoSchema } from "@mmapp/contracts/traffic-flow"
|
||||||
import { Badge } from "@/components/reui/badge"
|
import { Badge } from "@/components/reui/badge"
|
||||||
import { Sparkline } from "@/components/sparkline"
|
import { Sparkline } from "@/components/sparkline"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button, buttonVariants } from "@/components/ui/button"
|
||||||
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
import { ServiceBrandIcon } from "@/components/network-map/service-brand-icon"
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
import { formatBytes, fmtRate } from "@/lib/fmt-rate"
|
import { formatBytes, fmtRate } from "@/lib/fmt-rate"
|
||||||
import { formatNetflowRate } from "@/lib/map-netflow-hops"
|
import { formatNetflowRate } from "@/lib/map-netflow-hops"
|
||||||
|
import { servicePathKey } from "@/lib/format-service-path-label"
|
||||||
import { projectTrafficObservations } from "@/lib/traffic-observations"
|
import { projectTrafficObservations } from "@/lib/traffic-observations"
|
||||||
import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow"
|
import { getFlowAnalytics, getFlowMapHops } from "@/shared/api/traffic-flow"
|
||||||
import { requestJson } from "@/shared/api/http-client"
|
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?][] }) {
|
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">
|
return <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-t-lg border-b bg-border">
|
||||||
@@ -25,6 +36,46 @@ export function InspectorMetrics({ rows }: { rows: [string, ReactNode, string?][
|
|||||||
</dl>
|
</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 }) {
|
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 [sample, setSample] = useState<ReturnType<typeof projectTrafficObservations> | null>(null)
|
||||||
const [unavailable, setUnavailable] = useState(false)
|
const [unavailable, setUnavailable] = useState(false)
|
||||||
@@ -61,23 +112,28 @@ export function NodeHistory({ base, id, refresh, degraded }: { base: string | nu
|
|||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ServiceInspector({ service, paths, exits, exitName, country, base, refresh, windowLabel, flowAt, stale, activePath, onPath, onClose, filtered, onFilter }: {
|
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
|
service: FlowMapService; paths: FlowMapServicePath[]; exits: FlowMapServiceEdge[]; exitName: (id: string) => string
|
||||||
country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean
|
country?: string; base: string | null; refresh: number; windowLabel: string; flowAt: string | null; stale: boolean
|
||||||
activePath: { viaId: string; enId: string; serviceId: string } | null; onPath: (path: FlowMapServicePath) => void
|
activePath: FlowMapServicePath | null; onPath: (path: FlowMapServicePath) => void
|
||||||
onClose: () => void; filtered: boolean; onFilter: () => 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 [recent, setRecent] = useState<{ data: FlowAnalyticsDto; at: string } | null>(null)
|
||||||
const [volume, setVolume] = useState<{ bytes: number | null; window: string; 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 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(() => {
|
useEffect(() => {
|
||||||
if (base === null) return
|
if (base === null) return
|
||||||
const controller = new AbortController()
|
const controller = new AbortController()
|
||||||
const init = { signal: controller.signal }
|
const init = { signal: controller.signal }
|
||||||
if (canMatchService) void getFlowAnalytics(base, { range: "5m" }, init)
|
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()}) })
|
.then(data => { if (!controller.signal.aborted) setRecent({data, at: new Date().toISOString()}) })
|
||||||
.catch(() => { if (!controller.signal.aborted) setRecent(null) })
|
.catch(() => { if (!controller.signal.aborted) setRecent(null) })
|
||||||
void getFlowMapHops(base, { range: "24h" }, init)
|
if (!scoped) void getFlowMapHops(base, { range: "24h" }, init)
|
||||||
.then(raw => {
|
.then(raw => {
|
||||||
if (controller.signal.aborted) return
|
if (controller.signal.aborted) return
|
||||||
const data = flowMapHopsDtoSchema.parse(raw)
|
const data = flowMapHopsDtoSchema.parse(raw)
|
||||||
@@ -89,22 +145,32 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
|||||||
})
|
})
|
||||||
.catch(() => { if (!controller.signal.aborted) setVolume(null) })
|
.catch(() => { if (!controller.signal.aborted) setVolume(null) })
|
||||||
return () => controller.abort()
|
return () => controller.abort()
|
||||||
}, [base, refresh, country, service.id, canMatchService])
|
}, [base, refresh, country, service.id, canMatchService, scoped, scopedUser, exporter, userId])
|
||||||
const flows = recent?.data.conversationsList.filter(row => {
|
const countryFilter = service.id.startsWith("cc:other|") ? "unknown" : country
|
||||||
const categoryFallback = row.category === service.label && (row.service === "Прочее" || ["DNS", "SSH", "BGP"].includes(row.category))
|
const flows = recent?.data.conversationsList.filter(row => (!topology || topology.has(row.enId || row.serverId)) && matchesMapService(row, service.label, countryFilter))
|
||||||
if (row.service !== service.label && !categoryFallback) return false
|
|
||||||
if (!country) return true
|
|
||||||
if (service.id.startsWith("cc:other|")) return !row.dstCountry || row.dstCountry.toLowerCase() === "unknown"
|
|
||||||
return row.dstCountry?.toUpperCase() === country.toUpperCase()
|
|
||||||
})
|
|
||||||
.sort((a, b) => b.bps - a.bps).slice(0, 5) ?? []
|
.sort((a, b) => b.bps - a.bps).slice(0, 5) ?? []
|
||||||
const asns = [...new Set(flows.flatMap(flow => flow.dstAsn ? [flow.dstAsn] : []))]
|
const asns = [...new Set(flows.flatMap(flow => flow.dstAsn ? [flow.dstAsn] : []))]
|
||||||
const rates = [...exits].sort((a, b) => b.bps - a.bps)
|
const rates = [...exits].sort((a, b) => b.bps - a.bps)
|
||||||
const exitIds = [...new Set([...rates.map(e => e.fromId), ...paths.map(p => p.enId)])]
|
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 attributedBytes = (country ? paths : exits).reduce((sum, entry) => sum + entry.bytes, 0)
|
||||||
const remainder = Math.max(0, service.bytes - attributedBytes)
|
const remainder = Math.max(0, service.bytes - attributedBytes)
|
||||||
const observed = service.bytes > 0 && !stale
|
const observed = service.bytes > 0 && !stale
|
||||||
const currentVolume = base === null
|
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 <>
|
return <>
|
||||||
<header className="flex items-center gap-2 px-3 py-3">
|
<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="grid size-8 shrink-0 place-items-center rounded-md bg-muted"><ServiceBrandIcon label={service.label} size={18} /></div>
|
||||||
@@ -115,30 +181,71 @@ export function ServiceInspector({ service, paths, exits, exitName, country, bas
|
|||||||
</header>
|
</header>
|
||||||
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
|
<div className="mx-0.5 mb-0.5 min-h-0 overflow-y-auto rounded-lg border">
|
||||||
<InspectorMetrics rows={[
|
<InspectorMetrics rows={[
|
||||||
["Скорость", formatNetflowRate({ bps: service.bps }), "Средняя скорость NetFlow за " + windowLabel],
|
["Средняя скорость IPFIX", formatNetflowRate({ bps: service.bps }), "Сохранённые потоки за " + windowLabel],
|
||||||
[country ? "Доля страны" : "Доля трафика", new Intl.NumberFormat("ru-RU", {style:"percent", maximumFractionDigits:1}).format(service.share)],
|
[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>}</>],
|
["Объём · " + (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>}</>],
|
||||||
["Exit-узел", exitIds.map(exitName).join(", ") || "—", remainder ? "Часть трафика без подтверждённого выхода" : undefined],
|
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>
|
<section className="space-y-2 border-b px-3.5 py-3"><h3 className="text-[11px] text-muted-foreground">Путь трафика</h3>
|
||||||
{paths.map(p => {
|
{paths.map(p => {
|
||||||
const parts = [p.clientName !== "—" ? p.clientName : "", p.viaId !== p.enId ? p.viaName : "", p.enName, service.label].filter(Boolean)
|
const parts = [p.clientName !== "—" ? p.clientName : "", p.viaId !== p.enId ? p.viaName : "",
|
||||||
const active = activePath?.viaId === p.viaId && activePath.enId === p.enId && activePath.serviceId === p.serviceId
|
p.enName, service.label].filter(Boolean)
|
||||||
return <button type="button" key={JSON.stringify([p.clientId,p.viaId,p.enId])} onClick={() => onPath(p)} aria-pressed={active} title={formatNetflowRate({bps:p.bps})} className={cn("flex w-full flex-wrap items-center gap-1 rounded-sm text-left", active && "ring-1 ring-primary")}>
|
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>)}
|
{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>
|
</button>
|
||||||
})}
|
})}
|
||||||
{rates.filter(e => !paths.some(p => p.enId === e.fromId)).map(e => <div key={e.fromId} className="flex justify-between gap-2 text-xs"><span>{exitName(e.fromId)} → {service.label}</span><span className="shrink-0 font-mono">{formatNetflowRate({bps:e.bps})}</span></div>)}
|
{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>}
|
{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>}
|
{!paths.length && !rates.length && !remainder && <p className="text-xs text-muted-foreground">Маршрут не определён</p>}
|
||||||
</section>
|
</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>
|
<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) => <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}`}><span>{f.protoName}{f.dstPort ? "/" + f.dstPort : ""}</span> · {f.serverName || f.serverId}</p></div><span className="font-mono text-[11px] text-muted-foreground">{formatNetflowRate({bps:f.bps})}</span></div>)}
|
{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>}
|
{!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>}
|
{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>
|
</section>
|
||||||
<div className="flex flex-wrap gap-1.5 px-3.5 py-3">
|
<div className="flex flex-wrap gap-1.5 px-3.5 py-3">
|
||||||
<Button size="xs" nativeButton={false} render={<Link href="/traffic" />}>Открыть в «Трафике»</Button>
|
<Link href={`/traffic?${trafficQuery}`} className={buttonVariants({size:"xs"})}>Открыть в «Трафике»</Link>
|
||||||
<Button size="xs" variant="outline" aria-pressed={filtered} onClick={onFilter}>{filtered ? "Снять фильтр" : "Фильтр по сервису"}</Button>
|
<Button size="xs" variant="outline" aria-pressed={filtered} onClick={onFilter}>{filtered ? "Снять фильтр" : "Фильтр по сервису"}</Button>
|
||||||
</div>
|
</div>
|
||||||
</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"
|
"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 { FramePanel } from "@/components/reui/frame"
|
||||||
import { Badge } from "@/components/reui/badge"
|
import { Badge } from "@/components/reui/badge"
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||||
import { SectionFrame, ToneBadge, 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 { 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 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 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 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"
|
export type MapBottomTab = "flows" | "rtt" | "dest" | "events"
|
||||||
|
|
||||||
function Table({ head, cols, empty, children }: { head: string[]; cols: string; empty: string | null; children: ReactNode }) {
|
function Table({ head, cols, empty, children }: { head: string[]; cols: string; empty: string | null; children: ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<div className="max-h-[420px] overflow-auto">
|
<div className="max-h-[min(34svh,310px)] overflow-auto">
|
||||||
<div className="min-w-[720px]">
|
<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)}>
|
<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>)}
|
{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 каналов, назначения и события.
|
* Рабочая панель под картой (макет 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
|
tab: MapBottomTab
|
||||||
onTab: (tab: MapBottomTab) => void
|
onTab: (tab: MapBottomTab) => void
|
||||||
|
open: boolean
|
||||||
|
onOpenChange: (open: boolean) => void
|
||||||
flows: MapFlowRow[]
|
flows: MapFlowRow[]
|
||||||
rtt: MapRttRow[]
|
rtt: MapRttRow[]
|
||||||
destinations: MapDestRow[]
|
destinations: MapDestRow[]
|
||||||
events: MapEventRow[]
|
events: MapEventRow[]
|
||||||
|
onEvent: (event: MapEventRow) => void
|
||||||
|
onFlow: (id: string) => void
|
||||||
|
onDestination: (id: string) => void
|
||||||
eventsError: string | null
|
eventsError: string | null
|
||||||
stat: string
|
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 }> = [
|
const tabs: Array<{ id: MapBottomTab; label: string; count: number }> = [
|
||||||
{ id: "flows", label: "Потоки NetFlow", count: flows.length },
|
{ id: "flows", label: "Потоки NetFlow", count: flows.length },
|
||||||
{ id: "rtt", label: "RTT каналов", count: rtt.length },
|
{ id: "rtt", label: "RTT каналов", count: rtt.length },
|
||||||
{ id: "dest", label: "Назначения", count: destinations.length },
|
{ id: "dest", label: "Назначения", count: destinations.length },
|
||||||
{ id: "events", label: "События", count: events.length },
|
{ id: "events", label: "События", count: visibleEvents.length },
|
||||||
]
|
]
|
||||||
return (
|
return (
|
||||||
<SectionFrame aria-label="Рабочая панель карты" bare>
|
<SectionFrame aria-label="Рабочая панель карты" bare className="min-w-0 shrink-0">
|
||||||
<Tabs value={tab} onValueChange={(value) => onTab(value as MapBottomTab)} className="gap-1">
|
<Tabs value={tab} onValueChange={(value) => { onTab(value as MapBottomTab); onOpenChange(true) }} className="gap-1">
|
||||||
<div className="flex flex-wrap items-center gap-3 px-2 pt-1.5 pb-1">
|
<div className="flex min-w-0 items-center gap-2 px-2 py-1">
|
||||||
<TabsList aria-label="Рабочая панель">
|
<div className="min-w-0 flex-1 overflow-x-auto"><TabsList aria-label="Рабочая панель">
|
||||||
{tabs.map((t) => (
|
{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}
|
{t.label}
|
||||||
<Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge>
|
<Badge variant="secondary" size="sm" className="font-mono">{t.count}</Badge>
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
))}
|
))}
|
||||||
</TabsList>
|
</TabsList></div>
|
||||||
<span className="text-muted-foreground ml-auto text-xs">{stat}</span>
|
{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>
|
</div>
|
||||||
<FramePanel className="p-0">
|
<FramePanel id="network-map-analysis" hidden={!open} className="p-0">
|
||||||
<TabsContent value="flows">
|
<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) => (
|
{flows.map((r) => (
|
||||||
<Row key={r.id} cols={FLOW_COLS} hl={r.hl}>
|
<Row key={r.id} cols={FLOW_COLS} hl={r.hl}>
|
||||||
<span className="truncate font-mono">{r.client}</span>
|
<span className="truncate font-mono">{r.client}</span>
|
||||||
<span className="truncate font-mono">{r.exit}</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="font-mono tabular-nums">{r.rate}</span>
|
||||||
<span className="text-muted-foreground font-mono tabular-nums">{r.volume}</span>
|
<span className="text-muted-foreground font-mono tabular-nums">{r.volume}</span>
|
||||||
</Row>
|
</Row>
|
||||||
@@ -100,7 +111,7 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, e
|
|||||||
<Table head={["Назначение", "Категория", "Скорость", "Доля окна"]} cols={DEST_COLS} empty={destinations.length ? null : "Назначений за окно нет"}>
|
<Table head={["Назначение", "Категория", "Скорость", "Доля окна"]} cols={DEST_COLS} empty={destinations.length ? null : "Назначений за окно нет"}>
|
||||||
{destinations.map((r) => (
|
{destinations.map((r) => (
|
||||||
<Row key={r.id} cols={DEST_COLS} hl={r.hl}>
|
<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="text-muted-foreground truncate">{r.category}</span>
|
||||||
<span className="font-mono tabular-nums">{r.rate}</span>
|
<span className="font-mono tabular-nums">{r.rate}</span>
|
||||||
<span className="flex items-center gap-2">
|
<span className="flex items-center gap-2">
|
||||||
@@ -112,12 +123,17 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, e
|
|||||||
</Table>
|
</Table>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
<TabsContent value="events">
|
<TabsContent value="events">
|
||||||
<Table head={["Время", "Тип", "Событие", "Подробности"]} cols={EVENT_COLS} empty={eventsError ? `События недоступны: ${eventsError}` : events.length ? null : "Событий пока нет"}>
|
<div className="flex items-center gap-2 border-b px-3 py-1">
|
||||||
{events.map((r) => (
|
<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}>
|
<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>
|
<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><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>
|
<span className="text-muted-foreground truncate text-xs">{r.message}</span>
|
||||||
</Row>
|
</Row>
|
||||||
))}
|
))}
|
||||||
@@ -133,35 +149,45 @@ export function MapBottomPanel({ tab, onTab, flows, rtt, destinations, events, e
|
|||||||
* «Момент времени» (макет v3): инциденты за 24 часа на шкале и текущий Live-снимок.
|
* «Момент времени» (макет 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 from = now - 24 * 3_600_000
|
||||||
const marks = events.filter((e) => e.ts >= from && e.ts <= now)
|
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)})`
|
const at = (t: number) => `calc(10px + (100% - 20px) * ${t.toFixed(4)})`
|
||||||
// Шкала макета v3: остановки (кружок и подпись под ним), инциденты — цветные засечки над линией.
|
// Шкала макета v3: остановки (кружок и подпись под ним), инциденты — цветные засечки над линией.
|
||||||
const stop = "absolute top-[7px] flex -translate-x-1/2 flex-col items-center gap-1 text-[11px] leading-none whitespace-nowrap"
|
const stop = "absolute top-[7px] flex -translate-x-1/2 flex-col items-center gap-1 text-[11px] leading-none whitespace-nowrap"
|
||||||
return (
|
return (
|
||||||
<div className="flex shrink-0 items-center gap-3 border-t px-3 pt-1.5 pb-1">
|
<div className="flex shrink-0 items-center gap-3 border-t px-3 pt-1.5 pb-1">
|
||||||
<small className="text-muted-foreground text-xs whitespace-nowrap">Момент времени</small>
|
<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">
|
<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" />
|
<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]) => (
|
{[["−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)) }}>
|
<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}
|
<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>
|
</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
|
<button
|
||||||
key={e.id}
|
key={e.id}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => onPick(e)}
|
onClick={() => onPick(e)}
|
||||||
aria-label={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
|
aria-label={label}
|
||||||
title={`${new Date(e.ts).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" })} · ${e.title}`}
|
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"
|
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((e.ts - from) / (now - from)) }}
|
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] }} />
|
<span aria-hidden="true" className="block h-full w-1.5 rounded-sm" style={{ background: TONE_COLOR[e.tone] }} />
|
||||||
</button>
|
</button>
|
||||||
))}
|
)})}
|
||||||
<span className={cn(stop, "text-foreground font-semibold")} style={{ left: at(1) }}>
|
<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
|
<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>
|
</span>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client"
|
"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 { Frame, FramePanel } from "@/components/reui/frame"
|
||||||
import { ChartContainer, ChartTooltip, type ChartConfig } from "@/components/ui/chart"
|
import { ChartContainer, ChartTooltip, type ChartConfig } from "@/components/ui/chart"
|
||||||
import { fmtRate, formatRangeAgo, TRAFFIC_RANGE_MINUTES } from "@/lib/fmt-rate"
|
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) => {
|
return Array.from({ length: n }, (_, i) => {
|
||||||
const minutesAgo = Math.round((1 - i / denom) * rangeMinutes)
|
const minutesAgo = Math.round((1 - i / denom) * rangeMinutes)
|
||||||
return {
|
return {
|
||||||
|
index: i,
|
||||||
time: formatRangeAgo(minutesAgo),
|
time: formatRangeAgo(minutesAgo),
|
||||||
rx: typeof rx[i] === "number" && Number.isFinite(rx[i]) && rx[i] >= 0 ? rx[i] : null,
|
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,
|
tx: typeof tx[i] === "number" && Number.isFinite(tx[i]) && tx[i] >= 0 ? tx[i] : null,
|
||||||
@@ -72,6 +74,7 @@ export function TrafficRxTxChart({
|
|||||||
range = "1h",
|
range = "1h",
|
||||||
rangeMinutes: actualMinutes,
|
rangeMinutes: actualMinutes,
|
||||||
embedded = false,
|
embedded = false,
|
||||||
|
scrub = false,
|
||||||
}: {
|
}: {
|
||||||
rx: (number|null)[]
|
rx: (number|null)[]
|
||||||
tx: (number|null)[]
|
tx: (number|null)[]
|
||||||
@@ -79,9 +82,13 @@ export function TrafficRxTxChart({
|
|||||||
rangeMinutes?: number
|
rangeMinutes?: number
|
||||||
/** Skip outer Frame when already inside OpsPanel / Frame. */
|
/** Skip outer Frame when already inside OpsPanel / Frame. */
|
||||||
embedded?: boolean
|
embedded?: boolean
|
||||||
|
scrub?: boolean
|
||||||
}) {
|
}) {
|
||||||
const rangeMinutes = actualMinutes ?? TRAFFIC_RANGE_MINUTES[range] ?? 60
|
const rangeMinutes = actualMinutes ?? TRAFFIC_RANGE_MINUTES[range] ?? 60
|
||||||
const data = toChartData(rx, tx, rangeMinutes)
|
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 tickEvery = Math.max(1, Math.ceil(data.length / 6))
|
||||||
|
|
||||||
const hasRx = data.some(point => point.rx !== null)
|
const hasRx = data.some(point => point.rx !== null)
|
||||||
@@ -105,7 +112,8 @@ export function TrafficRxTxChart({
|
|||||||
stroke="var(--border)"
|
stroke="var(--border)"
|
||||||
/>
|
/>
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="time"
|
dataKey="index"
|
||||||
|
tickFormatter={(value: number) => data[value]?.time ?? ""}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
tick={{ fontSize: 11 }}
|
tick={{ fontSize: 11 }}
|
||||||
@@ -121,6 +129,7 @@ export function TrafficRxTxChart({
|
|||||||
width={72}
|
width={72}
|
||||||
/>
|
/>
|
||||||
<ChartTooltip content={<CustomTooltip />} />
|
<ChartTooltip content={<CustomTooltip />} />
|
||||||
|
{scrub && selected !== undefined && <ReferenceLine x={index} stroke="var(--muted-foreground)" />}
|
||||||
{hasRx && <Line
|
{hasRx && <Line
|
||||||
dataKey="rx"
|
dataKey="rx"
|
||||||
type="monotone"
|
type="monotone"
|
||||||
@@ -141,6 +150,15 @@ export function TrafficRxTxChart({
|
|||||||
<ChartLegendItem label="RX (входящий)" color="var(--chart-rx)" />
|
<ChartLegendItem label="RX (входящий)" color="var(--chart-rx)" />
|
||||||
<ChartLegendItem label="TX (исходящий)" color="var(--chart-tx)" />
|
<ChartLegendItem label="TX (исходящий)" color="var(--chart-tx)" />
|
||||||
</div>
|
</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>
|
</div>
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import {
|
|||||||
DATA_GRID_CELL_PAD_LAST,
|
DATA_GRID_CELL_PAD_LAST,
|
||||||
} from "@/components/data-grids/shared/data-grid-layout"
|
} from "@/components/data-grids/shared/data-grid-layout"
|
||||||
import { TrafficFlowsDataGrid } from "@/components/data-grids/traffic-flows-data-grid"
|
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 { FlowTrafficMap } from "@/components/traffic/flow-traffic-map"
|
||||||
import { StatusDot } from "@/components/status-dot"
|
import { StatusDot } from "@/components/status-dot"
|
||||||
import { Flag } from "@/components/flag"
|
import { Flag } from "@/components/flag"
|
||||||
@@ -79,7 +80,9 @@ export function FlowEntityCardView({
|
|||||||
{card.site}
|
{card.site}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</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 justify-between mt-2 gap-2">
|
||||||
<div className="flex items-center gap-1 text-xs">
|
<div className="flex items-center gap-1 text-xs">
|
||||||
<ArrowDownIcon className="size-3 text-success" />
|
<ArrowDownIcon className="size-3 text-success" />
|
||||||
@@ -103,13 +106,14 @@ type BreakdownFilter = {
|
|||||||
label: string
|
label: string
|
||||||
serverId?: 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 {
|
function talkerMatchesFilter(row: FlowTalkerDto, filter: SessionFilter): boolean {
|
||||||
switch (filter.kind) {
|
switch (filter.kind) {
|
||||||
case "application": return row.application === filter.value
|
case "application": return row.application === filter.value
|
||||||
case "category": return row.category === filter.value
|
case "category": return row.category === filter.value
|
||||||
case "service": return row.service === 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 "asn": return String(row.dstAsn ?? "unknown") === filter.value
|
||||||
case "country": return (!filter.serverId || row.serverId === filter.serverId) && (row.dstCountry || "unknown") === filter.value
|
case "country": return (!filter.serverId || row.serverId === filter.serverId) && (row.dstCountry || "unknown") === filter.value
|
||||||
case "protocol": return row.protoName === filter.value
|
case "protocol": return row.protoName === filter.value
|
||||||
@@ -329,6 +333,9 @@ export function FlowAnalyticsDetail({
|
|||||||
onExcludeOverlay,
|
onExcludeOverlay,
|
||||||
liveHint,
|
liveHint,
|
||||||
emptyHint,
|
emptyHint,
|
||||||
|
initialService,
|
||||||
|
initialCountry,
|
||||||
|
mapNodes,
|
||||||
}: {
|
}: {
|
||||||
card: (Pick<FlowEntityCard, "id" | "name" | "country" | "site"> & Partial<FlowEntityCard>) | null
|
card: (Pick<FlowEntityCard, "id" | "name" | "country" | "site"> & Partial<FlowEntityCard>) | null
|
||||||
analytics: FlowAnalyticsDto | null
|
analytics: FlowAnalyticsDto | null
|
||||||
@@ -349,14 +356,16 @@ export function FlowAnalyticsDetail({
|
|||||||
onExcludeOverlay: (value: boolean) => void
|
onExcludeOverlay: (value: boolean) => void
|
||||||
liveHint?: string
|
liveHint?: string
|
||||||
emptyHint?: string
|
emptyHint?: string
|
||||||
|
initialService?: string
|
||||||
|
initialCountry?: string
|
||||||
|
mapNodes?: string[]
|
||||||
}) {
|
}) {
|
||||||
const [slice, setSlice] = useState("applications")
|
const [slice, setSlice] = useState(initialService ? "sessions" : "applications")
|
||||||
const [sessionFilter, setSessionFilter] = useState<SessionFilter | null>(null)
|
const [sessionFilter, setSessionFilter] = useState<SessionFilter | null>(initialService ? { kind: "map-service", label: initialService, country: initialCountry } : null)
|
||||||
const rxNow = analytics ? analytics.bpsNow / 1_000_000 : (card?.rxNow ?? 0)
|
const rxNow = analytics?.bytes ? analytics.bpsNow / 1_000_000 : (card?.rxNow ?? null)
|
||||||
const bytes = analytics?.bytes ?? card?.bytes ?? 0
|
const bytes = analytics?.bytes ?? card?.bytes ?? 0
|
||||||
const sessionRows = (analytics?.conversationsList ?? []).filter((row) =>
|
const sessionRows = (analytics?.conversationsList ?? []).filter(row =>
|
||||||
sessionFilter ? talkerMatchesFilter(row, sessionFilter) : true,
|
(!mapNodes || mapNodes.includes(row.enId || row.serverId)) && (!sessionFilter || talkerMatchesFilter(row, sessionFilter)))
|
||||||
)
|
|
||||||
|
|
||||||
function pickBreakdown(kind: BreakdownFilter["kind"], row: FlowBreakdownRow) {
|
function pickBreakdown(kind: BreakdownFilter["kind"], row: FlowBreakdownRow) {
|
||||||
setSessionFilter({ kind, value: row.id, label: row.label })
|
setSessionFilter({ kind, value: row.id, label: row.label })
|
||||||
|
|||||||
@@ -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
|
if (label.includes(svc)) return label
|
||||||
return `${label} · ${svc}`
|
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])
|
||||||
|
}
|
||||||
@@ -960,17 +960,16 @@ export function buildGreMapEdges(
|
|||||||
if (!a || !b) continue
|
if (!a || !b) continue
|
||||||
if (a.id === b.id) continue
|
if (a.id === b.id) continue
|
||||||
|
|
||||||
const la = layerOfServer(a)
|
const aIsIx = a.type === "ix-node", bIsIx = b.type === "ix-node"
|
||||||
const lb = layerOfServer(b)
|
const la = aIsIx ? roleLayer("EN") : layerOfServer(a)
|
||||||
if (la == null || lb == null) continue
|
const lb = bIsIx ? roleLayer("EN") : layerOfServer(b)
|
||||||
// EN→EN, JH→JH и т.п. на карте не показываем — только межуровневые рёбра.
|
if (la == null || lb == null || la === lb && !aIsIx && !bIsIx) continue
|
||||||
if (la === lb) continue
|
|
||||||
|
|
||||||
// Строгий поток слева направо: HR → JH → EN.
|
// Строгий поток слева направо: HR → JH → EN.
|
||||||
// Если направление туннеля против иерархии — переворачиваем визуальное ребро.
|
// Если направление туннеля против иерархии — переворачиваем визуальное ребро.
|
||||||
let fromServer = a
|
let fromServer = a
|
||||||
let toServer = b
|
let toServer = b
|
||||||
if (la > lb) {
|
if (la > lb || la === lb && a.id > b.id) {
|
||||||
fromServer = b
|
fromServer = b
|
||||||
toServer = a
|
toServer = a
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import assert from "node:assert/strict"
|
|||||||
import {buildServerResourceMap,greTunnelProbe} from "./network-map-layout"
|
import {buildServerResourceMap,greTunnelProbe} from "./network-map-layout"
|
||||||
import {mergeGreMetricsWithSpeedProbe} from "./map-gre-speed-probe"
|
import {mergeGreMetricsWithSpeedProbe} from "./map-gre-speed-probe"
|
||||||
import {servers,greTunnels} from "./data"
|
import {servers,greTunnels} from "./data"
|
||||||
|
import {scopeMapDestinations} from "./network-map-scope"
|
||||||
test("live resources preserve zero, partial poll and unknowns without fake history",()=>{
|
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 base={...servers[0],cpuLoad:undefined,totalMemory:undefined,freeMemory:undefined,uptime:undefined,polledAt:undefined}
|
||||||
const unknown=buildServerResourceMap([base])[base.id]
|
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)
|
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})
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,7 +27,7 @@ export function validateNetworkMapSnapshot(servers:unknown,gre:unknown,probes:un
|
|||||||
|
|
||||||
import {flowMapHopsDtoSchema} from "@mmapp/contracts/traffic-flow"
|
import {flowMapHopsDtoSchema} from "@mmapp/contracts/traffic-flow"
|
||||||
import {isIpv4String} from "./gre-endpoint-resolve"
|
import {isIpv4String} from "./gre-endpoint-resolve"
|
||||||
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true }).refine(data =>
|
export const networkMapFlowSchema = flowMapHopsDtoSchema.required().partial({ sourceWindow: true, interfaceTraffic: true, includesCurrentMinute: true, nodeUsers: true }).refine(data =>
|
||||||
(data.includesCurrentMinute
|
(data.includesCurrentMinute
|
||||||
? !data.sourceWindow && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120
|
? !data.sourceWindow && data.rangeMinutes === 1 && data.windowSec >= 60 && data.windowSec < 120
|
||||||
: data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow
|
: data.windowSec === data.rangeMinutes * 60 && (data.sourceWindow
|
||||||
|
|||||||
@@ -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(),
|
site: z.string(),
|
||||||
country: z.string(),
|
country: z.string(),
|
||||||
status: z.enum(["online", "offline", "degraded"]),
|
status: z.enum(["online", "offline", "degraded"]),
|
||||||
rxNow: z.number(),
|
rxNow: z.number().nullable(),
|
||||||
txNow: z.number(),
|
txNow: z.number().nullable(),
|
||||||
sessions: z.number().int().nonnegative(),
|
sessions: z.number().int().nonnegative(),
|
||||||
rxSeries: z.array(z.number()),
|
rxSeries: z.array(z.number()),
|
||||||
txSeries: z.array(z.number()),
|
txSeries: z.array(z.number()),
|
||||||
@@ -366,6 +366,9 @@ export const flowMapHopDtoSchema = z.object({
|
|||||||
bpsRev: z.number().nonnegative(),
|
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({
|
export const flowMapServiceDtoSchema = z.object({
|
||||||
id: z.string(),
|
id: z.string(),
|
||||||
label: z.string(),
|
label: z.string(),
|
||||||
@@ -373,6 +376,16 @@ export const flowMapServiceDtoSchema = z.object({
|
|||||||
bytes: z.number().nonnegative(),
|
bytes: z.number().nonnegative(),
|
||||||
bps: z.number().nonnegative(),
|
bps: z.number().nonnegative(),
|
||||||
share: z.number().min(0).max(1),
|
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({
|
export const flowMapServiceEdgeDtoSchema = z.object({
|
||||||
@@ -388,6 +401,7 @@ export const flowMapServiceEdgeDtoSchema = z.object({
|
|||||||
id: z.string(),
|
id: z.string(),
|
||||||
name: z.string(),
|
name: z.string(),
|
||||||
})).optional(),
|
})).optional(),
|
||||||
|
observedOnly: z.literal(true).optional(),
|
||||||
})
|
})
|
||||||
|
|
||||||
export const flowMapServicePathDtoSchema = z.object({
|
export const flowMapServicePathDtoSchema = z.object({
|
||||||
@@ -395,6 +409,8 @@ export const flowMapServicePathDtoSchema = z.object({
|
|||||||
clientName: z.string(),
|
clientName: z.string(),
|
||||||
viaId: z.string(),
|
viaId: z.string(),
|
||||||
viaName: 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(),
|
enId: z.string(),
|
||||||
enName: z.string(),
|
enName: z.string(),
|
||||||
serviceId: z.string(),
|
serviceId: z.string(),
|
||||||
@@ -412,6 +428,12 @@ export const flowMapCountryServiceGroupDtoSchema = z.object({
|
|||||||
|
|
||||||
export const flowMapHopsDtoSchema = z.object({
|
export const flowMapHopsDtoSchema = z.object({
|
||||||
sourceWindow: flowSourceWindowSchema.optional(),
|
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(),
|
includesCurrentMinute: z.literal(true).optional(),
|
||||||
/** Link counters include private routed payload. Mesh visibility applies to the inferred graph. */
|
/** Link counters include private routed payload. Mesh visibility applies to the inferred graph. */
|
||||||
interfaceTraffic: z.array(z.object({
|
interfaceTraffic: z.array(z.object({
|
||||||
@@ -463,3 +485,4 @@ export type FlowMapServicePath = z.infer<typeof flowMapServicePathDtoSchema>
|
|||||||
export type FlowMapCountryServiceGroup = z.infer<typeof flowMapCountryServiceGroupDtoSchema>
|
export type FlowMapCountryServiceGroup = z.infer<typeof flowMapCountryServiceGroupDtoSchema>
|
||||||
export type FlowMapHopsDto = z.infer<typeof flowMapHopsDtoSchema>
|
export type FlowMapHopsDto = z.infer<typeof flowMapHopsDtoSchema>
|
||||||
export type FlowMapInterfaceTraffic = NonNullable<FlowMapHopsDto["interfaceTraffic"]>[number]
|
export type FlowMapInterfaceTraffic = NonNullable<FlowMapHopsDto["interfaceTraffic"]>[number]
|
||||||
|
export type FlowMapUser = NonNullable<FlowMapHopsDto["nodeUsers"]>[string][number]
|
||||||
@@ -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 page.goto("/settings");await page.getByRole("link",{name:/^Карта сети/}).click()
|
||||||
await expect(page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Прежняя карта",{exact:true})).toBeVisible()
|
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"
|
const path=part==="snapshot"?"/api/servers":part==="flow"?"/api/traffic/flow/map-hops":"/api/network/resolve-hosts"
|
||||||
await page.route("**/api/**",async r=>{
|
await page.route("**/api/**",async r=>{
|
||||||
const u=new URL(r.request().url());if(u.port!=="8000"||u.pathname!==path||started)return r.fallback()
|
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")}
|
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()
|
else await page.getByRole("button",{name:"Моковые",exact:true}).click()
|
||||||
await page.getByRole("link",{name:/^Карта сети/}).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()}
|
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("Демо · mock",{exact:true})).toBeVisible()
|
else await expect(page.getByText("Демонстрационные данные",{exact:true})).toBeVisible()
|
||||||
const before=newReads;release();await expect.poll(()=>completed).toBe(true)
|
const before=newReads;release();await expect.poll(()=>completed).toBe(true)
|
||||||
await page.evaluate(()=>new Promise<void>(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))))
|
await page.evaluate(()=>new Promise<void>(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))))
|
||||||
await expect(page.getByText("Старая ошибка карты",{exact:false})).toHaveCount(0)
|
await expect(page.getByText("Старая ошибка карты",{exact:false})).toHaveCount(0)
|
||||||
|
|||||||
@@ -38,8 +38,10 @@ test("Карта: неизвестный статус не становится
|
|||||||
await page.route("**/health",r=>r.fulfill({json:{ok:true}}))
|
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.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 page.goto("/network-map")
|
||||||
|
await page.getByText("Сводка сети", {exact:true}).click()
|
||||||
await expect(page.getByRole("button",{name:"Неизвестно 1",exact:true})).toBeVisible()
|
await expect(page.getByRole("button",{name:"Неизвестно 1",exact:true})).toBeVisible()
|
||||||
await expect(page.getByRole("button",{name:"Оффлайн 0",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 page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Роутер",{exact:true}).click()
|
||||||
await expect(page.getByRole("complementary", {name:"Детали объекта карты"}).getByText("Неизвестно", {exact:true}).first()).toBeVisible()
|
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()
|
await page.getByRole("button",{name:/^Фильтр/}).click();await page.getByRole("button",{name:"Неизвестно",exact:true}).click()
|
||||||
|
|||||||
@@ -19,7 +19,11 @@ test("Карта: открытые детали обновляются вмес
|
|||||||
})
|
})
|
||||||
test("Карта: модель WAN не утверждает активный маршрут и RTT линии",async({page})=>{
|
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.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 page.locator("[data-map-legend] summary").click();await expect(page.getByText("Пунктир WAN→JH — модель связности; маршрут не подтверждён.",{exact:true})).toBeVisible();await page.locator("[data-map-legend] summary").click()
|
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 expect(page.locator("svg text").filter({hasText:/^5 мс$/})).toHaveCount(0)
|
||||||
await page.getByRole("group",{name:"Интерактивная карта сети"}).getByText("Домашний",{exact:true}).click()
|
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()
|
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()
|
||||||
|
|||||||
@@ -1,12 +1,77 @@
|
|||||||
import {test,expect} from "@playwright/test"
|
import {test,expect} from "@playwright/test"
|
||||||
import { installOpenLiveStream } from "./live-stream-fixture"
|
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 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"
|
const flowPath="/api/traffic/flow/map-hops"
|
||||||
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
|
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"}
|
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}) => {
|
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}
|
const edge = {fromId: "1", toId: service.id, bytes: 300000, bps: 8000, bpsFwd: 2000, bpsRev: 6000}
|
||||||
let known = false
|
let known = false
|
||||||
await page.route("**/api/**", route => {
|
await page.route("**/api/**", route => {
|
||||||
@@ -25,6 +90,10 @@ test("Карта не приписывает весь YouTube единствен
|
|||||||
})
|
})
|
||||||
await page.goto("/network-map")
|
await page.goto("/network-map")
|
||||||
await page.getByRole("button", {name: "Сервис YouTube", exact: true}).press("Enter")
|
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 unknown = page.getByText("Выход не определён", {exact: true}).locator("..")
|
||||||
const badges = page.locator("[data-map-ribbon] > title")
|
const badges = page.locator("[data-map-ribbon] > title")
|
||||||
await expect(unknown).toContainText("24 Кбит/с")
|
await expect(unknown).toContainText("24 Кбит/с")
|
||||||
@@ -37,6 +106,58 @@ test("Карта не приписывает весь YouTube единствен
|
|||||||
await expect(badges).toContainText("↓6 Кбит/с ↑2 Кбит/с")
|
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 }) => {
|
for (const reverse of [false, true]) test(`Карта: малый NetFlow и текущие RX/TX GRE показаны отдельно, reverse=${reverse}`, async ({ page }) => {
|
||||||
const exit = { ...server, name: "ARN", type: "exit-node" }
|
const exit = { ...server, name: "ARN", type: "exit-node" }
|
||||||
const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" }
|
const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" }
|
||||||
@@ -96,8 +217,10 @@ for (const reverse of [false, true]) test(`Карта: малый NetFlow и т
|
|||||||
await expect(panel.getByText("↓14 бит/с ↑0 Кбит/с", { exact: true })).toBeVisible()
|
await expect(panel.getByText("↓14 бит/с ↑0 Кбит/с", { exact: true })).toBeVisible()
|
||||||
await expect(page.getByText("За интервал · 525 Б · 3 пак.")).toBeVisible()
|
await expect(page.getByText("За интервал · 525 Б · 3 пак.")).toBeVisible()
|
||||||
nativeAvailable = true
|
nativeAvailable = true
|
||||||
await expect(badge).toContainText("Live 81", {timeout: 18000})
|
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 expect(page.getByText("Макс. из замеров · Live", {exact: true}).locator("..")).toContainText("81")
|
||||||
|
await page.keyboard.press("Escape")
|
||||||
await expect(live).toContainText("↓80")
|
await expect(live).toContainText("↓80")
|
||||||
await expect(panel.getByText("↓14 бит/с ↑0 Кбит/с", { exact: true })).toBeVisible()
|
await expect(panel.getByText("↓14 бит/с ↑0 Кбит/с", { exact: true })).toBeVisible()
|
||||||
})
|
})
|
||||||
@@ -136,7 +259,7 @@ test("Карта: параллельные GRE с разными владель
|
|||||||
: path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} })
|
: path === "/api/uptime/speed-probes" ? { probes: [] } : path === "/api/auth/config" ? { required: false } : {} })
|
||||||
})
|
})
|
||||||
await page.goto("/network-map")
|
await page.goto("/network-map")
|
||||||
await expect(page.getByRole("button", { name: /^Связь Router → Exit: Live 90.*GRE ×2$/ })).toHaveCount(1)
|
await expect(page.getByRole("button", { name: /^Связь Router → Exit: 90.*GRE ×2$/ })).toHaveCount(1)
|
||||||
expect(liveReads).toBeGreaterThan(0)
|
expect(liveReads).toBeGreaterThan(0)
|
||||||
await page.getByRole("button", { name: "Устройство Router", exact: true }).click()
|
await page.getByRole("button", { name: "Устройство Router", exact: true }).click()
|
||||||
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
|
const panel = page.getByRole("complementary", { name: "Детали объекта карты" })
|
||||||
@@ -172,7 +295,7 @@ for(const malformed of [false,true])test("Карта: NetFlow отказ и по
|
|||||||
await expect(page.getByRole("alert").filter({hasText:"Первоначальная загрузка NetFlow"})).toBeVisible()
|
await expect(page.getByRole("alert").filter({hasText:"Первоначальная загрузка NetFlow"})).toBeVisible()
|
||||||
await expect(page.getByText("Данные NetFlow неизвестны",{exact:true})).toBeVisible()
|
await expect(page.getByText("Данные NetFlow неизвестны",{exact:true})).toBeVisible()
|
||||||
failing=false;await page.getByRole("button",{name:"Обновить",exact:true}).click()
|
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)
|
await expect(page.getByRole("alert").filter({hasText:"NetFlow:"})).toHaveCount(0)
|
||||||
})
|
})
|
||||||
test("Карта: NetFlow сохраняет сервис при фоновом сбое",async({page})=>{
|
test("Карта: NetFlow сохраняет сервис при фоновом сбое",async({page})=>{
|
||||||
@@ -197,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.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.goto("/network-map");await expect.poll(()=>requests).toBe(1)
|
||||||
await page.clock.runFor(5000);expect(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("**/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}:{}})})
|
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 page.setViewportSize({width,height:900});await page.goto("/network-map")
|
||||||
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||||
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
|
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.screenshot({path:testInfo.outputPath("network-map-overview.png")})
|
||||||
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
|
await page.getByRole("textbox",{name:"Поиск узла или назначения"}).fill("Домашний");await page.getByRole("group",{name:"Подсказки поиска"}).getByRole("button",{name:/^Домашний/}).click()
|
||||||
const panel=page.getByRole("complementary",{name:"Детали объекта карты"})
|
const panel=page.getByRole("complementary",{name:"Детали объекта карты"})
|
||||||
await expect(panel).toBeVisible();await expect(panel.getByText("Ресурсы",{exact:true})).toBeVisible()
|
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)
|
expect(bounds!.width).toBeGreaterThan(250);expect(bounds!.height).toBeGreaterThan(350)
|
||||||
if(width<1024)await expect(page.getByRole("group",{name:"Интерактивная карта сети"})).toBeHidden()
|
expect(map!.height).toBeGreaterThanOrEqual(390)
|
||||||
else expect(map!.height).toBeGreaterThan(0)
|
if(width>=1024)expect(bounds!.x).toBeGreaterThan(map!.x+map!.width/2)
|
||||||
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true)
|
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 panel.getByRole("button",{name:"Закрыть детали устройства"}).click()
|
||||||
await expect(panel).toHaveCount(0)
|
await expect(panel).toHaveCount(0)
|
||||||
const node=page.getByRole("button",{name:/^Устройство Домашний/});await node.focus();await node.press("Enter");await expect(panel).toBeVisible()
|
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.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/)
|
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})=>{
|
test("Карта: reduced motion и самостоятельный SVG экспорт",async({page})=>{
|
||||||
await page.emulateMedia({reducedMotion:"reduce"});await page.goto("/network-map")
|
await page.emulateMedia({reducedMotion:"reduce"});await page.goto("/network-map")
|
||||||
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
await expect(page.getByRole("button",{name:/^Устройство Домашний/})).toBeVisible()
|
||||||
|
|||||||
@@ -17,20 +17,30 @@ test.beforeEach(async ({ page }) => {
|
|||||||
|
|
||||||
test("Карта: раскрытая легенда объясняет статусы, типы, линии и неизвестные измерения", async ({ page }) => {
|
test("Карта: раскрытая легенда объясняет статусы, типы, линии и неизвестные измерения", async ({ page }) => {
|
||||||
await page.goto("/network-map")
|
await page.goto("/network-map")
|
||||||
|
const trigger = page.getByRole("button", { name: "Легенда", exact: true })
|
||||||
const legend = page.getByRole("region", { name: "Легенда карты" })
|
const legend = page.getByRole("region", { name: "Легенда карты" })
|
||||||
await expect(legend).not.toBeVisible()
|
await expect(legend).not.toBeVisible()
|
||||||
await page.locator("[data-map-legend] summary").click()
|
await trigger.click()
|
||||||
await expect(legend).toBeVisible()
|
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 expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS")
|
await expect(legend).toContainText("последний замер RX/TX интерфейса RouterOS")
|
||||||
await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX")
|
await expect(legend).toContainText("среднюю скорость по принятым записям IPFIX")
|
||||||
await page.locator("[data-map-legend] summary").click()
|
await trigger.click()
|
||||||
await expect(legend).not.toBeVisible()
|
await expect(legend).not.toBeVisible()
|
||||||
await page.locator("[data-map-legend] summary").press("Enter")
|
await trigger.press("Enter")
|
||||||
await expect(legend).toBeVisible()
|
await expect(legend).toBeVisible()
|
||||||
await legend.getByText("Онлайн", { exact: true }).click()
|
await legend.getByText("Онлайн", { exact: true }).click()
|
||||||
await page.screenshot({ path: "tmp/map270-desktop.png" })
|
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 }) => {
|
test("Карта: мышь не рисует прямоугольную рамку, клавиатурный фокус остаётся видимым", async ({ page }) => {
|
||||||
@@ -52,15 +62,16 @@ test("Карта: мышь не рисует прямоугольную рамк
|
|||||||
test("Карта: легенда помещается на телефоне и сворачивается", async ({ page }) => {
|
test("Карта: легенда помещается на телефоне и сворачивается", async ({ page }) => {
|
||||||
await page.setViewportSize({ width: 390, height: 844 })
|
await page.setViewportSize({ width: 390, height: 844 })
|
||||||
await page.goto("/network-map")
|
await page.goto("/network-map")
|
||||||
|
const trigger = page.getByRole("button", { name: "Легенда", exact: true })
|
||||||
const legend = page.getByRole("region", { name: "Легенда карты" })
|
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.screenshot({ path: "tmp/map270-mobile.png" })
|
||||||
await page.locator("[data-map-legend] summary").click()
|
await trigger.click()
|
||||||
await expect(legend).toBeVisible()
|
await expect(legend).toBeVisible()
|
||||||
const bounds = await legend.boundingBox()
|
const bounds = await legend.boundingBox()
|
||||||
expect(bounds!.x).toBeGreaterThanOrEqual(0)
|
expect(bounds!.x).toBeGreaterThanOrEqual(0)
|
||||||
expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390)
|
expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390)
|
||||||
await page.locator("[data-map-legend] summary").click()
|
await trigger.click()
|
||||||
await expect(legend).not.toBeVisible()
|
await expect(legend).not.toBeVisible()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 серв
|
|||||||
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" }))
|
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 serve(page, servers, tunnels, { services, serviceEdges, interfaceTraffic, totalBytes: 5e7, namedBytes: 5e7 })
|
||||||
await page.goto("/network-map")
|
await page.goto("/network-map")
|
||||||
|
await page.getByRole("button", { name: /^Остальные сервисы \(/ }).first().click()
|
||||||
await expect(page.getByRole("button", { name: "Сервис Telegram", exact: true })).toBeVisible()
|
await expect(page.getByRole("button", { name: "Сервис Telegram", exact: true })).toBeVisible()
|
||||||
await expect.poll(async () => (await overlaps(page)).cards).toBe(5)
|
await expect.poll(async () => (await overlaps(page)).cards).toBe(5)
|
||||||
const result = await overlaps(page)
|
const result = await overlaps(page)
|
||||||
@@ -64,6 +65,46 @@ test("Карта: 3 JH → Exit + IX, параллельные GRE и 8 серв
|
|||||||
expect(await page.locator("path > title", { hasText: pair }).count()).toBeGreaterThan(0)
|
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 }) => {
|
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 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 = [
|
const servers = [
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ async function setup(page: Page) {
|
|||||||
|
|
||||||
test('Детали трафика: поздний период не заменяет текущий', async ({ page }) => {
|
test('Детали трафика: поздний период не заменяет текущий', async ({ page }) => {
|
||||||
const control = await setup(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'
|
control.holdRange = '24h'
|
||||||
const started = page.waitForRequest(r => new URL(r.url()).pathname === '/api/traffic/servers/1' && r.url().includes('range=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()
|
await page.getByRole('button', { name: '24ч', exact: true }).click()
|
||||||
|
|||||||
@@ -41,15 +41,39 @@ test('Список трафика: поздний период не заменя
|
|||||||
await started
|
await started
|
||||||
await expect(page.getByText('Загрузка списка трафика…', { exact: true })).toBeVisible()
|
await expect(page.getByText('Загрузка списка трафика…', { exact: true })).toBeVisible()
|
||||||
await expect(page.getByRole('button').filter({ hasText: 'Список 1h' })).toHaveCount(0)
|
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 page.getByRole('button', { name: '15м', exact: true }).click()
|
||||||
await expect(page.getByRole('button').filter({ hasText: 'Список 15m' })).toBeVisible()
|
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()
|
control.release()
|
||||||
await late
|
await cancelled
|
||||||
await expect(page.getByRole('button').filter({ hasText: 'Список 15m' })).toBeVisible()
|
await expect(page.getByRole('button').filter({ hasText: 'Список 15m' })).toBeVisible()
|
||||||
await expect(page.getByRole('button').filter({ hasText: 'Список 24h' })).toHaveCount(0)
|
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 }) => {
|
test('Список трафика: ошибка обновления скрывает сводку; повтор восстанавливает список', async ({ page }) => {
|
||||||
const control = await setup(page)
|
const control = await setup(page)
|
||||||
control.failList = true
|
control.failList = true
|
||||||
|
|||||||
Reference in new issue
Block a user