health.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // health.go — GET /api/health (público, contrato) y GET /health (SPEC §2.1/§2.2).
  2. package httpapi
  3. import (
  4. "net/http"
  5. "runtime"
  6. "time"
  7. )
  8. // handleAPIHealth: {ok, version, mode, uptimeSec, db, agentsConnected,
  9. // sseConnections, devicesTotal}.
  10. func (s *server) handleAPIHealth(mode string) http.HandlerFunc {
  11. return func(w http.ResponseWriter, r *http.Request) {
  12. dbOk := s.db.CheckHealth()
  13. dbStatus := "ok"
  14. if !dbOk {
  15. dbStatus = "error"
  16. }
  17. // Métricas operativas (Fase 8): agentes vivos (dentro de TTL),
  18. // clientes SSE conectados y total de dispositivos del último
  19. // overview del poller. Nil-safe: demo/sin datos → 0.
  20. agentsConnected := 0
  21. if s.agents != nil {
  22. agentsConnected = s.agents.ActiveCount()
  23. }
  24. sseConnections := 0
  25. if s.hub != nil {
  26. sseConnections = s.hub.Size()
  27. }
  28. // #681: los agentes conectan por el AgentHub (SSE bidireccional),
  29. // distinto del hub de UI. Sin este conteo, con toda la flota de
  30. // agentes empujando el health solo refleja las pestañas abiertas.
  31. agentSseConnections := 0
  32. if s.agentHub != nil {
  33. agentSseConnections = len(s.agentHub.ConnectedSlugs())
  34. }
  35. devicesTotal := 0
  36. if s.lastOv != nil {
  37. if ov := s.lastOv(); ov != nil {
  38. devicesTotal = ov.DeviceTotals.Total
  39. }
  40. }
  41. writeJSON(w, http.StatusOK, map[string]any{
  42. "ok": dbOk,
  43. "version": Version,
  44. "mode": mode,
  45. "uptimeSec": int64(time.Since(s.started).Seconds()),
  46. "db": dbStatus,
  47. "agentsConnected": agentsConnected,
  48. "sseConnections": sseConnections,
  49. "agentSseConnections": agentSseConnections,
  50. "devicesTotal": devicesTotal,
  51. })
  52. }
  53. }
  54. // handleHealth: {status, uptime (float segundos), memory:{rss, heap}, db}.
  55. // En Go los bytes salen de runtime.ReadMemStats: rss ≈ Sys (memoria obtenida
  56. // del SO) y heap ≈ HeapAlloc. Los valores absolutos cambian de lenguaje —
  57. // solo el shape es contrato (SPEC §2.2).
  58. func (s *server) handleHealth(w http.ResponseWriter, r *http.Request) {
  59. dbOk := s.db.CheckHealth()
  60. status, dbStatus := "ok", "connected"
  61. if !dbOk {
  62. status, dbStatus = "degraded", "error"
  63. }
  64. var mem runtime.MemStats
  65. runtime.ReadMemStats(&mem)
  66. writeJSON(w, http.StatusOK, map[string]any{
  67. "status": status,
  68. "uptime": time.Since(s.started).Seconds(),
  69. "memory": map[string]any{
  70. "rss": mem.Sys,
  71. "heap": mem.HeapAlloc,
  72. },
  73. "db": dbStatus,
  74. })
  75. }