Browse Source

fix(traffic): preserve WAN peaks in aggregated charts (#1790)

Nacho 1 month ago
parent
commit
ff61b7e995

+ 1 - 1
app/public/locales/en/translation.json

@@ -652,7 +652,7 @@
       "rangeAria": "Traffic chart range",
       "tableCaption": "Traffic data ({{range}})",
       "time": "Time",
-      "title": "Network traffic",
+      "title": "WAN traffic",
       "total24h": "Total 24h",
       "uploadMbps": "Upload (Mbps)",
       "contracted": "Contracted: ↓ {{down}} / ↑ {{up}} Mbps",

+ 1 - 1
app/public/locales/es/translation.json

@@ -652,7 +652,7 @@
       "rangeAria": "Rango del gráfico de tráfico",
       "tableCaption": "Datos de tráfico ({{range}})",
       "time": "Hora",
-      "title": "Tráfico de red",
+      "title": "Tráfico WAN",
       "total24h": "Total 24h",
       "uploadMbps": "Subida (Mbps)",
       "contracted": "Contratado: ↓ {{down}} / ↑ {{up}} Mbps",

+ 1 - 1
app/src/components/routers/FleetCard.tsx

@@ -307,7 +307,7 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
                 </defs>
                 <Tooltip content={<TrafficTooltip unit={trafficUnit} />} cursor={{ stroke: 'rgb(var(--border-strong))', strokeWidth: 1 }} />
                 <Area
-                  type="monotone"
+                  type="linear"
                   dataKey="v"
                   stroke="#22D3EE"
                   strokeWidth={1.75}

+ 2 - 2
app/src/components/routers/PortSeriesChart.tsx

@@ -460,7 +460,7 @@ export function PortSeriesChart({
               <XAxis dataKey="t" hide />
               <Tooltip content={<PortTooltip unit={effUnit} />} cursor={{ stroke: 'rgb(var(--border-strong))', strokeWidth: 1 }} />
               <Area
-                type="monotone"
+                type="linear"
                 dataKey="rx"
                 name="RX"
                 stroke="#3b82f6"
@@ -471,7 +471,7 @@ export function PortSeriesChart({
                 isAnimationActive={false}
               />
               <Area
-                type="monotone"
+                type="linear"
                 dataKey="tx"
                 name="TX"
                 stroke="#10b981"

+ 2 - 2
app/src/components/routers/WanLatency.tsx

@@ -99,8 +99,8 @@ export function WanLatency({ extras }: { extras?: RouterExtras }) {
                 minTickGap={40}
               />
               <Tooltip content={<WanTooltip />} cursor={{ stroke: 'rgb(var(--border-strong))', strokeWidth: 1 }} />
-              <Area type="monotone" dataKey="down" stroke="#22D3EE" strokeWidth={2} fill="url(#wan-detail-down)" dot={false} animationDuration={900} animationEasing="ease-out" />
-              <Area type="monotone" dataKey="up" stroke="#A78BFA" strokeWidth={2} fill="url(#wan-detail-up)" dot={false} animationDuration={900} animationEasing="ease-out" />
+              <Area type="linear" dataKey="down" stroke="#22D3EE" strokeWidth={2} fill="url(#wan-detail-down)" dot={false} animationDuration={900} animationEasing="ease-out" />
+              <Area type="linear" dataKey="up" stroke="#A78BFA" strokeWidth={2} fill="url(#wan-detail-up)" dot={false} animationDuration={900} animationEasing="ease-out" />
             </AreaChart>
           </ResponsiveContainer>
         </motion.div>

+ 2 - 2
app/src/sections/WanTraffic.tsx

@@ -176,7 +176,7 @@ export function WanTraffic() {
               />
             ) : null}
             <Area
-              type="monotone"
+              type="linear"
               dataKey="down"
               stroke="#22D3EE"
               strokeWidth={2}
@@ -187,7 +187,7 @@ export function WanTraffic() {
               animationEasing="ease-out"
             />
             <Area
-              type="monotone"
+              type="linear"
               dataKey="up"
               stroke="#A78BFA"
               strokeWidth={2}

+ 2 - 2
server-go/internal/adapters/live.go

@@ -1023,7 +1023,7 @@ func (l *Live) metricsHistoryBuckets(routerID string, span, bucket int64, fmtLab
 	}
 	now := time.Now().UnixMilli()
 	rows, err := l.db.Query(
-		`SELECT (bucket_ts / ?) AS win, AVG(rx_avg) AS rx, AVG(tx_avg) AS tx,
+		`SELECT (bucket_ts / ?) AS win, MAX(rx_max) AS rx, MAX(tx_max) AS tx,
 		        AVG(cpu_avg) AS cpu, AVG(ram_avg) AS ram, AVG(temp_avg) AS temp,
 		        MIN(bucket_ts) AS t0
 		 FROM metrics_buckets WHERE router_id = ? AND bucket_ts >= ?
@@ -1091,7 +1091,7 @@ func (l *Live) metricsHistory(routerID, rang string) []histPoint {
 		return l.metricsHistoryBuckets(routerID, span, bucket, fmtLabel)
 	}
 	rows, err := l.db.Query(
-		`SELECT (ts / ?) AS bucket, AVG(rx_bps) AS rx, AVG(tx_bps) AS tx, AVG(cpu) AS cpu, AVG(ram) AS ram, AVG(temp) AS temp, MIN(ts) AS t0
+		`SELECT (ts / ?) AS bucket, MAX(rx_bps) AS rx, MAX(tx_bps) AS tx, AVG(cpu) AS cpu, AVG(ram) AS ram, AVG(temp) AS temp, MIN(ts) AS t0
 		 FROM metrics WHERE router_id = ? AND ts >= ? GROUP BY bucket ORDER BY bucket`,
 		bucket, routerID, now-span)
 	if err != nil {

+ 72 - 0
server-go/internal/adapters/live_traffic_history_test.go

@@ -0,0 +1,72 @@
+package adapters
+
+import (
+	"testing"
+	"time"
+)
+
+func TestMetricsHistoryPreservesTrafficPeaks(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := &Live{db: d}
+	start := time.Now().Add(-2 * time.Hour).Truncate(time.Hour)
+
+	for i := 0; i < 16; i++ {
+		rx, tx, cpu := 1e6, 1e6, 10.0
+		if i == 7 {
+			rx, tx, cpu = 447.5e6, 28.2e6, 100.0
+		}
+		if _, err := d.Exec(`INSERT INTO metrics
+			(router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps)
+			VALUES ('gw', ?, ?, 20, 40, 0, ?, ?)`,
+			start.Add(time.Duration(i)*3*time.Minute).UnixMilli(), cpu, rx, tx); err != nil {
+			t.Fatalf("insert metric: %v", err)
+		}
+	}
+
+	got := l.metricsHistory("gw", "24h")
+	if len(got) != 1 {
+		t.Fatalf("len=%d, want 1 hourly point", len(got))
+	}
+	if got[0].down != 447.5 || got[0].up != 28.2 {
+		t.Fatalf("traffic=(%.1f, %.1f) Mbps, want peak (447.5, 28.2)", got[0].down, got[0].up)
+	}
+	if got[0].cpu != 16 {
+		t.Fatalf("cpu=%d, want average 16", got[0].cpu)
+	}
+}
+
+func TestMetricsHistoryBucketsPreservesTrafficPeaks(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := &Live{db: d}
+	start := time.Now().Add(-24 * time.Hour).Truncate(6 * time.Hour)
+	samples := []struct {
+		offset       time.Duration
+		rxAvg, rxMax float64
+		txAvg, txMax float64
+		cpu          float64
+	}{
+		{offset: 5 * time.Minute, rxAvg: 1e6, rxMax: 50e6, txAvg: 1e6, txMax: 10e6, cpu: 10},
+		{offset: 10 * time.Minute, rxAvg: 2e6, rxMax: 447.5e6, txAvg: 2e6, txMax: 28.2e6, cpu: 20},
+	}
+	for _, sample := range samples {
+		ts := start.Add(sample.offset).UnixMilli()
+		if _, err := d.Exec(`INSERT INTO metrics_buckets
+			(router_id, bucket_ts, n, min_ts, cpu_avg, ram_avg, temp_avg,
+			 rx_min, rx_max, rx_avg, tx_min, tx_max, tx_avg)
+			VALUES ('gw', ?, 1, ?, ?, 20, 40, 0, ?, ?, 0, ?, ?)`,
+			ts, ts, sample.cpu, sample.rxMax, sample.rxAvg, sample.txMax, sample.txAvg); err != nil {
+			t.Fatalf("insert metrics bucket: %v", err)
+		}
+	}
+
+	got := l.metricsHistory("gw", "30d")
+	if len(got) != 1 {
+		t.Fatalf("len=%d, want 1 six-hour point", len(got))
+	}
+	if got[0].down != 447.5 || got[0].up != 28.2 {
+		t.Fatalf("traffic=(%.1f, %.1f) Mbps, want peak (447.5, 28.2)", got[0].down, got[0].up)
+	}
+	if got[0].cpu != 15 {
+		t.Fatalf("cpu=%d, want average 15", got[0].cpu)
+	}
+}

+ 2 - 2
server-go/internal/portseries/portseries.go

@@ -379,7 +379,7 @@ func (s *Store) HourlyFpsTotal(routerID string, hours int) ([]float64, error) {
 // HourlyBpsTotal devuelve el tráfico agregado del router en bits/s por bucket
 // de una hora. Es el respaldo de la línea de 24 h de las unidades que no
 // publican serie de throughput propia (SNMP o pusher external, #1741): por
-// cada hora y puerto se toma la media de rx_bps/tx_bps de las muestras
+// cada hora y puerto se toma el máximo de rx_bps/tx_bps de las muestras
 // guardadas y se suman todos los puertos. A diferencia de HourlyFpsTotal no
 // necesita la hora anterior: la tasa ya viene derivada en cada muestra. El
 // slice tiene `hours` entradas; huecos a 0.
@@ -393,7 +393,7 @@ func (s *Store) HourlyBpsTotal(routerID string, hours int) ([]float64, error) {
 	// Mismo cuidado con el driver (issue #648): divisor literal entero dentro
 	// del CAST para que la división sea entera y no pierda precisión.
 	rows, err := s.db.Query(`SELECT CAST(ts / 3600000 AS INTEGER) AS h, port_id,
-			AVG(COALESCE(rx_bps, 0)), AVG(COALESCE(tx_bps, 0))
+			MAX(COALESCE(rx_bps, 0)), MAX(COALESCE(tx_bps, 0))
 		FROM port_series_raw
 		WHERE router_id = ? AND ts >= ?
 		GROUP BY h, port_id ORDER BY h`, routerID, startMs)

+ 4 - 4
server-go/internal/portseries/portseries_test.go

@@ -333,7 +333,7 @@ func TestHourlyFpsTotal(t *testing.T) {
 }
 
 // HourlyBpsTotal: respaldo de la línea de 24 h de las unidades sin serie
-// propia de throughput (#1741). Por hora y puerto se toma la media de las
+// propia de throughput (#1741). Por hora y puerto se conserva el pico de las
 // muestras y se suman los puertos.
 func TestHourlyBpsTotal(t *testing.T) {
 	s := openTestDB(t)
@@ -361,9 +361,9 @@ func TestHourlyBpsTotal(t *testing.T) {
 	if out[0] < 349 || out[0] > 351 {
 		t.Fatalf("hora anterior: %.0f bps, esperaba 350", out[0])
 	}
-	// Hora en curso: media del SFP (400 rx + 100 tx) y ether1 sin tasa.
-	if out[1] < 499 || out[1] > 501 {
-		t.Fatalf("hora en curso: %.0f bps, esperaba 500", out[1])
+	// Hora en curso: pico del SFP (500 rx + 100 tx) y ether1 sin tasa.
+	if out[1] < 599 || out[1] > 601 {
+		t.Fatalf("hora en curso: %.0f bps, esperaba 600", out[1])
 	}
 }