Compare commits

..
2 Commits
Author SHA1 Message Date
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
7 changed files with 123 additions and 29 deletions

No files matched your search

+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",
},
+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 }
@@ -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)
+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
}
+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()
}
})