Просмотр исходного кода

feat(server-go): métricas operativas en /api/health (agentsConnected, sseConnections, devicesTotal) (#20)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 4 месяцев назад
Родитель
Сommit
27222c7aa1

+ 14 - 0
server-go/internal/adapters/agent.go

@@ -93,6 +93,20 @@ func (r *AgentRegistry) Expired(slug string) bool {
 	return ok && r.now().Sub(st.LastSeen) > r.ttl
 }
 
+// ActiveCount devuelve cuántos agentes tienen su último push dentro del TTL
+// (métricas operativas de /api/health).
+func (r *AgentRegistry) ActiveCount() int {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	n := 0
+	for _, st := range r.states {
+		if r.now().Sub(st.LastSeen) <= r.ttl {
+			n++
+		}
+	}
+	return n
+}
+
 // Forget borra el estado del slug (revocación de token).
 func (r *AgentRegistry) Forget(slug string) {
 	r.mu.Lock()

+ 29 - 6
server-go/internal/httpapi/health.go

@@ -7,7 +7,8 @@ import (
 	"time"
 )
 
-// handleAPIHealth: {ok, version, mode, uptimeSec, db}.
+// handleAPIHealth: {ok, version, mode, uptimeSec, db, agentsConnected,
+// sseConnections, devicesTotal}.
 func (s *server) handleAPIHealth(mode string) http.HandlerFunc {
 	return func(w http.ResponseWriter, r *http.Request) {
 		dbOk := s.db.CheckHealth()
@@ -15,12 +16,34 @@ func (s *server) handleAPIHealth(mode string) http.HandlerFunc {
 		if !dbOk {
 			dbStatus = "error"
 		}
+
+		// Métricas operativas (Fase 8): agentes vivos (dentro de TTL),
+		// clientes SSE conectados y total de dispositivos del último
+		// overview del poller. Nil-safe: demo/sin datos → 0.
+		agentsConnected := 0
+		if s.agents != nil {
+			agentsConnected = s.agents.ActiveCount()
+		}
+		sseConnections := 0
+		if s.hub != nil {
+			sseConnections = s.hub.Size()
+		}
+		devicesTotal := 0
+		if s.lastOv != nil {
+			if ov := s.lastOv(); ov != nil {
+				devicesTotal = ov.DeviceTotals.Total
+			}
+		}
+
 		writeJSON(w, http.StatusOK, map[string]any{
-			"ok":        dbOk,
-			"version":   Version,
-			"mode":      mode,
-			"uptimeSec": int64(time.Since(s.started).Seconds()),
-			"db":        dbStatus,
+			"ok":              dbOk,
+			"version":         Version,
+			"mode":            mode,
+			"uptimeSec":       int64(time.Since(s.started).Seconds()),
+			"db":              dbStatus,
+			"agentsConnected": agentsConnected,
+			"sseConnections":  sseConnections,
+			"devicesTotal":    devicesTotal,
 		})
 	}
 }

+ 7 - 0
server-go/internal/httpapi/httpapi_test.go

@@ -679,6 +679,13 @@ func TestHealthEndpoints(t *testing.T) {
 	if _, ok := body["uptimeSec"].(float64); !ok {
 		t.Fatalf("uptimeSec: %v", body)
 	}
+	// Métricas operativas (Fase 8): los 3 campos presentes; en demo los
+	// agentes/sse son 0 y devicesTotal viene del overview del poller demo.
+	for _, k := range []string{"agentsConnected", "sseConnections", "devicesTotal"} {
+		if _, ok := body[k].(float64); !ok {
+			t.Fatalf("%s ausente o no numérico: %v", k, body)
+		}
+	}
 	res = get(t, srv.URL, "/health", "")
 	body = readJSON(t, res)
 	if body["status"] != "ok" || body["db"] != "connected" {