From 1b927dcf68ee2845057b4f193e86916afa2c6790 Mon Sep 17 00:00:00 2001 From: Denozordec Date: Tue, 24 Nov 2026 16:37:50 +0700 Subject: [PATCH] =?UTF-8?q?fix(traffic):=20=D0=BF=D0=BE=D0=BA=D0=B0=D0=B7?= =?UTF-8?q?=D1=8B=D0=B2=D0=B0=D1=82=D1=8C=20=D0=BF=D0=BE=D0=BA=D0=B0=D0=B7?= =?UTF-8?q?=D0=B0=D1=82=D0=B5=D0=BB=D0=B8=20=D0=B8=D0=BD=D1=82=D0=B5=D1=80?= =?UTF-8?q?=D1=84=D0=B5=D0=B9=D1=81=D0=BE=D0=B2=20=D0=BF=D1=80=D0=B8=20?= =?UTF-8?q?=D0=BD=D0=B5=D0=BF=D0=BE=D0=BB=D0=BD=D1=8B=D1=85=20=D0=B7=D0=B0?= =?UTF-8?q?=D0=BC=D0=B5=D1=80=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/(main)/traffic/page.tsx | 32 ++++++++++++++--------- lib/traffic-observations.test.ts | 18 ++++++++----- lib/traffic-observations.ts | 27 +++++++++++++------ tests/e2e/traffic-peak-confidence.spec.ts | 31 ++++++++++++++++++++++ 4 files changed, 81 insertions(+), 27 deletions(-) diff --git a/app/(main)/traffic/page.tsx b/app/(main)/traffic/page.tsx index ccd684df..ee9a71bc 100644 --- a/app/(main)/traffic/page.tsx +++ b/app/(main)/traffic/page.tsx @@ -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: , 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: , iconClassName: "text-info", }, { id: "peak-rx", label: "Пик суммы RX", - value: fmtRate(peakRx), - hint: exactPeaks ? "По общим замерам" : "По интервалам графика", + value: fmtRate(peakRx.value), + hint: coverageHint(peakRx.observed) ?? peakHint, icon: , iconClassName: "text-warning", }, { id: "peak-tx", label: "Пик суммы TX", - value: fmtRate(peakTx), - hint: exactPeaks ? "По общим замерам" : "По интервалам графика", + value: fmtRate(peakTx.value), + hint: coverageHint(peakTx.observed) ?? peakHint, icon: , iconClassName: "text-warning", }, diff --git a/lib/traffic-observations.test.ts b/lib/traffic-observations.test.ts index cad0216c..7ef3c060 100644 --- a/lib/traffic-observations.test.ts +++ b/lib/traffic-observations.test.ts @@ -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 }) diff --git a/lib/traffic-observations.ts b/lib/traffic-observations.ts index a807fceb..c05b2e9f 100644 --- a/lib/traffic-observations.ts +++ b/lib/traffic-observations.ts @@ -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 -/** 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((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 } diff --git a/tests/e2e/traffic-peak-confidence.spec.ts b/tests/e2e/traffic-peak-confidence.spec.ts index cb3c147a..5f4b1b3e 100644 --- a/tests/e2e/traffic-peak-confidence.spec.ts +++ b/tests/e2e/traffic-peak-confidence.spec.ts @@ -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 = { + "/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() + } +})