Explorar o código

fix(wan): compute peak today, avg and 24h total from metrics in live mode (#170)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho hai 3 meses
pai
achega
76d5a340d8

+ 9 - 1
server-go/internal/adapters/fmtutil.go

@@ -31,8 +31,16 @@ func parseBytes(str string) float64 {
 }
 
 // fmtBytes formatea bytes al estilo ES del contrato (wireguard.js:38-46):
-// ≥1e9 → entero "N GB" o 1 decimal con coma; ≥1e6 → "N MB"; ≥1e3 → "N KB".
+// ≥1e12 → entero "N TB" o 1 decimal con coma; ≥1e9 → "N GB"; ≥1e6 → "N MB";
+// ≥1e3 → "N KB". La rama TB la pide el total 24h del WAN (issue #169).
 func fmtBytes(bytes float64) string {
+	if bytes >= 1e12 {
+		v := bytes / 1e12
+		if v == math.Trunc(v) {
+			return fmt.Sprintf("%d TB", int64(v))
+		}
+		return strings.Replace(strconv.FormatFloat(v, 'f', 1, 64), ".", ",", 1) + " TB"
+	}
 	if bytes >= 1e9 {
 		v := bytes / 1e9
 		if v == math.Trunc(v) {

+ 63 - 0
server-go/internal/adapters/live.go

@@ -176,6 +176,10 @@ type Live struct {
 	agentDown        map[string]bool
 	agentDownConfirm time.Duration // Dead Man's Switch: confirmar caída tras este periodo sin alertar
 
+	// now: reloj inyectable para tests deterministas (nil → time.Now).
+	// Mismo patrón que AgentRegistry.SetClock.
+	now func() time.Time
+
 	agStd *AdGuardClient
 	agGL  *AdGuardGlinetClient
 	agKey string
@@ -511,6 +515,56 @@ func (l *Live) metricsHistory(routerID, rang string) []histPoint {
 	return out
 }
 
+// wanDayStats rellena los campos del resumen WAN que solo el modo demo
+// calculaba (issue #169): pico de hoy (Mbps + hora), media de bajada y total
+// de 24 h, todo desde la tabla raw de métricas del gateway. La hora del pico
+// usa el ts de la fila del máximo; el total estima bytes como
+// SUM(rx_bps) × Δt (Δt = 86400/N s entre muestras, luego /8 bits→bytes).
+// Sin BD, sin gateway o sin datos devuelve los valores cero/"—" de partida.
+type wanDayStatsResult struct {
+	peakMbps float64
+	peakTime string
+	avgMbps  float64
+	totalStr string
+}
+
+func (l *Live) wanDayStats(gwID string) wanDayStatsResult {
+	out := wanDayStatsResult{peakTime: "—", totalStr: "—"}
+	if l.db == nil || gwID == "" {
+		return out
+	}
+	now := time.Now()
+	if l.now != nil {
+		now = l.now()
+	}
+	startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).UnixMilli()
+	start24h := now.Add(-24 * time.Hour).UnixMilli()
+
+	// Pico de hoy: fila con MAX(rx_bps) y su ts (la hora del pico).
+	row := l.db.QueryRow(
+		`SELECT rx_bps, ts FROM metrics WHERE router_id = ? AND ts >= ? AND rx_bps IS NOT NULL
+		 ORDER BY rx_bps DESC LIMIT 1`, gwID, startOfDay)
+	var peakBps float64
+	var peakTs int64
+	if err := row.Scan(&peakBps, &peakTs); err == nil {
+		out.peakMbps = math.Round(peakBps/1e6*10) / 10
+		out.peakTime = time.UnixMilli(peakTs).Local().Format("15:04")
+	}
+
+	// Media 24h + total: AVG(rx_bps) y bytes estimados con el Δt medio.
+	row = l.db.QueryRow(
+		`SELECT AVG(rx_bps), SUM(rx_bps), COUNT(rx_bps) FROM metrics
+		 WHERE router_id = ? AND ts >= ? AND rx_bps IS NOT NULL`, gwID, start24h)
+	var avg, sum sql.NullFloat64
+	var n sql.NullInt64
+	if err := row.Scan(&avg, &sum, &n); err == nil && avg.Valid && sum.Valid && n.Valid && n.Int64 > 0 {
+		out.avgMbps = math.Round(avg.Float64/1e6*10) / 10
+		dt := float64(86400) / float64(n.Int64) // s entre muestras
+		out.totalStr = fmtBytes(sum.Float64 * dt / 8)
+	}
+	return out
+}
+
 // pollRouter sondea un router; error si está inalcanzable. Si el router tiene
 // agente nativo con payload fresco (Tier 2), el sondeo viene del último push
 // y NO se toca SSH; si el agente expiró, se degrada a Tier 0 (SSH) con aviso.
@@ -1258,6 +1312,15 @@ func (l *Live) defaultWan(gw *RouterConfig) WAN {
 			wan.LossPct = *p.lossPct
 		}
 	}
+	// Resumen del día desde la BD (issue #169): pico de hoy, media y total
+	// 24h solo los poblaba el modo demo; aquí se calculan con la tabla raw.
+	if gw != nil {
+		ds := l.wanDayStats(gw.ID)
+		wan.PeakTodayMbps = ds.peakMbps
+		wan.PeakTodayTime = ds.peakTime
+		wan.AvgDownMbps = ds.avgMbps
+		wan.Total24h = ds.totalStr
+	}
 	return wan
 }
 

+ 95 - 0
server-go/internal/adapters/live_wanstats_test.go

@@ -0,0 +1,95 @@
+package adapters
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// openLiveTestDB abre una BD SQLite real en un dir temporal (patrón de
+// db/rollup_test.go, pero en el paquete adapters para probar wanDayStats).
+func openLiveTestDB(t *testing.T) *db.DB {
+	t.Helper()
+	dataDir := t.TempDir()
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	return d
+}
+
+func insertMetric(t *testing.T, d *db.DB, routerID string, ts time.Time, rxBps float64) {
+	t.Helper()
+	_, err := d.Exec(
+		"INSERT INTO metrics (router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps) VALUES (?,?,0,0,0,0,?,0)",
+		routerID, ts.UnixMilli(), rxBps)
+	if err != nil {
+		t.Fatalf("insert metric: %v", err)
+	}
+}
+
+// Reloj fijo: 12-Ago-2026 21:00 local (ventana "hoy" = 12-Ago 00:00–23:59).
+func fixedNow() time.Time {
+	return time.Date(2026, 8, 12, 21, 0, 0, 0, time.Local)
+}
+
+// wanDayStats calcula pico de hoy, media y total 24h desde la tabla raw del
+// gateway (issue #169: solo la demo poblaba estos campos en live).
+func TestWanDayStats(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := &Live{db: d, now: fixedNow}
+	now := fixedNow()
+
+	// Ayer (fuera del rango de hoy, pero 2 muestras dentro de la ventana 24h
+	// si caen >= now-24h). now-24h = 11-Ago 21:00.
+	insertMetric(t, d, "gw", now.Add(-25*time.Hour), 10e6)  // 11-Ago 20:00 → fuera de 24h
+	insertMetric(t, d, "gw", now.Add(-24*time.Hour), 20e6)  // 11-Ago 21:00 → dentro (borde)
+	// Hoy (12-Ago): pico a las 15:00 con 90 Mbps.
+	insertMetric(t, d, "gw", time.Date(2026, 8, 12, 10, 0, 0, 0, time.Local), 30e6)
+	insertMetric(t, d, "gw", time.Date(2026, 8, 12, 15, 0, 0, 0, time.Local), 90e6)
+	insertMetric(t, d, "gw", time.Date(2026, 8, 12, 18, 0, 0, 0, time.Local), 50e6)
+	// Otro router: no debe contaminar las stats del gateway.
+	insertMetric(t, d, "rt2", time.Date(2026, 8, 12, 15, 0, 0, 0, time.Local), 999e6)
+
+	res := l.wanDayStats("gw")
+	if res.peakMbps != 90 {
+		t.Fatalf("peakMbps=%v, esperaba 90", res.peakMbps)
+	}
+	if res.peakTime != "15:00" {
+		t.Fatalf("peakTime=%q, esperaba 15:00", res.peakTime)
+	}
+	// Media de los 4 puntos del gateway dentro de 24h: (20+30+90+50)/4 = 47.5.
+	if res.avgMbps != 47.5 {
+		t.Fatalf("avgMbps=%v, esperaba 47.5", res.avgMbps)
+	}
+	// Total 24h: SUM(rx_bps)×dt/8 con dt = 86400/4 = 21600s.
+	// (20+30+90+50)e6 × 21600 / 8 = 190e6×21600/8 = 5.13e11 bytes = 513 GB.
+	if res.totalStr != "513 GB" {
+		t.Fatalf("totalStr=%q, esperaba 513 GB", res.totalStr)
+	}
+}
+
+// wanDayStats con gateway sin datos: devuelve los marcadores "—"/0 de partida
+// (no pánico, no datos inventados).
+func TestWanDayStatsSinDatos(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := &Live{db: d, now: fixedNow}
+	res := l.wanDayStats("gw")
+	if res.peakMbps != 0 || res.avgMbps != 0 {
+		t.Fatalf("stats sin datos deberían ser 0: %+v", res)
+	}
+	if res.peakTime != "—" || res.totalStr != "—" {
+		t.Fatalf("marcadores sin datos deberían ser '—': %+v", res)
+	}
+}
+
+// wanDayStats sin BD (db nil, p. ej. modo demo): cero y "—" sin pánico.
+func TestWanDayStatsSinBD(t *testing.T) {
+	l := &Live{db: nil}
+	res := l.wanDayStats("gw")
+	if res.peakMbps != 0 || res.avgMbps != 0 || res.totalStr != "—" {
+		t.Fatalf("sin BD debería devolver zeros/'—': %+v", res)
+	}
+}