Compare commits

...
5 Commits
Author SHA1 Message Date
Denozordec 682d6c8d55 fix(mcp): разрешить настройку размера сегмента TCP
Docker images / prepare-release (push) Successful in 9s
Docker images / backend-test (push) Successful in 10m27s
Docker images / backend-image (push) Successful in 2m19s
Docker images / frontend-image (push) Successful in 2m16s
Docker images / updater-image (push) Successful in 38s
Docker images / netflow-agent-image (push) Successful in 45s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 10s
2026-11-25 13:35:20 +07:00
Denozordec a41c70b104 feat(ix): добавить одноразовые ссылки импорта конфигураций
Docker images / prepare-release (push) Successful in 9s
Docker images / updater-image (push) Successful in 42s
Docker images / netflow-agent-image (push) Successful in 36s
Docker images / backend-test (push) Successful in 9m43s
Docker images / backend-image (push) Successful in 1m59s
Docker images / frontend-image (push) Successful in 15m47s
Docker images / notify-webhook (push) Successful in 0s
Docker images / publish-release (push) Successful in 10s
2026-11-25 11:46:51 +07:00
Denozordec 01779d7ee6 fix(scheduler): дождаться освобождения блокировки перед сбором метрик
Docker images / prepare-release (push) Successful in 9s
Docker images / updater-image (push) Successful in 3m22s
Docker images / frontend-image (push) Successful in 3m26s
Docker images / netflow-agent-image (push) Successful in 3m21s
Docker images / backend-test (push) Successful in 25m38s
Docker images / backend-image (push) Successful in 20m27s
Docker images / notify-webhook (push) Successful in 1s
Docker images / publish-release (push) Successful in 9s
2026-11-24 22:01:12 +07:00
Denozordec 1b927dcf68 fix(traffic): показывать показатели интерфейсов при неполных замерах
Docker images / prepare-release (push) Successful in 9s
Docker images / backend-test (push) Successful in 2s
Docker images / backend-image (push) Successful in 15s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 1m18s
Docker images / notify-webhook (push) Successful in 2s
Docker images / publish-release (push) Successful in 29s
Docker images / frontend-image (push) Successful in 6m50s
2026-11-24 16:37:50 +07:00
Denozordec af82497f20 fix(netflow): исправить учёт трафика по выходным узлам на карте сети
Docker images / prepare-release (push) Successful in 12s
Docker images / backend-test (push) Successful in 10m33s
Docker images / updater-image (push) Successful in 39s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 2m0s
Docker images / frontend-image (push) Successful in 7m41s
Docker images / publish-release (push) Successful in 33s
Docker images / notify-webhook (push) Successful in 1m55s
2026-11-24 15:41:44 +07:00
30 changed files with 603 additions and 283 deletions

No files matched your search

+10
View File
@@ -12,6 +12,8 @@ import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetT
import { requestJson } from "@/shared/api/http-client"
import { nodeLabel, type IxNode } from "./ix-view"
import { IxExistingTransport } from "./ix-existing-transport"
import { toast } from "sonner"
import { copyIxImportLink } from "./ix-import-link"
const modes = [
{ value: "failover", label: "Основной и резервные" },
@@ -107,6 +109,14 @@ export function IxClientBonds({ segmentId, segments, backendUrl, nodes, readOnly
{ method: "POST", body: JSON.stringify({ revision: g.revision }) })
download("ix-bond-" + g.id + ".json", JSON.stringify(bundle, null, 2))
})}>Скачать для ix-client</Button>
<Button size="sm" variant="outline" disabled={busy} onClick={() => void perform(async () => {
try {
await copyIxImportLink(backendUrl, `/api/ix/segments/${g.ownerSegmentId}/linux-bonds/${g.id}/export`, { revision: g.revision })
toast.success("Ссылка скопирована. На VPS откройте ix-client → L.")
} catch (error) {
toast.error(error instanceof Error ? error.message : "Не удалось скопировать ссылку")
}
})}>Скопировать ссылку для ix-client</Button>
</div>}
</div>)
const rows = children(binding => {
+12
View File
@@ -0,0 +1,12 @@
import { requestJson } from "@/shared/api/http-client"
export async function copyIxImportLink(backendUrl: string, path: string, params: object) {
const link = new URL(backendUrl.replace(/\/$/, "") + "/api/ix/import", window.location.origin)
if (link.protocol !== "https:" || !navigator.clipboard) throw new Error("Для одноразовой ссылки откройте Manager по HTTPS")
const { code } = await requestJson<{ code: string }>(backendUrl, path, {
method: "POST", body: JSON.stringify({ ...params, importLink: true }),
})
if (!/^[A-Za-z0-9_-]{32}$/.test(code)) throw new Error("Manager вернул неверный код импорта")
link.hash = code
await navigator.clipboard.writeText(link.toString())
}
+5 -3
View File
@@ -239,11 +239,11 @@ function TunnelTable({ data, columns, busy }: {
return <DataGridShell table={table} recordCount={data.length} isLoading={busy && !data.length} loadingMode="skeleton" emptyMessage="В сегменте пока нет Linux-клиентов" />
}
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, inspect, bondAction, catalog, renderGroups, manualGroup }: {
export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly, busy, error, save, refresh, revoke, view, copyImport, inspect, bondAction, catalog, renderGroups, manualGroup }: {
segment: IxSegment; nodes: IxNode[]; backendUrl: string; applied: IxLinuxBinding[]; readOnly: boolean; busy: boolean; error?: string
save: (input: IxLinuxClientRequest) => Promise<boolean>; refresh: () => void
view: (binding: IxLinuxBinding, transportOnly?: boolean) => void; revoke: (binding: IxLinuxBinding) => void
inspect: (binding: IxLinuxBinding) => void
copyImport: (binding: IxLinuxBinding) => void; inspect: (binding: IxLinuxBinding) => void
bondAction: IxRowBondAction; catalog: IxBondCatalog
renderGroups: (clientId: string) => ReactNode; manualGroup: ReactNode
}) {
@@ -331,6 +331,8 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
{bond && <DropdownMenuItem onClick={bond.open}>{bond.label}</DropdownMenuItem>}
{live && (binding.policy || catalog.candidates.some(c => c.segmentId === segment.id && c.serverId === live.serverId && c.interfaceName === live.interfaceName)) &&
<DropdownMenuItem onClick={() => view(live, true)}>Конфиг для группы ix-client</DropdownMenuItem>}
{!readOnly && live?.policy && (live.managedWireguard || live.kind === "gre-ipsec") &&
<DropdownMenuItem onClick={() => copyImport(live)}>Скопировать ссылку для ix-client</DropdownMenuItem>}
{live?.policy && <DropdownMenuItem onClick={() => inspect(live)}>Проверить путь</DropdownMenuItem>}
{!readOnly && site && saved?.linux && <DropdownMenuItem
onClick={() => { setEdit({ site, binding: saved, addProtocol: true, chooseTransport: true }); setOpen(true) }}>Добавить туннель</DropdownMenuItem>}
@@ -339,7 +341,7 @@ export function IxLinuxClients({ segment, nodes, backendUrl, applied, readOnly,
</DropdownMenu>}
</div>
} },
], [nodes, applied, segment, readOnly, busy, view, revoke, inspect, bondAction, catalog.candidates])
], [nodes, applied, segment, readOnly, busy, view, copyImport, revoke, inspect, bondAction, catalog.candidates])
return <Frame spacing="sm" className="min-w-0">
<FrameHeader className="flex-row flex-wrap items-center justify-between gap-2">
<FrameTitle>Linux-клиенты</FrameTitle>
+10
View File
@@ -24,6 +24,7 @@ import { ConfigurationFields, newSite, nodeLabel, RouteGrid, SegmentGrid, Segmen
import { IxLinuxClients } from "./ix-linux-clients"
import { IxExits } from "./ix-exits"
import { IxClientBonds } from "./ix-client-bonds"
import { copyIxImportLink } from "./ix-import-link"
type Tab = "configuration" | "routes" | "linux"
@@ -281,6 +282,14 @@ export default function IxPage() {
setLinux({ ...binding, ...access, transportOnly })
}
async function copyLinuxImport(binding: IxLinuxBinding) {
if (!selected) return
await copyIxImportLink(backendUrl, `/api/ix/segments/${selected.id}/linux/credential`, {
serverId: binding.serverId, interfaceName: binding.interfaceName,
})
setNotice("Ссылка скопирована. На VPS откройте ix-client → L. Ссылка действует до 5 минут.")
}
async function inspectLinux(binding: IxLinuxBinding) {
if (!selected) return
setLinuxPath(null)
@@ -474,6 +483,7 @@ export default function IxPage() {
applied={linuxBindings} busy={busy} error={error} readOnly={!live || !write || dirty}
save={input => perform(() => stageClient(input))} revoke={binding => void perform(() => stageClient(binding))}
refresh={() => void perform(loadLinuxBindings)} view={(binding, transportOnly) => void perform(() => exportLinux(binding, transportOnly))}
copyImport={binding => void perform(() => copyLinuxImport(binding))}
inspect={binding => void perform(() => inspectLinux(binding))} />}
</IxClientBonds>
: <EmptyState title="Сохраните сегмент" description="После сохранения можно подключать клиентов." />}
+22 -95
View File
@@ -356,85 +356,6 @@ function serviceSharePct(share: number): string {
return `${Math.round(share * 100)}%`
}
function exitNodeIdsFromGre(greEdges: GreMapEdge[]): string[] {
const ids = new Set<string>()
for (const g of greEdges) {
if (g.fromServer.type === "exit-node") ids.add(g.fromServer.id)
if (g.toServer.type === "exit-node") ids.add(g.toServer.id)
}
return [...ids]
}
function remapServiceEdgeFromId(
fromId: string,
servers: Server[],
greEdges: GreMapEdge[],
soleEnId: string | null,
): string | null {
const srv = servers.find((s) => s.id === fromId)
if (srv?.type === "exit-node") return fromId
for (const g of greEdges) {
if (g.fromServer.id === fromId && g.toServer.type === "exit-node") return g.toServer.id
if (g.toServer.id === fromId && g.fromServer.type === "exit-node") return g.fromServer.id
}
return soleEnId
}
/** API-рёбра на EN; если hop нет — синтез от единственного EN на карте (GRE / каталог). */
function drawableServiceEdges(
services: FlowMapService[],
edges: FlowMapServiceEdge[],
servers: Server[],
greEdges: GreMapEdge[],
nodePosById: Record<string, { x: number; y: number }>,
): FlowMapServiceEdge[] {
const keep = new Set(services.map((s) => s.id))
const greEn = exitNodeIdsFromGre(greEdges)
const catalogEn = servers.filter((s) => s.type === "exit-node").map((s) => s.id)
const enPool = greEn.length > 0 ? greEn : catalogEn
const soleEnId = enPool.length === 1 ? enPool[0]! : null
const merged = new Map<string, FlowMapServiceEdge>()
function bump(e: FlowMapServiceEdge) {
const key = `${e.fromId}|${e.toId}`
const prev = merged.get(key)
if (!prev) {
merged.set(key, { ...e })
return
}
merged.set(key, {
...prev,
bytes: prev.bytes + e.bytes,
bps: prev.bps + e.bps,
bpsFwd: prev.bpsFwd + e.bpsFwd,
bpsRev: prev.bpsRev + e.bpsRev,
})
}
for (const e of edges) {
if (!keep.has(e.toId)) continue
const fromId = remapServiceEdgeFromId(e.fromId, servers, greEdges, soleEnId)
if (!fromId || !nodePosById[fromId]) continue
bump({ ...e, fromId })
}
const covered = new Set([...merged.values()].map((e) => e.toId))
if (soleEnId && nodePosById[soleEnId]) {
for (const svc of services) {
if (covered.has(svc.id)) continue
bump({
fromId: soleEnId,
toId: svc.id,
bytes: svc.bytes,
bps: svc.bps,
bpsFwd: svc.bps,
bpsRev: 0,
})
}
}
return [...merged.values()]
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
function pingColor(ms: number | null) {
@@ -597,6 +518,11 @@ function GreEdgeMetricBadge({
)
}
// The badge shows download first. Destination edges are oriented from exit to service.
function destinationRate(edge: FlowMapServiceEdge): MatchedNetflowHop {
return { bytes: edge.bytes, bps: edge.bps, bpsFwd: edge.bpsRev, bpsRev: edge.bpsFwd }
}
/** Живой поток NetFlow (не ёмкость канала / не BT). */
function NetflowRateBadge({
mx,
@@ -626,7 +552,7 @@ function NetflowRateBadge({
onClick={(e) => { e.stopPropagation(); onOpen?.(e) }}
>
<title>
{sourceLabel ? sourceLabel + " · RX/TX интерфейса" : "Поток NetFlow между узлами за интервал карты, без overlay/mesh."}
{sourceLabel ? sourceLabel + " · RX/TX интерфейса" : "Средняя скорость по сохранённым потокам NetFlow за завершённые минуты."}
</title>
<rect className="network-map-focus-ring" x={-bw / 2 - 4} y={-bh / 2 - 4} width={bw + 8} height={bh + 8} rx="9" fill="none" stroke="var(--ring)" strokeWidth="2" />
<rect
@@ -1683,9 +1609,14 @@ function NetworkMapContent() {
const visibleMapServices = showServices ? destNodes : []
const visibleServiceEdges = showServices
? drawableServiceEdges(visibleMapServices, destEdges, mapServers, greEdges, nodePosById)
? destEdges.filter(edge => nodePosById[edge.fromId] && visibleMapServices.some(service => service.id === edge.toId))
: []
const selectedExitEdges = destEdges.filter(edge => edge.toId === liveSelectedService?.id)
const unassignedBytes = liveSelectedService
? liveSelectedService.bytes - selectedExitEdges.reduce((sum, edge) => sum + edge.bytes, 0)
: 0
const nodes = mapServers
.map((s) => ({ ...s, ...nodePosById[s.id]! }))
// Визуальный приоритет: HR поверх JH, JH поверх EN.
@@ -2636,12 +2567,7 @@ function NetworkMapContent() {
const from = nodeById[edge.fromId] ?? nodePosById[edge.fromId]
const to = servicePosById[edge.toId]
if (!from || !to) return null
const hop: MatchedNetflowHop = {
bytes: edge.bytes,
bps: edge.bps,
bpsFwd: edge.bpsFwd,
bpsRev: edge.bpsRev,
}
const hop = destinationRate(edge)
const fromR = "type" in from && from.type
? TYPE_STYLE[from.type].r
: TYPE_STYLE["exit-node"].r
@@ -2721,12 +2647,7 @@ function NetworkMapContent() {
const from = servicePosById[edge.fromId]
const to = nestedPosById[edge.toId]
if (!from || !to) return null
const hop: MatchedNetflowHop = {
bytes: edge.bytes,
bps: edge.bps,
bpsFwd: edge.bpsFwd,
bpsRev: edge.bpsRev,
}
const hop = destinationRate(edge)
const clipped = clipSegmentCircleToRect(
from.x,
from.y,
@@ -3207,7 +3128,7 @@ function NetworkMapContent() {
</div>
)}
<div className="flex items-center justify-between py-2 border-b border-border/50">
<span className="text-xs text-muted-foreground">Скорость</span>
<span className="text-xs text-muted-foreground">Скорость по сохранённым потокам</span>
<span className="text-xs font-mono font-medium [overflow-wrap:anywhere] text-right">
{formatNetflowRate({
bytes: liveSelectedService.bytes,
@@ -3244,7 +3165,13 @@ function NetworkMapContent() {
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">Выход</p>
<div className="flex flex-col gap-3">
{visibleServiceEdges.filter((e) => e.toId === liveSelectedService.id).map((e) => {
{unassignedBytes > 0 && (
<div className="flex items-center justify-between text-xs">
<span>Выход не определён</span>
<span className="font-mono">{formatNetflowRate({ bps: liveSelectedService.bps * unassignedBytes / liveSelectedService.bytes })}</span>
</div>
)}
{selectedExitEdges.map((e) => {
const src = mapServers.find((s) => s.id === e.fromId)
const enPaths = destPaths
.filter((p) => p.serviceId === liveSelectedService.id && p.enId === e.fromId)
+19 -13
View File
@@ -2,7 +2,7 @@
import { useState, useMemo, useEffect, type ReactNode } from "react"
import { Alert, AlertTitle, AlertDescription } from "@/components/reui/alert"
import { peakOfCombinedTraffic, projectTrafficObservations, type TrafficObservationMeta } from "@/lib/traffic-observations"
import { peakOfCombinedTraffic, projectTrafficObservations, sumObservedTraffic, type TrafficObservationMeta } from "@/lib/traffic-observations"
import { projectTrafficBindingStatus } from "@/lib/traffic-binding-status"
import { TrafficObservationStatus } from "@/components/traffic/traffic-observation-status"
import { TrafficDataTime } from "@/components/traffic/traffic-data-time"
@@ -1143,11 +1143,17 @@ export default function TrafficPage() {
: effectiveMode === "ifaces"
? activeBoundIfaces
: activeServerTraffic
const totalRx = kpiSource.length && kpiSource.every(s => s.rxNow !== null) ? kpiSource.reduce((a, s) => a + (s.rxNow ?? 0), 0) : null
const totalTx = kpiSource.length && kpiSource.every(s => s.txNow !== null) ? kpiSource.reduce((a, s) => a + (s.txNow ?? 0), 0) : null
const allowPartialKpi = effectiveMode === "ifaces"
const totalRx = sumObservedTraffic(kpiSource.map(s => s.rxNow))
const totalTx = sumObservedTraffic(kpiSource.map(s => s.txNow))
const exactPeaks = effectiveMode === "servers" && trafficReady ? trafficState?.peaks : undefined
const peakRx = exactPeaks ? exactPeaks.rx : peakOfCombinedTraffic(kpiSource.map(s => s.rxSeries))
const peakTx = exactPeaks ? exactPeaks.tx : peakOfCombinedTraffic(kpiSource.map(s => s.txSeries))
const peakRx = exactPeaks ? { value: exactPeaks.rx, observed: kpiSource.length } : peakOfCombinedTraffic(kpiSource.map(s => s.rxSeries), allowPartialKpi)
const peakTx = exactPeaks ? { value: exactPeaks.tx, observed: kpiSource.length } : peakOfCombinedTraffic(kpiSource.map(s => s.txSeries), allowPartialKpi)
const coverageHint = (observed: number) => allowPartialKpi && observed > 0 && observed < kpiSource.length
? `${observed} из ${kpiSource.length} интерф.`
: undefined
const totalHint = effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined
const peakHint = exactPeaks ? "По общим замерам" : "По интервалам графика"
const visibleSortFields = SORT_FIELDS.filter(s => !s.modesOnly || s.modesOnly.includes(effectiveMode))
const ingestLine = flowIngestLine(collectorStatus)
@@ -1192,32 +1198,32 @@ export default function TrafficPage() {
{
id: "rx",
label: "Сумма RX",
value: fmtRate(totalRx),
hint: effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined,
value: fmtRate(allowPartialKpi || totalRx.observed === kpiSource.length ? totalRx.value : null),
hint: coverageHint(totalRx.observed) ?? totalHint,
icon: <ArrowDownIcon className="size-4" />,
iconClassName: "text-success",
},
{
id: "tx",
label: "Сумма TX",
value: fmtRate(totalTx),
hint: effectiveMode === "servers" ? "Интерфейсы и туннели" : undefined,
value: fmtRate(allowPartialKpi || totalTx.observed === kpiSource.length ? totalTx.value : null),
hint: coverageHint(totalTx.observed) ?? totalHint,
icon: <ArrowUpIcon className="size-4" />,
iconClassName: "text-info",
},
{
id: "peak-rx",
label: "Пик суммы RX",
value: fmtRate(peakRx),
hint: exactPeaks ? "По общим замерам" : "По интервалам графика",
value: fmtRate(peakRx.value),
hint: coverageHint(peakRx.observed) ?? peakHint,
icon: <TrendingUpIcon className="size-4" />,
iconClassName: "text-warning",
},
{
id: "peak-tx",
label: "Пик суммы TX",
value: fmtRate(peakTx),
hint: exactPeaks ? "По общим замерам" : "По интервалам графика",
value: fmtRate(peakTx.value),
hint: coverageHint(peakTx.observed) ?? peakHint,
icon: <TrendingUpIcon className="size-4" />,
iconClassName: "text-warning",
},
+7
View File
@@ -464,6 +464,13 @@
],
"reason": "Общий listRevisions с REST: только метаданные, максимум 50 записей; серверная область и права проверяются до SQL, payload ревизии не выдаётся."
},
{
"method": "POST",
"path": "/api/ix/import",
"status": "excluded",
"operations": [],
"reason": "Одноразовый импорт Linux-клиента: выдаёт конфигурацию только по коду, созданному оператором IX."
},
{
"method": "GET",
"path": "/api/ix/linux-bonds",
+1 -1
View File
@@ -60,7 +60,7 @@
"test:ipsec": "tsx src/services/ipsec-config.test.ts && tsx src/services/ipsec-state.test.ts && tsx src/routes/ipsec-history.test.ts && tsx src/services/ipsec-restore.test.ts && tsx src/services/ipsec-operation.test.ts && tsx src/routes/ipsec-mutation.test.ts && tsx src/routes/ipsec-nat.test.ts && tsx src/routes/ipsec-group.test.ts && tsx src/services/ipsec-peer-delete.test.ts && tsx src/modules/mcp/ipsec-peer-delete-actions.test.ts && tsx src/services/ipsec-user-delete.test.ts && tsx src/modules/mcp/ipsec-user-delete-actions.test.ts && tsx src/services/ipsec-certificate-delete.test.ts && tsx src/modules/mcp/ipsec-certificate-delete-actions.test.ts && tsx src/services/ipsec-peer-update.test.ts && tsx src/modules/mcp/ipsec-peer-update-actions.test.ts && tsx src/services/ipsec-user-update-model.test.ts && tsx src/modules/mcp/ipsec-user-update-actions.test.ts && tsx src/services/ipsec-server-delete-model.test.ts && tsx src/modules/mcp/ipsec-server-delete-actions.test.ts && tsx src/services/ipsec-proof-telemetry.test.ts && tsx src/services/ipsec-user-create-model.test.ts",
"test:live-maps": "tsx src/services/gre-revision-restore.test.ts && tsx src/services/gre-native-mutation.test.ts && tsx src/services/gre-mutation.test.ts && tsx src/services/filter-rules-observed.test.ts && tsx src/services/firewall-revision-restore.test.ts && tsx src/services/firewall-address-write.test.ts && tsx src/services/firewall-rule-write.test.ts && tsx src/services/gre-observed-read.test.ts && tsx src/services/network-observed-read.test.ts && tsx src/services/firewall-rule-move.test.ts && tsx src/services/ospf-state-read.test.ts && tsx src/modules/mcp/readiness-http.test.ts && tsx src/services/probe-interface-model.test.ts && tsx src/services/wan-runtime-model.test.ts && tsx src/services/gre-keepalive.test.ts && tsx src/services/gre-read.test.ts && tsx src/services/ospf-route-parse.test.ts && tsx src/services/vxlan-live.test.ts && tsx src/routes/vxlan.test.ts && tsx src/services/containers-live.test.ts && tsx src/services/firewall-poll.test.ts && tsx src/services/gre-catalog-poll.test.ts && tsx src/routes/filters-gre-catalog.test.ts && tsx src/routes/bgp-catalog.test.ts && tsx src/services/bgp-catalog-parse.test.ts && tsx src/routes/ospf-catalog.test.ts && tsx src/services/ospf-observed-values.test.ts && tsx src/routes/ospf-legacy.test.ts",
"test": "node scripts/test.mjs",
"test:ix": "tsx --test src/services/internet-exchange-plan.test.ts src/services/internet-exchange-execution.test.ts src/services/internet-exchange-bonds.test.ts src/services/ix-bond-transport.test.ts",
"test:ix": "tsx --test src/services/internet-exchange-plan.test.ts src/services/internet-exchange-execution.test.ts src/services/internet-exchange-bonds.test.ts src/services/ix-bond-transport.test.ts src/services/ix-import-links.test.ts",
"test:evolution": "tsx src/services/evobgp-catalog.test.ts && tsx src/services/evobgp-client.test.ts && tsx src/routes/evobgp-catalog.test.ts && tsx src/routes/evobgp-settings.test.ts && tsx src/plugins/auth.evolution-settings.test.ts",
"test:netflow-purge": "tsx src/db/operation-lock.test.ts && tsx src/services/traffic-flow-purge-execution.test.ts && tsx src/services/flow-purge-partitions.test.ts && tsx --test src/services/traffic-flow-worker-lifecycle.test.ts && tsx src/routes/traffic-flow-purge.test.ts",
"test:netflow-settings": "tsx src/services/traffic-flow-host-file-builders.test.ts && tsx src/services/traffic-flow-key-execution.test.ts && tsx src/routes/traffic-flow-settings.test.ts && tsx src/plugins/auth.netflow-settings.test.ts && tsx src/services/traffic-flow-agent-install.test.ts && tsx src/services/traffic-flow-agent-client.test.ts && tsx src/services/traffic-flow-operation-queue.test.ts && tsx src/routes/traffic-flow-host.test.ts && tsx src/services/traffic-flow-settings-execution.test.ts && tsx src/modules/mcp/flow-host-keys-actions.test.ts && tsx src/services/traffic-flow-lifecycle-fence.test.ts && tsx src/services/traffic-flow-settings-store.test.ts && tsx src/services/traffic-flow-settings-service.test.ts && tsx src/modules/mcp/flow-settings-actions.test.ts",
+1
View File
@@ -9,6 +9,7 @@ assert.equal(new Set(coverage.routes.map(routeKey)).size, coverage.routes.length
assert.deepEqual(coverage.routes.map(routeKey).sort(), actual.map(routeKey).sort(), "REST routes changed: update mcp-coverage.json with a typed tool, human-only reason, or explicit pending adapter")
const implemented = new Set(listActions().map(action => action.operation.id))
const ixInterfaceRoutes = new Set([
"POST /api/ix/import",
"GET /api/ix/linux-bonds",
"POST /api/ix/segments/:id/linux-bonds",
"DELETE /api/ix/segments/:id/linux-bonds/:bondId",
+1 -1
View File
@@ -49,7 +49,7 @@ export function registerFlowMapActions(register: typeof add) {
await authorize()
const output = { serverId: server.id, userId: input.userId ?? null, interface: input.interface ?? null, map: projected, pages, sourceWindow,
readStartedAt: startedAt, observedAt: new Date().toISOString(), live: false, listenerBound,
source: "retained flow_buckets plus pending for paths; interfaceTraffic includes private routed traffic in closed minutes before top-N",
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",
topRowsPerBucketLimit: Math.max(20, limits.topN), rowLimit: 20000, incomplete: true, graphComplete: false,
referencedNodesMayBeOutsidePage: true, inferredPathsVerified: false, forwardingVerified: false, coverageVerified: false,
rowSumIsNetworkTotal: false, historicalOwnershipVerified: false,
+13 -2
View File
@@ -85,6 +85,17 @@ const firewall = {
"src-address-list": text.optional(), "dst-address-list": text.optional(), "connection-state": text.optional(),
comment: text.optional(), disabled: bool.optional(), log: bool.optional(), "log-prefix": text.optional(),
}
const ipv4Mangle = {
...firewall,
"tcp-flags": z.string().regex(/^!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)(?:,!?(?:ack|cwr|ece|fin|psh|rst|syn|urg)){0,7}$/)
.refine(value => new Set(value.replaceAll("!", "").split(",")).size === value.split(",").length, "Флаги TCP не должны повторяться").optional(),
"tcp-mss": z.string().regex(/^(?:0|[1-9]\d{0,4})(?:-(?:0|[1-9]\d{0,4}))?$/).refine(value => {
const [min, max = min] = value.split("-").map(Number)
return min <= max && max <= 65535
}, "Требуется значение или диапазон TCP MSS от 0 до 65535").optional(),
"new-mss": integer(1, 65535).optional(),
passthrough: bool.optional(),
}
const route = {
"dst-address": name.optional(), gateway: name.optional(), distance: integer(1, 255).optional(), scope: integer(0, 255).optional(),
"target-scope": integer(0, 255).optional(), "routing-table": name.optional(), "check-gateway": z.enum(["none", "ping", "arp", "bfd"]).optional(),
@@ -112,7 +123,7 @@ export const rosResources: RosResourceSpec[] = [
{ id: "vrf", path: "/ip/vrf", title: "VRF", permission: "mm:network", fields: z.object({ name: name.optional(), interfaces: text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name", "interfaces"] },
{ id: "ip_settings", path: "/ip/settings", title: "RPF и IPv4 hash-policy", permission: "mm:network", fields: z.object({ "rp-filter": z.enum(["no", "loose", "strict"]).optional(), "ipv4-multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
{ id: "ipv6_settings", path: "/ipv6/settings", title: "IPv6 hash-policy", permission: "mm:network", fields: z.object({ "multipath-hash-policy": z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), create: false, remove: false },
...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))),
...(["ip", "ipv6"] as const).flatMap(family => (["filter", "nat", "mangle", "raw"] as const).map(table => ({ id: `${family}_${table}`, path: `/${family}/firewall/${table}`, title: `${family} firewall ${table}`, permission: "mm:network", fields: z.object(family === "ip" && table === "mangle" ? ipv4Mangle : firewall).strict(), create: true, remove: true, requiredOnCreate: ["chain", "action"] }))),
{ id: "gre", path: "/interface/gre", title: "GRE", permission: "mm:network", fields: greNativeFieldsSchema, create: true, remove: true, requiredOnCreate: ["name", "remote-address"] },
{ id: "wireguard", path: "/interface/wireguard", title: "WireGuard", permission: "mm:network", fields: z.object({ ...common, "listen-port": integer(1, 65535).optional(), mtu: integer(68, 65535).optional() }).strict(), create: true, remove: true, requiredOnCreate: ["name"] },
{ id: "wireguard_peer", path: "/interface/wireguard/peers", title: "WireGuard peers", permission: "mm:network", fields: z.object({ interface: name.optional(), "public-key": name.optional(), "allowed-address": text.optional(), "endpoint-address": text.optional(), "endpoint-port": integer(0, 65535).optional(), "persistent-keepalive": text.optional(), disabled: bool.optional(), comment: text.optional() }).strict(), create: true, remove: true, requiredOnCreate: ["interface", "public-key", "allowed-address"] },
@@ -154,7 +165,7 @@ export function supportsRosPlacement(step: Pick<RosStep, "resource" | "action" |
export const ROS_SNAPSHOT_VERSION = 3
// OSPF cost plans and archived inverses issued before prefix-list evidence cannot be reused.
export const isSingletonRosResource = (resource: string) => ["ip_settings", "ipv6_settings", "ipv6_nd_settings"].includes(resource)
export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION
export const rosSnapshotVersion = (resource: string): number => resource === "ospf_template" ? 10 : resource === "bfd_configuration" ? 7 : ["bridge", "bridge_port", "bridge_vlan", "routing_table", "ip_settings", "ipv6_settings", "ospf_instance", "ipv6_nd", "ip_mangle"].includes(resource) ? 4 : ROS_SNAPSHOT_VERSION
export interface RosSnapshot { serverId: number; resource: string; rows: ConfigurationRow[]; fingerprint: string; projectionVersion?: number; sourceProof?: string }
const firewallAddressListResources = ["ip_address_list", "ipv6_address_list"]
const routingPolicyResources = new Set(["routing_rule", "routing_filter", "routing_filter_select", "bfd_configuration", ...firewallAddressListResources, "ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw"])
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
import { configurationRows, isOrderedRosResource, resourceById, rosSnapshotVersion, splitOspfUnsetUpdate, validateRosStep, type ConfigurationRow, type RosSnapshot, type RosStep } from "./resources.js"
import { fingerprint } from "./security.js"
import { proveRosDriftExpectation, verifyRosStepSnapshots } from "./ros-step-verification.js"
import { readOspfTemplateFlags } from "../../services/ospf-template-flags.js"
@@ -24,6 +24,26 @@ assert.equal(check(create, ack, [a, b], [a, b, { ...c, action: "drop" }]), false
assert.equal(check(create, undefined, [a], [a, c]), false, "Observed object never substitutes a lost acknowledgement")
assert.equal(check({ ...create, id: "*A" }, ack, [a], [a, c]), false)
const mangle = resourceById("ip_mangle")
const mssFields = {
chain: "forward", "out-interface": "gre-ix", "dst-address": "192.0.2.2/32", protocol: "tcp",
"tcp-flags": "syn,ack", "tcp-mss": "1381-65535", action: "change-mss", "new-mss": 1380, passthrough: true,
}
const mss = { ...create, resource: mangle.id, fields: validateRosStep(mangle, "create", mssFields) }
const liveMss = { ...mss.fields, ".id": "*C", "dst-address": "192.0.2.2", "tcp-flags": "ack,syn", passthrough: "yes", packets: "3" }
const mangleRows = (rows: ConfigurationRow[]) => configurationRows(mangle, rows)
assert.equal(check(mss, ack, [], mangleRows([liveMss])), true)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "new-mss": "1460" }])), false)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "dst-address": "192.0.2.2/24" }])), false)
assert.equal(check(mss, ack, [], mangleRows([{ ...liveMss, "tcp-flags": "syn,!ack" }])), false)
const mssUpdate = { ...mss, action: "update" as const, id: "*C", fields: validateRosStep(mangle, "update", { "new-mss": 1360 }, "*C") }
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360" }])), true)
assert.equal(check(mssUpdate, {}, mangleRows([liveMss]), mangleRows([{ ...liveMss, "new-mss": "1360", "tcp-mss": "1361-65535" }])), false)
for (const bad of [{ "new-mss": 65536 }, { "tcp-mss": "1400-1300" }, { "tcp-mss": "1-65536" }, { "tcp-flags": "syn,!syn" }, { passthrough: "yes" }]) {
assert.throws(() => validateRosStep(mangle, "create", { ...mssFields, ...bad }))
}
assert.equal(resourceById("ip_filter").fields.safeParse(mssFields).success, false)
const update: RosStep = { ...create, action: "update", id: "*A", fields: { action: "accept" } }
const updated = { ...a, action: "accept" }
assert.equal(check(update, {}, [a, b], [updated, b]), true)
@@ -29,6 +29,10 @@ function requested(resource: RosResourceSpec, fields: RosStep["fields"], row: Co
if (resource.id === "bridge_vlan" && ["vlan-ids", "tagged", "untagged"].includes(key)) {
try { return canonicalBridgeVlanValue(key, row[key]) === canonicalBridgeVlanValue(key, value) } catch { return false }
}
if (resource.id === "ip_mangle") {
if (key === "dst-address" || key === "src-address") return String(row[key]).replace(/\/32$/, "") === value.replace(/\/32$/, "")
if (key === "tcp-flags" && schema.safeParse(row[key]).success) return String(row[key]).split(",").sort().join(",") === value.split(",").sort().join(",")
}
return String(row[key]) === value
})
}
+2 -1
View File
@@ -276,7 +276,8 @@ export async function requireAuth(
/** Gate the matched route, including encoded static segments in the raw URL. */
export async function requireApiAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> {
const pathname = request.routeOptions.url ?? request.url.split("?")[0] ?? request.url
if (!pathname.startsWith("/api/") || pathname === "/api/auth/config") return
if (!pathname.startsWith("/api/") || pathname === "/api/auth/config" ||
request.method === "POST" && pathname === "/api/ix/import") return
await requireAuth(request, reply)
}
+63 -7
View File
@@ -5,7 +5,9 @@ import { ixBondEditSchema, ixChangeSchema, ixLinuxClientRequest, ixTransitReques
import { fingerprint, McpError } from "../modules/mcp/security.js"
import { audit } from "../modules/mcp/store.js"
import { pool } from "../db/index.js"
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError } from "../plugins/auth.js"
import { captureVerifiedRestRequest, inspectVerifiedRestRequest, RestRequestProvenanceError, type VerifiedRestRequestAuthority } from "../plugins/auth.js"
import { assertPortalClaimsCurrent } from "../modules/mcp/portal-revocation.js"
import { createIxImportLinks } from "../services/ix-import-links.js"
import { withApplicationCollectorLock, withApplicationMutationLock } from "../services/config-mutation-lock.js"
import { withConfigurationActor } from "../services/config-mutation-policy.js"
import { applyIxChange, assignIxRouterIds, configureIxLinuxClient, configureIxTransit, listIxLinuxClients, observeIxLinuxPath, observeIxSegment, prepareIxChange, prepareIxRemoval, readIxLinuxClient, readIxNodeInventory, removeIxSegment } from "../services/internet-exchange-execution.js"
@@ -49,7 +51,23 @@ function summarizeTasks(tasks: Awaited<ReturnType<typeof prepareIxChange>>["nati
}))
}
const importLinkLifetime = 5 * 60_000
function importLinkOwner(authority: VerifiedRestRequestAuthority) {
const { ownerId, issuedAt, authentication, expiresAt } = authority
return async () => {
if (Date.now() >= expiresAt) throw new IxConflict("Ссылка истекла", 410)
if (authentication === "jwt") await assertPortalClaimsCurrent({ id: ownerId, issuedAt })
}
}
const ixRoutes: FastifyPluginAsync = async app => {
const links = createIxImportLinks()
app.post("/ix/import", { bodyLimit: 256 }, async (request, reply) => {
reply.header("Cache-Control", "private, no-store")
const { code } = z.object({ code: z.string().regex(/^[A-Za-z0-9_-]{32}$/) }).strict().parse(request.body)
return links.redeem(code)
})
app.setErrorHandler((error, request, reply) => {
if (error instanceof z.ZodError) return reply.code(400).send({ error: "Некорректные параметры IX", details: error.issues })
if (error instanceof IxConflict) return reply.code(error.statusCode).send({ error: error.message })
@@ -81,11 +99,25 @@ const ixRoutes: FastifyPluginAsync = async app => {
})
app.post("/ix/segments/:id/linux-bonds/:bondId/export", async (request, reply) => {
const { id, bondId } = segmentParams.extend({ bondId: z.uuid() }).parse(request.params)
const { revision } = planRequest.parse(request.body)
const scope = { deadlineAt: Date.now() + 90_000 }
const { revision, importLink } = planRequest.extend({ importLink: z.boolean().optional() }).parse(request.body)
const scope = { deadlineAt: Date.now() + (importLink ? importLinkLifetime : 90_000) }
const token = await captureVerifiedRestRequest(request, scope)
const authorize = () => inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = await authorize()
const authority = await authorize()
const { ownerId } = authority
if (importLink) {
const authorizeOwner = importLinkOwner(authority)
await audit(pool, ownerId, "ix.bond.import_link_issued", null, { segmentId: id, bondId, revision })
await authorize()
reply.header("Cache-Control", "private, no-store")
return { code: links.issue(authority.monotonicDeadline, () => withApplicationCollectorLock(async () => {
await authorizeOwner()
const bond = await exportIxBond(id, bondId, revision, authorizeOwner)
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
await authorizeOwner()
return { version: 1, kind: "bond", bond }
})) }
}
return withApplicationCollectorLock(async () => {
const bundle = await exportIxBond(id, bondId, revision, authorize)
await audit(pool, ownerId, "ix.bond.exported", null, { segmentId: id, bondId, revision })
@@ -158,12 +190,36 @@ const ixRoutes: FastifyPluginAsync = async app => {
})
app.post("/ix/segments/:id/linux/credential", async (request, reply) => {
const { id } = segmentParams.parse(request.params)
const { serverId, interfaceName, transportOnly } = clientKey.extend({ transportOnly: z.boolean().optional() }).parse(request.body)
const scope = { deadlineAt: Date.now() + 60_000 }
const { serverId, interfaceName, transportOnly, importLink } = clientKey.extend({
transportOnly: z.boolean().optional(), importLink: z.boolean().optional(),
}).parse(request.body)
const scope = { deadlineAt: Date.now() + (importLink ? importLinkLifetime : 60_000) }
const token = await captureVerifiedRestRequest(request, scope)
const { ownerId } = await inspectVerifiedRestRequest(token, scope, "mm:network:write")
const authority = await inspectVerifiedRestRequest(token, scope, "mm:network:write")
const { ownerId } = authority
const segment = await readIxSegment(id)
if (!segment) throw new IxConflict("Сегмент IX не найден", 404)
if (importLink) {
const revision = segment.appliedRevision
if (revision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
const authorizeOwner = importLinkOwner(authority)
await audit(pool, ownerId, "ix.linux.import_link_issued", null, { segmentId: id, serverId, interfaceName, revision })
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
reply.header("Cache-Control", "private, no-store")
return { code: links.issue(authority.monotonicDeadline, async () => {
await authorizeOwner()
const current = await readIxSegment(id)
if (!current || current.appliedRevision !== revision) throw new IxConflict("Ревизия IX изменилась; получите новую ссылку", 410)
const access = await readIxLinuxClient(current, serverId, interfaceName, true, true, true)
if ((await readIxSegment(id))?.appliedRevision !== revision) throw new IxConflict("Ревизия IX изменилась; получите новую ссылку", 410)
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision })
await authorizeOwner()
const name = access.filename.replace(/\.conf$/, "")
if (access.kind === "wireguard") return { version: 1, kind: "wireguard", name, config: access.template }
if (!access.greImport) throw new IxConflict("Нет параметров управляемого GRE/IPsec")
return { version: 1, kind: "gre-ipsec", name, gre: access.greImport }
}) }
}
const access = await readIxLinuxClient(segment, serverId, interfaceName, true, transportOnly)
await inspectVerifiedRestRequest(token, scope, "mm:network:write")
await audit(pool, ownerId, "ix.linux.credential_exported", null, { segmentId: id, serverId, interfaceName, revision: access.revision })
+20 -1
View File
@@ -80,10 +80,29 @@ export async function withApplicationMutationLock<T>(work: () => Promise<T>, opt
/** Collectors coexist with each other but exclude configuration mutation for
* the complete native/sample/status operation. This lock grants no authority.
* Verified operations retain their original exact exclusive client protocol. */
export async function withApplicationCollectorLock<T>(work: () => Promise<T>): Promise<T> {
export async function withApplicationCollectorLock<T>(work: () => Promise<T>, { waitMs = 5000 }: { waitMs?: number } = {}): Promise<T> {
assertOperationConfigurationLockScope()
if (applicationLease.getStore()?.active || captureOperationConfigurationLockHandoff()) return withApplicationMutationLock(work)
if (collectorLease.getStore()?.active) return work()
const deadline = performance.now() + waitMs
for (;;) {
let admitted = false
try {
return await tryApplicationCollectorLock(() => {
admitted = true
return work()
})
} catch (error) {
const remaining = deadline - performance.now()
if (admitted || !(error instanceof ConfigurationBusyError) || remaining <= 0) throw error
// Release the failed attempt's connection before waiting for the writer.
await delay(Math.min(250, remaining))
if (performance.now() >= deadline) throw error
}
}
}
async function tryApplicationCollectorLock<T>(work: () => Promise<T>): Promise<T> {
let complete!: () => void
const completed = new Promise<void>(resolve => { complete = resolve })
const client = await pool.connect(), context = { active: true, completed }
@@ -870,7 +870,7 @@ export async function observeIxLinuxPath(segment: IxSegment, serverId: number, n
})) }
}
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false, transportOnly = false): Promise<IxLinuxAccess> {
export async function readIxLinuxClient(segment: IxSegment, serverId: number, name: string, includeCredential: boolean | "wireguard" = false, transportOnly = false, forImportLink = false): Promise<IxLinuxAccess & { greImport?: import("./ix-import-links.js").IxImportGre }> {
if (segment.appliedRevision === null) throw new IxConflict("Сначала примените конфигурацию площадки")
const configuration = await readIxRevision(segment.id, segment.appliedRevision)
const site = configuration.sites.find(site => site.serverId === serverId)
@@ -902,7 +902,15 @@ export async function readIxLinuxClient(segment: IxSegment, serverId: number, na
throw new IxConflict("Действующий PSK не совпал с применённой ревизией. Выполните сверку")
}
}
return { ...clientInfo, kind: "gre-ipsec", ...ixGreClientTemplate(binding, serverId, peer, credential, transportOnly) }
const access = ixGreClientTemplate(binding, serverId, peer, credential, transportOnly)
if (forImportLink && (!credential || !binding.provisionGre || !binding.endpoint || !binding.localEndpoint)) {
throw new IxConflict("Для импорта по ссылке нужен управляемый GRE/IPsec")
}
return { ...clientInfo, kind: "gre-ipsec", ...access,
...(forImportLink && credential && binding.provisionGre && binding.endpoint && binding.localEndpoint && {
greImport: { local: binding.endpoint, remote: binding.localEndpoint, address: binding.provisionGre.peerAddress, psk: credential },
}),
}
}
if (ixLinuxBindingKind(binding) !== "wireguard") throw new IxConflict("Нет параметров WireGuard для Linux")
const wireguard = await readRows(client, "/interface/wireguard", ["name", "public-key", "listen-port", "comment", "disabled"])
@@ -0,0 +1,26 @@
import assert from "node:assert/strict"
import { test } from "node:test"
import { createIxImportLinks, type IxImportBundle } from "./ix-import-links.js"
const bundle: IxImportBundle = { version: 1, kind: "wireguard", name: "ixw000000000000", config: "fixture" }
test("only one concurrent request can claim a link", async () => {
const links = createIxImportLinks(() => 10)
let reads = 0
const code = links.issue(20, async () => { reads++; return bundle })
assert.match(code, /^[A-Za-z0-9_-]{32}$/)
const responses = await Promise.allSettled([links.redeem(code), links.redeem(code)])
assert.deepEqual(responses[0], { status: "fulfilled", value: bundle })
assert.equal(responses[1].status, "rejected")
assert.equal(reads, 1)
})
test("expiry is enforced before and after loading the bundle", async () => {
let now = 10
const links = createIxImportLinks(() => now)
const expired = links.issue(20, async () => { assert.fail("expired link read its source") })
const tooSlow = links.issue(30, async () => { now = 31; return bundle })
now = 20
await assert.rejects(links.redeem(expired), /истекла/)
await assert.rejects(links.redeem(tooSlow), /истекла/)
})
+39
View File
@@ -0,0 +1,39 @@
import { createHash, randomBytes } from "node:crypto"
import { performance } from "node:perf_hooks"
import type { IxBondBundle } from "@mmapp/contracts/internet-exchange"
import { IxConflict } from "./internet-exchange-plan.js"
export type IxImportGre = { local: string; remote: string; address: string; psk: string }
export type IxImportBundle =
| { version: 1; kind: "wireguard"; name: string; config: string }
| { version: 1; kind: "gre-ipsec"; name: string; gre: IxImportGre }
| { version: 1; kind: "bond"; bond: IxBondBundle }
const digest = (code: string) => createHash("sha256").update(code).digest("hex")
const maxLinks = 256
const expired = () => new IxConflict("Ссылка истекла или уже использована", 410)
export function createIxImportLinks(now = () => performance.now()) {
const links = new Map<string, { deadline: number; load: () => Promise<IxImportBundle> }>()
return {
issue(deadline: number, load: () => Promise<IxImportBundle>) {
const current = now()
for (const [key, entry] of links) if (entry.deadline <= current) links.delete(key)
if (deadline <= current) throw expired()
if (links.size >= maxLinks) throw new IxConflict("Слишком много активных ссылок импорта", 429)
const code = randomBytes(24).toString("base64url")
// shortcut: pending links live in this backend process, use shared storage if the backend is replicated.
links.set(digest(code), { deadline, load })
return code
},
async redeem(code: string) {
const key = digest(code), entry = links.get(key)
links.delete(key)
if (!entry || entry.deadline <= now()) throw expired()
const bundle = await entry.load()
if (entry.deadline <= now()) throw expired()
return bundle
},
}
}
@@ -100,6 +100,27 @@ export async function checkCatalogReadContention(serverId: number) {
const load = () => Promise.all([readFilterRulesCatalog([server], { source: "live", persistObserved: true }),
readRecursiveCatalogForServer(server), readRecursiveRoutesForServer(server)])
try {
const jobs = ["uptime_resources", "uptime_ping"]
const startedAt = new Date().toISOString()
const pending = await withApplicationMutationLock(async () => {
const runs = independent.runInAsyncScope(() => Promise.all(jobs.map(runSchedulerJobNow)))
const state = await Promise.race([runs.then(() => "finished", () => "failed"), delay(600, "waiting")])
assert.equal(state, "waiting", "Scheduler must wait for a transient exclusive lock")
await independent.runInAsyncScope(() => assert.rejects(
withApplicationCollectorLock(async () => assert.fail("Collector entered during a write"), { waitMs: 50 }),
ConfigurationBusyError,
))
return { runs }
})
assert.deepEqual((await pending.runs).map(run => run.status), ["ok", "ok"])
const { rows } = await pool.query("SELECT job_key,status FROM scheduler_runs WHERE started_at >= $1 AND job_key=ANY($2::text[]) ORDER BY job_key", [startedAt, jobs])
assert.deepEqual(rows, [{ job_key: "uptime_ping", status: "ok" }, { job_key: "uptime_resources", status: "ok" }])
let executions = 0
await assert.rejects(withApplicationCollectorLock(async () => {
executions++
throw new ConfigurationBusyError("server")
}), ConfigurationBusyError)
assert.equal(executions, 1, "An admitted collector must never be replayed")
const cold = await Promise.all(Array.from({ length: 24 }, load))
assert(cold.every(([filters, catalog, routes]) => filters[0].live && catalog.live && routes.live))
const revisions = () => pool.query("SELECT section,source FROM config_revisions WHERE server_id=$1 ORDER BY section,created_at", [server.id])
@@ -78,7 +78,7 @@ export async function readCatalogWithObservedCache<T extends { current: boolean
let done!: () => void
catalogRefreshes.set(serverId, new Promise(resolve => { done = resolve }))
try {
return await enterCatalogLock(work => withApplicationCollectorLock(() => withConfigMutationLock([serverId], work)), async () => {
return await enterCatalogLock(work => withApplicationCollectorLock(() => withConfigMutationLock([serverId], work), { waitMs: 0 }), async () => {
await assertCatalogSource(server)
const latest = await read(true)
return latest.current ? latest : save(latest)
+7 -6
View File
@@ -476,8 +476,9 @@ export function queueParsedFlows(serverId: number, flows: ParsedFlowInput[]): vo
if (prev) {
prev.bytes += flow.bytes
prev.packets += flow.packets
if (flow.outIface && !prev.flow.outIface) prev.flow.outIface = flow.outIface
if (flow.nextHop && !prev.flow.nextHop) prev.flow.nextHop = flow.nextHop
// This tuple is keyed by ingress. Only retain egress metadata shared by all its bytes.
if (prev.flow.outIface !== flow.outIface) prev.flow.outIface = ""
if (prev.flow.nextHop !== flow.nextHop) prev.flow.nextHop = ""
if (flow.natSrc && !prev.flow.natSrc) prev.flow.natSrc = flow.natSrc
if (flow.natDst && !prev.flow.natDst) prev.flow.natDst = flow.natDst
if (flow.natSrcPort && !prev.flow.natSrcPort) prev.flow.natSrcPort = flow.natSrcPort
@@ -554,8 +555,8 @@ function mergeInto(map: Map<string, PendingFlowRow>, row: PendingFlowRow): void
if (prev) {
prev.bytes += row.bytes
prev.packets += row.packets
if (row.outIface && !prev.outIface) prev.outIface = row.outIface
if (row.nextHop && !prev.nextHop) prev.nextHop = row.nextHop
if (prev.outIface !== row.outIface) prev.outIface = ""
if (prev.nextHop !== row.nextHop) prev.nextHop = ""
if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc
if (row.natDst && !prev.natDst) prev.natDst = row.natDst
if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort
@@ -964,8 +965,8 @@ async function upsertFlowBucketsBatch(rows: PendingFlowRow[]): Promise<void> {
DO UPDATE SET
bytes = flow_buckets.bytes + excluded.bytes,
packets = flow_buckets.packets + excluded.packets,
out_iface = CASE WHEN excluded.out_iface != '' THEN excluded.out_iface ELSE flow_buckets.out_iface END,
next_hop = COALESCE(excluded.next_hop, flow_buckets.next_hop),
out_iface = CASE WHEN flow_buckets.out_iface = excluded.out_iface THEN excluded.out_iface ELSE '' END,
next_hop = CASE WHEN flow_buckets.next_hop = excluded.next_hop THEN excluded.next_hop END,
flow_start_ms = CASE
WHEN excluded.flow_start_ms > 0 AND (flow_buckets.flow_start_ms = 0 OR excluded.flow_start_ms < flow_buckets.flow_start_ms)
THEN excluded.flow_start_ms ELSE flow_buckets.flow_start_ms END,
+2 -2
View File
@@ -429,8 +429,8 @@ function mergeInto(map: Map<string, PendingFlowRow>, row: PendingFlowRow): void
if (prev) {
prev.bytes += row.bytes
prev.packets += row.packets
if (row.outIface && !prev.outIface) prev.outIface = row.outIface
if (row.nextHop && !prev.nextHop) prev.nextHop = row.nextHop
if (prev.outIface !== row.outIface) prev.outIface = ""
if (prev.nextHop !== row.nextHop) prev.nextHop = ""
if (row.natSrc && !prev.natSrc) prev.natSrc = row.natSrc
if (row.natDst && !prev.natDst) prev.natDst = row.natDst
if (row.natSrcPort && !prev.natSrcPort) prev.natSrcPort = row.natSrcPort
@@ -102,6 +102,20 @@ disableRipePersistForTests()
resetRipeCacheForTests()
disableRipeEnqueueForTests()
const bucket = Math.floor(Date.now() / 60000) * 60000 - 60000
function ingestClosed(serverId: number, flows: Parameters<typeof ingestParsedFlowsForServerForTests>[1], at = bucket) {
const clock = mock.method(Date, "now", () => at)
try { ingestParsedFlowsForServerForTests(serverId, flows) } finally { clock.mock.restore() }
}
const { rows: [snapshot] } = await dbQuery<{id: number}>(`
INSERT INTO internet_path_snapshots(sampled_at,payload_json) VALUES (?,?::jsonb) RETURNING id
`, [new Date(bucket).toISOString(), JSON.stringify({ collectionComplete: true, greTunnels: [
{serverId: "7", name: "gre-jh-en", remoteAddress: "198.51.100.1", enabled: true},
{serverId: "7", name: "SWE-VEESP", remoteAddress: "198.51.100.1", enabled: true},
{serverId: "7", name: "gre-second", remoteAddress: "198.51.100.2", enabled: true},
] })])
const topo: FlowTopology = {
clientIfaces: new Map([[7, new Set(["gre-client"])]]),
clientByIface: new Map([["7|gre-client", {
@@ -134,7 +148,7 @@ rememberServerIfaces(3, [
{ ".id": "*1", name: "ether1-rt" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
{
src: "10.100.1.17",
dst: "8.8.8.8",
@@ -181,7 +195,7 @@ ingestParsedFlowsForServerForTests(7, [
outIface: "",
},
])
ingestParsedFlowsForServerForTests(3, [
ingestClosed(3, [
{
src: "192.168.1.10",
dst: "8.8.4.4",
@@ -292,7 +306,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 600),
payloadFlow("11.0.113.50", 9400),
])
@@ -324,7 +338,7 @@ try {
assert.ok(usPath)
assert.equal(usPath.clientName, "Alice")
ingestParsedFlowsForServerForTests(7, [{ ...payloadFlow("8.8.8.8", 2000), proto: 17, dstPort: 51820 }])
ingestClosed(7, [{ ...payloadFlow("8.8.8.8", 2000), proto: 17, dstPort: 51820 }])
const mixedPeer = await buildFlowMapHops({ minutes: 5, serverId: 7, excludeOverlay: false })
assert.equal(mixedPeer.totalBytes, 12_000)
assert.equal(mixedPeer.namedBytes, 600, "WireGuard to the same peer is separate from the HTTPS service")
@@ -344,7 +358,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 400),
payloadFlow("11.0.113.50", 9600),
])
@@ -378,7 +392,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 400),
payloadFlow("104.18.35.51", 400),
payloadFlow("11.0.113.50", 9200),
@@ -411,7 +425,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
seedRipeAsn("162.254.192.71", 32590, "VALVE-CORP")
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("162.254.192.71", 2000),
])
try {
@@ -433,7 +447,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("64.233.161.1", 10_000),
payloadFlow("11.0.113.50", 20_000),
])
@@ -484,7 +498,7 @@ rememberServerIfaces(7, [
])
googleRipe()
for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder)
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 5000),
...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)),
])
@@ -512,7 +526,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
{
src: "203.0.113.10",
dst: "198.51.100.1",
@@ -548,7 +562,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
{
src: "10.100.1.17",
dst: "8.8.8.8",
@@ -613,7 +627,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
{
src: "173.194.151.65",
dst: "10.200.100.53",
@@ -622,9 +636,9 @@ ingestParsedFlowsForServerForTests(7, [
dstPort: 57182,
bytes: 9_000,
packets: 90,
inIface: "2",
outIface: "3",
nextHop: "198.51.100.1",
inIface: "3",
outIface: "2",
nextHop: "",
},
{
src: "104.18.35.51",
@@ -634,9 +648,9 @@ ingestParsedFlowsForServerForTests(7, [
dstPort: 53880,
bytes: 1_000,
packets: 10,
inIface: "2",
outIface: "3",
nextHop: "198.51.100.1",
inIface: "3",
outIface: "2",
nextHop: "",
},
])
try {
@@ -663,7 +677,7 @@ rememberServerIfaces(7, [
{ ".id": "*2", name: "gre-client" },
{ ".id": "*3", name: "gre-jh-en" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 500),
{
src: "173.194.151.65",
@@ -701,9 +715,9 @@ resetRipeCacheForTests()
disableRipeEnqueueForTests()
seedFlowTopologyForTests(topo)
rememberServerIfaces(7, [
{ ".id": "*1", name: "SWE-VEESP" },
{ ".id": "*1", name: "ether1" },
])
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
{
src: "173.194.151.65",
dst: "10.200.100.53",
@@ -720,16 +734,12 @@ ingestParsedFlowsForServerForTests(7, [
try {
resetFlowMapHopsCacheForTests()
const wanOnly = await buildFlowMapHops({ minutes: 5, minSharePct: 0 })
const googleEdge = wanOnly.serviceEdges?.find((e) => e.toId === "svc:youtube")
assert.ok(googleEdge, "YouTube WAN без GRE payload")
assert.equal(googleEdge.fromId, "9", "единственный EN, даже без nextHop")
assert.ok(googleEdge.bps > 0, "скорость на hop EN→сервис")
assert.ok(!(wanOnly.serviceEdges ?? []).some((e) => e.fromId === "7"), "нет пунктира с JH")
const googlePath = wanOnly.servicePaths?.find((p) => p.serviceId === "svc:youtube")
assert.ok(googlePath, "путь WAN YouTube")
assert.equal(googlePath.viaId, "7", "via = JH exporter")
assert.equal(googlePath.enId, "9", "якорь EN")
assert.ok(googlePath.bps > 0, "скорость на пути клиента")
assert.equal(wanOnly.services?.find(s => s.id === "svc:youtube")?.bytes, 9000)
assert.deepEqual(wanOnly.serviceEdges, [])
assert.deepEqual(wanOnly.servicePaths, [])
assert.deepEqual(wanOnly.countryEdges, [])
assert.ok(wanOnly.countryServiceGroups?.every(group => !group.edges.length && !group.paths.length))
} finally {
seedFlowTopologyForTests(null)
resetFlowRingsForTests()
@@ -751,8 +761,8 @@ rememberServerIfaces(9, [
{ ".id": "*1", name: "ether1" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [payloadFlow("8.8.8.8", 12_000)])
ingestParsedFlowsForServerForTests(9, [{
ingestClosed(7, [payloadFlow("8.8.8.8", 12_000)])
ingestClosed(9, [{
src: "10.100.1.17",
dst: "8.8.8.8",
proto: 6,
@@ -796,7 +806,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 8_000),
{
src: "8.8.8.8",
@@ -822,6 +832,8 @@ try {
assert.ok(!(bothDir.servicePaths ?? []).some((p) => p.serviceId === "svc:google" && p.clientId === "—"))
const googleEdge = bothDir.serviceEdges?.find((e) => e.toId === "svc:google" && e.fromId === "9")
assert.ok(googleEdge)
assert.equal(googleEdge.bpsFwd, 8000 * 8 / 300)
assert.equal(googleEdge.bpsRev, 4000 * 8 / 300)
assert.equal(googleEdge.bytes, 12_000)
assert.equal(googleEdge.bps, googlePaths[0]?.bps)
} finally {
@@ -852,7 +864,7 @@ seedRipeCacheForTests({
ok: true,
fetchedAt: Date.now(),
})
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 5000),
payloadFlow("185.45.12.10", 5000),
])
@@ -889,7 +901,7 @@ rememberServerIfaces(7, [
{ ".id": "*3", name: "gre-jh-en" },
])
googleRipe()
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 600),
payloadFlow("11.0.113.50", 9400),
])
@@ -942,7 +954,7 @@ seedRipeCacheForTests({
ok: true,
fetchedAt: Date.now(),
})
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 5000),
payloadFlow("185.45.12.10", 5000),
])
@@ -978,7 +990,7 @@ rememberServerIfaces(7, [
])
googleRipe()
for (const b of smallBrands) seedRipeAsn(b.ip, b.asn, b.holder)
ingestParsedFlowsForServerForTests(7, [
ingestClosed(7, [
payloadFlow("8.8.8.8", 5000),
...smallBrands.map((b) => payloadFlow(b.ip, b.bytes)),
])
@@ -1010,6 +1022,27 @@ try {
console.log("traffic-flow-map-hops.test.ts: ok")
// Identical destination/ports on two exits and the local WAN must remain separate.
seedFlowTopologyForTests({ ...topo, enNodes: [...topo.enNodes, {id: 10, name: "FIN", hosts: ["198.51.100.2"]}] })
try {
const flow = { ...payloadFlow("173.194.151.65", 0), nextHop: "", inIface: "gre-client" }
ingestClosed(7, [
{ ...flow, src: "10.0.0.1", bytes: 1000, outIface: "SWE-VEESP" },
{ ...flow, src: "10.0.0.2", bytes: 2000, outIface: "gre-second" },
{ ...flow, src: "10.0.0.3", bytes: 9000, outIface: "ether1" },
])
// This open minute must affect neither the service nor the link rate.
ingestParsedFlowsForServerForTests(7, [{ ...flow, bytes: 90000, outIface: "SWE-VEESP" }])
const map = await buildFlowMapHops({ serverId: 7, minutes: 5, minSharePct: 0 })
assert.equal(map.services?.find(s => s.id === "svc:youtube")?.bytes, 12000)
assert.deepEqual(map.serviceEdges?.map(e => [e.fromId, e.bytes]), [["10", 2000], ["9", 1000]])
assert.equal(map.servicePaths?.reduce((n, p) => n + p.bytes, 0), 3000)
} finally {
await dbQuery("DELETE FROM internet_path_snapshots WHERE id=?", [snapshot.id])
resetFlowRingsForTests()
seedFlowTopologyForTests(null)
}
// Captured on the test CHR. Three 64-byte UDP packets traversed GRE A -> GRE B.
// RouterOS also exported three 88-byte outer GRE packets on GRE B -> underlay.
const datagram = Buffer.from(
@@ -1052,6 +1085,21 @@ try {
assert.deepEqual([b.rxBytes, b.txBytes, b.rxPackets, b.txPackets], [0, 192, 0, 3])
const overlay = await buildFlowMapHops({ serverId: sid, minutes: 5, iface: "gre-b", excludeOverlay: false })
assert.deepEqual(overlay.interfaceTraffic?.map(row => [row.iface, row.rxBytes, row.txBytes]), [["gre-b", 264, 192]])
// One tuple reroutes within a minute, first in memory and then across SQL flushes.
const routed = { ...payloadFlow("173.194.151.65", 1000), inIface: "mixed-lan", outIface: "uplink-a" }
const rerouted = { ...routed, outIface: "uplink-b", nextHop: "198.51.100.2" }
const split = { ...routed, srcPort: 40001 }
ingestClosed(sid, [routed, rerouted, routed, split], bucket - 60000)
await flushEngineNow({ prune: false })
ingestClosed(sid, [{ ...rerouted, srcPort: split.srcPort }], bucket - 60000)
await flushEngineNow({ prune: false })
ingestClosed(sid, [split], bucket - 60000)
const mixed = await buildFlowMapHops({serverId: sid, minutes: 5, iface: "mixed-lan"})
assert.equal(mixed.totalBytes, 6000)
assert.deepEqual(mixed.serviceEdges, [])
await flushEngineNow({ prune: false })
assert.deepEqual((await dbQuery("SELECT out_iface,next_hop FROM flow_buckets WHERE server_id=? AND in_iface='mixed-lan'", [sid])).rows,
[{out_iface: "", next_hop: null}, {out_iface: "", next_hop: null}])
const user = await buildFlowMapHops({serverId: sid, minutes: 5, userId: "no-interface-binding"})
assert.equal(user.interfaceTraffic, undefined)
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")
+109 -95
View File
@@ -10,14 +10,14 @@ import { OTHER_SERVICE, isNamedInternetService, mapCountryNodeId, mapCountryServ
import type { FlowIpMeta } from "./traffic-flow-ripe.js"
import { refreshFlowCatalogInBackground } from "./traffic-flow-classify.js"
import { collapseGreEspRows, dedupFlowRowsAcrossExporters, dedupFlowRowsMaxBytes } from "./traffic-flow-dedup.js"
import { getFlowListenerState, listFlowRowsForWindow } from "./traffic-flow-ingest.js"
import { getFlowListenerState, listStoredFlowRows } from "./traffic-flow-ingest.js"
import { resolveIfaceName } from "./traffic-flow-ifaces.js"
import { classifyFlowPlane, shouldKeepPlane } from "./traffic-flow-planes.js"
import { destCtxForIface, flowRateDirection, mapInternetBrand } from "./traffic-flow-dest.js"
import { resolveFlowEndpoints } from "./traffic-flow-ip.js"
import { geoipReadersStatus, resolveFlowIp } from "./traffic-flow-geoip.js"
import { getTrafficFlowSettingsRow } from "./traffic-flow-settings.js"
import { loadFlowTopology, resolveClient, resolveEn, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
import { loadFlowTopology, resolveClient, getServerCatalog, type FlowTopology } from "./traffic-flow-topology.js"
import { flowDataEpoch, FLOW_IFACE_RX_DIM, FLOW_IFACE_TX_DIM } from "./traffic-flow-engine.js"
export const DEFAULT_MAP_SERVICE_MIN_SHARE_PCT = 5
@@ -61,6 +61,9 @@ interface ClientAcc {
}
interface FromAcc {
exporterId: string
enId: string
reverseBytes: number
bytes: number
clients: Map<string, ClientAcc>
}
@@ -111,16 +114,13 @@ function bumpClient(clients: Map<string, ClientAcc>, bytes: number, client: { us
clients.set(id, { name, bytes })
}
function bumpFrom(acc: DstAcc, exporterId: string, bytes: number, client: { userId: string; name: string } | null): void {
const prev = acc.fromBytes.get(exporterId)
if (prev) {
prev.bytes += bytes
bumpClient(prev.clients, bytes, client)
return
}
const clients = new Map<string, ClientAcc>()
bumpClient(clients, bytes, client)
acc.fromBytes.set(exporterId, { bytes, clients })
function bumpFrom(acc: DstAcc, exporterId: string, enId: string, bytes: number, reverse: boolean, client: { userId: string; name: string } | null): void {
const key = exporterId + "|" + enId
const from = acc.fromBytes.get(key) ?? { exporterId, enId, bytes: 0, reverseBytes: 0, clients: new Map<string, ClientAcc>() }
from.bytes += bytes
if (reverse) from.reverseBytes += bytes
bumpClient(from.clients, bytes, client)
acc.fromBytes.set(key, from)
}
let hopsCache: { key: string; at: number; dto: FlowMapHopsDto } | null = null
@@ -180,27 +180,24 @@ function bumpDestFrom(
}
if (prevEdge) {
prevEdge.bytes += from.bytes
prevEdge.bytesFwd += from.bytes
prevEdge.bytesFwd += from.bytes - from.reverseBytes
prevEdge.bytesRev += from.reverseBytes
for (const [id, name] of namedClients) prevEdge.clients.set(id, name)
} else {
edges.set(edgeKey, {
fromId: edgeFromId,
toId,
bytes: from.bytes,
bytesFwd: from.bytes,
bytesRev: 0,
bytesFwd: from.bytes - from.reverseBytes,
bytesRev: from.reverseBytes,
clients: namedClients,
})
}
for (const [clientId, c] of from.clients) {
const pathKey = `${clientId}|${fromId}|${toId}`
const pathKey = `${clientId}|${exporterId}|${fromId}|${toId}`
const prevPath = paths.get(pathKey)
if (prevPath) {
prevPath.bytes += c.bytes
if (exporterId !== fromId && prevPath.viaId === fromId) {
prevPath.viaId = exporterId
prevPath.viaName = viaName
}
if (prevPath.clientName === "—" && c.name !== "—") prevPath.clientName = c.name
} else {
paths.set(pathKey, {
@@ -413,13 +410,12 @@ async function resolveMinSharePct(q: FlowMapHopsQuery): Promise<number> {
}
// Closed minute buckets from every admitted export. Keep an hour of last-seen context for idle links.
async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowMapHopsQuery, now: number): Promise<FlowMapInterfaceTraffic[]> {
async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowMapHopsQuery, end: number): Promise<FlowMapInterfaceTraffic[]> {
if (!serverIds.length) return []
const { minutes } = q
// Private site-to-site flows are traffic on the link even when the destination graph hides mesh paths.
const planes = q.excludeOverlay === false ? ["payload", "client_mesh", "overlay"] : ["payload", "client_mesh"]
const dimensions = planes.flatMap(plane => [FLOW_IFACE_RX_DIM + ":" + plane, FLOW_IFACE_TX_DIM + ":" + plane])
const end = Math.floor(now / 60000) * 60000
const start = new Date(end - minutes * 60000).toISOString()
const rows = await flowReadDbAll<{server_id: number; key: string; dim: string; bytes: string; packets: string; last_at: Date | string}>(`
SELECT server_id, key, dim, COALESCE(SUM(bytes) FILTER (WHERE bucket_at >= ?), 0) AS bytes,
@@ -448,6 +444,38 @@ async function readInterfaceTraffic(serverIds: number[], iface: string, q: FlowM
return [...totals.values()].sort((a,b) => a.serverId.localeCompare(b.serverId) || a.iface.localeCompare(b.iface))
}
// Interface names are local to the exporter; match them against the GRE inventory for the flow minute.
async function readMapGrePeers(rows: { serverId: number; bucketAt: string; inIface: string; outIface: string }[]) {
const peers = new Map<string, Map<string, string>>()
if (!rows.length) return peers
const buckets = new Set<string>(), names = new Set<string>()
for (const row of rows) {
buckets.add(row.bucketAt)
for (const iface of [row.inIface, row.outIface]) names.add(row.serverId + "|" + resolveIfaceName(row.serverId, iface).name)
}
const bindings = await flowReadDbAll<{ bucket: string; key: string; remote: string }>(`
SELECT b.bucket, (t->>'serverId') || '|' || (t->>'name') AS key, t->>'remoteAddress' AS remote
FROM unnest(?::text[]) AS b(bucket)
CROSS JOIN LATERAL (
SELECT payload_json FROM internet_path_snapshots
WHERE sampled_at < b.bucket::timestamptz + interval '1 minute'
AND sampled_at >= b.bucket::timestamptz - interval '15 minutes'
ORDER BY sampled_at DESC, id DESC LIMIT 1
) snapshot
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(payload_json->'greTunnels')='array'
THEN payload_json->'greTunnels' ELSE '[]'::jsonb END) AS t
WHERE payload_json->>'collectionComplete'='true' AND t->>'serverId' ~ '^[1-9][0-9]*$'
AND ((t->>'serverId') || '|' || (t->>'name'))=ANY(?::text[])
AND t->>'enabled'='true' AND t->>'name'<>'' AND t->>'remoteAddress'<>''
`, [[...buckets], [...names]])
for (const row of bindings) {
const interfaces = peers.get(row.bucket) ?? new Map<string, string>()
interfaces.set(row.key, interfaces.has(row.key) ? "" : row.remote.trim().toLowerCase())
peers.set(row.bucket, interfaces)
}
return peers
}
async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number, scope?: ScopedFlowAnalyticsRead): Promise<FlowMapHopsDto> {
const authorize = scope?.authorize ?? (async () => {})
if (!scope) refreshFlowCatalogInBackground()
@@ -455,8 +483,9 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const limits = scope ? await readFlowMapSourceLimits() : undefined
const windowSec = Math.max(60, q.minutes * 60)
await authorize()
const now = Date.now()
const raw = await listFlowRowsForWindow(q.minutes, q.serverId, { ...(scope ? { maxRows: scope.maxRows } : {}), untilIso: new Date(now).toISOString() })
const end = Math.floor(Date.now() / 60000) * 60000
const start = new Date(end - windowSec * 1000).toISOString()
const raw = await listStoredFlowRows(start, q.serverId, { ...(scope ? { maxRows: scope.maxRows } : {}), untilIso: new Date(end - 1).toISOString() })
if (scope && raw.some(row => row.serverId !== q.serverId)) throw new Error("Строка карты вне выбранного сервера")
await authorize()
const catalog = await getServerCatalog(scope?.serverIds)
@@ -510,7 +539,16 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
if (scope) flowCounterSum(working.map(row => row.bytes))
const hops = new Map<string, HopAcc>()
const dstAcc = new Map<string, DstAcc>()
const jhToEn = new Map<number, number>()
const hostIds = new Map<string, number | null>()
for (const node of topo.enNodes) for (const host of node.hosts) {
const key = host.trim().split("/")[0]!.toLowerCase()
if (!key || key === "0.0.0.0" || key === "::") continue
const previous = hostIds.get(key)
hostIds.set(key, previous === undefined || previous === node.id ? node.id : null)
}
await authorize()
const peers = await readMapGrePeers(working)
const observed = new Map<(typeof working)[number], { endpoints: ReturnType<typeof resolveFlowEndpoints>; exitId?: number; reverse: boolean }>()
const enIds = new Set(topo.enNodes.map((n) => n.id))
let totalBytes = 0
@@ -520,15 +558,6 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
return resolveMapClient(topo, r.serverId, inName, outName)
}
const payloadRows = wantDedup
? dedupFlowRowsAcrossExporters(working, (a, b) => {
const aCli = Boolean(rowClient(a))
const bCli = Boolean(rowClient(b))
if (aCli !== bCli) return aCli ? a : b
return a.bytes >= b.bytes ? a : b
})
: working
for (const r of working) {
const inRes = resolveIfaceName(r.serverId, r.inIface)
const outRes = resolveIfaceName(r.serverId, r.outIface)
@@ -573,20 +602,37 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
}
}
const enOut = ifaceUsable(outName) ? resolveEn(topo, r.nextHop, outName) : null
const enIn = ifaceUsable(inName) ? resolveEn(topo, "", inName) : null
const en = (enOut && enOut.id !== r.serverId ? enOut : null)
?? (enIn && enIn.id !== r.serverId ? enIn : null)
if (en) {
jhToEn.set(r.serverId, en.id)
const toId = String(en.id)
const dir: "fwd" | "rev" = enOut && enOut.id === en.id ? "fwd" : "rev"
const bindings = peers.get(r.bucketAt)
const outPeer = bindings?.get(fromId + "|" + outName)
const outId = outPeer === undefined ? hostIds.get(r.nextHop) : hostIds.get(outPeer)
const inId = hostIds.get(bindings?.get(fromId + "|" + inName) ?? "")
const peerId = outId && inId && outId !== inId ? null : outId ?? inId
const endpoints = resolveFlowEndpoints({
src: r.src,
dst: r.dst,
srcPort: r.srcPort,
dstPort: r.dstPort,
ctx: destCtxForIface(topo, r.serverId, inName, {
outIface: outName,
natSrc: r.natSrc,
natDst: r.natDst,
natSrcPort: r.natSrcPort,
natDstPort: r.natDstPort,
}),
})
const reverse = !!endpoints.internetPeer && (endpoints.internetPeer === endpoints.packetSrc || endpoints.internetPeer === r.natSrc)
const serviceSide = endpoints.internetPeer ? (reverse ? inId : outId) : peerId
const exitId = enIds.has(r.serverId) ? r.serverId : serviceSide ?? undefined
observed.set(r, { endpoints, exitId, reverse })
if (peerId && peerId !== r.serverId) {
const toId = String(peerId)
const dir = outId === peerId ? "fwd" : "rev"
const greIface = dir === "fwd" && ifaceUsable(outName) ? outName : (ifaceUsable(inName) ? inName : undefined)
bump(hops, JSON.stringify(["gre", fromId, toId, greIface]), {
fromId,
fromLabel,
toId,
toLabel: en.name,
toLabel: nodeName(toId),
kind: "gre",
iface: greIface,
}, r.bytes, dir)
@@ -616,44 +662,32 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
}
}
const payloadRows = wantDedup
? dedupFlowRowsAcrossExporters(working, (a, b) => {
const aRouted = observed.get(a)?.exitId !== undefined
const bRouted = observed.get(b)?.exitId !== undefined
if (aRouted !== bRouted) return aRouted ? a : b
const aCli = Boolean(rowClient(a))
const bCli = Boolean(rowClient(b))
if (aCli !== bCli) return aCli ? a : b
return a.bytes >= b.bytes ? a : b
})
: working
for (const r of payloadRows) {
const inName = resolveIfaceName(r.serverId, r.inIface).name
const outName = resolveIfaceName(r.serverId, r.outIface).name
totalBytes += r.bytes
const ep = resolveFlowEndpoints({
src: r.src,
dst: r.dst,
srcPort: r.srcPort,
dstPort: r.dstPort,
ctx: destCtxForIface(topo, r.serverId, inName, {
outIface: outName,
natSrc: r.natSrc,
natDst: r.natDst,
natSrcPort: r.natSrcPort,
natDstPort: r.natDstPort,
}),
})
const { endpoints: ep, exitId, reverse } = observed.get(r)!
const dst = ep.internetPeer
const dstPort = ep.peerPort || r.dstPort
const srcPort = ep.otherPort || r.srcPort
const destKey = dst ? JSON.stringify([dst, r.proto, dstPort, srcPort]) : ""
const client = resolveMapClient(topo, r.serverId, inName, outName)
const prevDst = dstAcc.get(destKey)
if (prevDst) {
prevDst.bytes += r.bytes
bumpFrom(prevDst, String(r.serverId), r.bytes, client)
} else {
const acc: DstAcc = {
dst,
bytes: r.bytes,
proto: r.proto,
dstPort,
srcPort,
fromBytes: new Map(),
}
bumpFrom(acc, String(r.serverId), r.bytes, client)
dstAcc.set(destKey, acc)
}
const acc = dstAcc.get(destKey) ?? { dst, bytes: 0, proto: r.proto, dstPort, srcPort, fromBytes: new Map<string, FromAcc>() }
acc.bytes += r.bytes
if (exitId !== undefined) bumpFrom(acc, String(r.serverId), String(exitId), r.bytes, reverse, client)
dstAcc.set(destKey, acc)
}
const svcTotals = new Map<string, DestTotal>()
@@ -666,25 +700,6 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
const nestedEdges = new Map<string, DestEdgeAcc>()
const nestedPaths = new Map<string, DestPathAcc>()
for (const h of hops.values()) {
if (h.kind !== "gre" || !h.toId) continue
const from = Number(h.fromId)
const to = Number(h.toId)
if (!Number.isFinite(from) || !Number.isFinite(to)) continue
if (enIds.has(to) && !enIds.has(from)) jhToEn.set(from, to)
}
const soleEnId = topo.enNodes.length === 1 ? String(topo.enNodes[0]!.id) : null
function anchorEnId(exporterId: string): string | null {
const n = Number(exporterId)
if (enIds.has(n)) return exporterId
const mapped = jhToEn.get(n)
if (mapped != null) return String(mapped)
if (soleEnId) return soleEnId
return null
}
function nodeName(id: string): string {
const n = Number(id)
if (Number.isFinite(n)) {
@@ -708,9 +723,8 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
bumpDestTotal(ccTotals, country.id, country.label, country.category, acc.bytes)
const nestedId = mapCountryServiceNodeId(country.id, svcId)
bumpDestTotal(nestedTotals, nestedId, classified.service, classified.category, acc.bytes)
for (const [exporterId, from] of acc.fromBytes) {
const fromId = anchorEnId(exporterId)
if (!fromId) continue
for (const from of acc.fromBytes.values()) {
const { exporterId, enId: fromId } = from
const enName = nodeName(fromId)
const viaName = nodeName(exporterId)
bumpDestFrom(svcEdges, svcPaths, svcId, from, exporterId, fromId, enName, viaName)
@@ -741,7 +755,7 @@ async function buildFlowMapHopsUncached(q: FlowMapHopsQuery, minSharePct: number
if (scope && (!isDeepStrictEqual(topo, await loadFlowTopology(scope.serverIds, authorize)) || !isDeepStrictEqual(limits, await readFlowMapSourceLimits()))) throw new Error("Топология или пределы карты NetFlow изменились во время чтения")
await authorize()
// Whole-interface counters must never be exposed as per-user payload or added to totalBytes.
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, now)
const interfaceTraffic = q.userId ? undefined : await readInterfaceTraffic(q.serverId ? [q.serverId] : [...catalog.byId.keys()], ifaceFilter, q, end)
await authorize()
return {
...(interfaceTraffic ? { interfaceTraffic } : {}),
+2
View File
@@ -66,6 +66,8 @@
### Несколько туннелей на одном VPS
Для подготовки транспорта из меню WireGuard или GRE/IPsec выберите **Скопировать ссылку для ix-client**. На VPS нажмите **L** в ix-client, вставьте ссылку и нажмите **F2**. Ссылка действует до пяти минут и погашается при первой попытке загрузки. В **P → Зависимости** можно проверить и по подтверждению установить недостающие пакеты. После подготовки транспорта сохраните группу и скопируйте её ссылку рядом с кнопкой **Скачать для ix-client**. JSON по-прежнему можно импортировать через **B → I**.
Карточка Linux-клиента объединяет его туннели и группы резервирования. Для нового интерфейса RouterOS имя включает протокол, имя клиента и уникальный суффикс, например `il-gre-tg-a1b2c3d4e5f6`. Существующие подключения сохраняют свои имена. RX и TX в строке GRE/IPsec показывают накопленные байты интерфейса на CHR.
1. В **Linux-клиенты** откройте меню действующего подключения и выберите **Создать группу с этим туннелем**. Интерфейс уже будет первым в списке. Для участника существующей группы это же меню открывает её редактор. Ключи VPS и CHR при создании группы сохраняются. Для нового транспорта откройте меню клиента и скачайте **Конфиг для группы ix-client**.
+12 -6
View File
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
import { peakOfCombinedTraffic, projectTrafficObservations } from "./traffic-observations.js"
import { peakOfCombinedTraffic, projectTrafficObservations, sumObservedTraffic } from "./traffic-observations.js"
const at=Date.parse("2026-10-12T12:00:00Z"),sampledAt=new Date(at).toISOString(),expiresAt=new Date(at+90_000).toISOString()
const row={rxNow:0,txNow:0,rxPeak:0,txPeak:0,rxTotal:0,txTotal:0,rxSeries:[0,0],txSeries:[0,0]}
const obs={rxNow:true,txNow:true,rxSeries:[false,true],txSeries:[false,true],sampledAt,currentState:"current",expiresAt}
@@ -16,8 +16,14 @@ const noPeak=projectTrafficObservations({...row,volumeUnit:"GiB",observations:{.
assert.equal(noPeak.rxPeak,null);assert.equal(noPeak.txPeak,null);assert.equal(noPeak.rxTotal,0)
assert.equal(projectTrafficObservations({...row,observations:{...obs,rxPeak:true,txPeak:true}},at).rxPeak,0)
console.log('aggregate peak confidence overrides bucket confidence; measured zero and volumes retained')
assert.equal(peakOfCombinedTraffic([[10, 3, 20], [4, 15, null]]), 18)
assert.equal(peakOfCombinedTraffic([[0, null], [0, 50]]), 0)
assert.equal(peakOfCombinedTraffic([[null, 10], [4, null]]), null)
assert.equal(peakOfCombinedTraffic([[2], [4, 5]]), null)
assert.equal(peakOfCombinedTraffic([]), null)
assert.equal(peakOfCombinedTraffic([[10, 3, 20], [4, 15, null]]).value, 18)
assert.equal(peakOfCombinedTraffic([[0, null], [0, 50]]).value, 0)
assert.equal(peakOfCombinedTraffic([[null, 10], [4, null]]).value, null)
assert.equal(peakOfCombinedTraffic([[2], [4, 5]]).value, null)
assert.equal(peakOfCombinedTraffic([]).value, null)
assert.deepEqual(sumObservedTraffic([null, 0]), { value: 0, observed: 1 })
assert.deepEqual(sumObservedTraffic([null, null]), { value: null, observed: 0 })
assert.deepEqual(peakOfCombinedTraffic([[10, 3], [4, 15], [null, null]], true), { value: 18, observed: 2 })
assert.deepEqual(peakOfCombinedTraffic([[10, 5], [null, 5]], true), { value: 10, observed: 2 })
assert.deepEqual(peakOfCombinedTraffic([[100, 5], [null, 5]], true), { value: 100, observed: 1 })
assert.deepEqual(peakOfCombinedTraffic([[null], [null]], true), { value: null, observed: 0 })
+19 -8
View File
@@ -7,16 +7,27 @@ const meta = z.object({ rxNow: z.boolean(), txNow: z.boolean(), rxSeries: z.arra
currentState: z.enum(["current", "unknown", "pending", "error", "stale", "disabled"]).optional() })
export type TrafficObservationMeta = z.infer<typeof meta>
/** Sum only intervals with an observation from every series. */
export function peakOfCombinedTraffic(series: readonly (readonly (number | null)[])[]): number | null {
export function sumObservedTraffic(rates: readonly (number | null)[]) {
let sum = 0
let observed = 0
for (const rate of rates) {
if (rate === null) continue
sum += rate
observed++
}
return { value: observed > 0 ? sum : null, observed }
}
export function peakOfCombinedTraffic(series: readonly (readonly (number | null)[])[], allowPartial = false) {
const length = series[0]?.length
if (!length || series.some(values => values.length !== length)) return null
let peak: number | null = null
let peak = { value: null as number | null, observed: 0 }
if (!length || series.some(values => values.length !== length)) return peak
for (let index = 0; index < length; index++) {
const slots = series.map(values => values[index])
if (slots.some(value => value == null)) continue
const sum = slots.reduce<number>((total, value) => total + (value ?? 0), 0)
peak = peak === null ? sum : Math.max(peak, sum)
const bucket = sumObservedTraffic(series.map(values => values[index]))
if (bucket.value === null || (!allowPartial && bucket.observed !== series.length)) continue
if (peak.value === null || bucket.value > peak.value || (bucket.value === peak.value && bucket.observed > peak.observed)) {
peak = bucket
}
}
return peak
}
+27
View File
@@ -4,6 +4,33 @@ const flowPath="/api/traffic/flow/map-hops"
test.beforeEach(async({page})=>{await page.route("**/health",r=>r.fulfill({json:{ok:true}}))})
const server={id:1,name:"Router",host:"192.0.2.1",type:"home-router",country:"RU",enabled:true,status:"online"}
test("Карта не приписывает весь YouTube единственному выходу ARN", async ({page}) => {
const service = {id: "svc:youtube", label: "YouTube", category: "Видео", bytes: 900000, bps: 24000, share: 1}
const edge = {fromId: "1", toId: service.id, bytes: 300000, bps: 8000, bpsFwd: 2000, bpsRev: 6000}
let known = false
await page.route("**/api/**", route => {
const path = new URL(route.request().url()).pathname
const responses: Record<string, unknown> = {
"/api/auth/config": {required: false}, "/api/servers": [{...server, type: "exit-node", name: "ARN"}],
"/api/filters/gre-tunnels": {tunnels: [], failures: []}, "/api/uptime/speed-probes": {probes: []},
[flowPath]: {...empty, totalBytes: service.bytes, namedBytes: service.bytes, services: [service], serviceEdges: known ? [edge] : []},
}
return route.fulfill({json: responses[path] ?? {}})
})
await page.goto("/network-map")
await page.getByRole("button", {name: "Сервис YouTube", exact: true}).press("Enter")
const unknown = page.getByText("Выход не определён", {exact: true}).locator("..")
const badges = page.getByRole("button", {name: "Поток NetFlow между узлами"})
await expect(unknown).toContainText("24 Кбит/с")
await expect(badges).toHaveCount(0)
known = true
await page.getByRole("button", {name: "Обновить", exact: true}).click()
await expect(unknown).toContainText("16 Кбит/с")
await expect(badges).toHaveCount(1)
await expect(badges).toContainText("8 Кбит/с")
await expect(badges).toContainText("↓6 Кбит/с ↑2 Кбит/с")
})
for (const reverse of [false, true]) test(`Карта: малый NetFlow и текущие RX/TX GRE показаны отдельно, reverse=${reverse}`, async ({ page }) => {
const exit = { ...server, name: "ARN", type: "exit-node" }
const jump = { ...server, id: 2, name: "MSK-02", host: "192.0.2.2", type: "jump-host" }
+31
View File
@@ -1,4 +1,5 @@
import {test,expect} from '@playwright/test'
import {observedTrafficFixturePayload} from "./traffic-observation-fixture"
for(const width of [1440,320])test(`Пик трафика: неизвестный интервал, подтверждённый пик и ноль ${width}`,async({page})=>{
await page.setViewportSize({width,height:1000})
let peakKnown=false,peak=100
@@ -23,3 +24,33 @@ for(const width of [1440,320])test(`Пик трафика: неизвестны
await expect(peakCard).toContainText('0')
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1)).toBe(true)
})
test("Интерфейсы: один интерфейс без замеров не очищает суммы и пики", async ({page}) => {
const metrics = {rxNow: 2, txNow: 3, rxPeak: 8, txPeak: 9, rxTotal: 1, txTotal: 2, rxSeries: [8, 2], txSeries: [9, 3]}
const iface = {id: "i1", bindingId: "b1", userId: "u1", userLogin: "test", userName: "Тест",
interfaceName: "gre-a", interfaceType: "gre", comment: "", serverId: "1", serverName: "CHR",
serverSite: "TEST", serverCountry: "RU", status: "online"}
const interfaces = [
{...iface, ...metrics},
{...iface, ...metrics, id: "i2", bindingId: "b2", interfaceName: "gre-b", rxNow: 1, txNow: 2, rxSeries: [1, 7], txSeries: [2, 8]},
{...iface, ...metrics, id: "i3", bindingId: "b3", interfaceName: "gre-c", status: "unknown",
observations: {rxNow: false, txNow: false, rxSeries: [false, false], txSeries: [false, false],
sampledAt: null, currentState: "unknown"}},
]
await page.route("**/health", route => route.fulfill({json: {ok: true}}))
await page.route("**/api/**", route => {
const path = new URL(route.request().url()).pathname
const responses: Record<string, unknown> = {
"/api/auth/config": {required: false}, "/api/traffic/servers": {servers: []},
"/api/traffic/users": {users: []}, "/api/traffic/bound-interfaces": {interfaces}, "/api/servers": [],
}
return route.fulfill({json: observedTrafficFixturePayload(responses[path] ?? {})})
})
await page.goto("/traffic")
await page.getByRole("button", {name: "Интерфейсы", exact: true}).click()
for (const [label, value] of [["Сумма RX", "3"], ["Сумма TX", "5"], ["Пик суммы RX", "9"], ["Пик суммы TX", "11"]]) {
const card = page.locator('[data-slot="frame-panel"]').filter({has: page.getByText(label, {exact: true})})
await expect(card.getByText(new RegExp(`^${value}(?:[.,]0+)? Мбит/с$`))).toBeVisible()
await expect(card.getByText("2 из 3 интерф.", {exact: true}).filter({visible: true})).toBeVisible()
}
})