health.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. devicesTotal := 0
  29. if s.lastOv != nil {
  30. if ov := s.lastOv(); ov != nil {
  31. devicesTotal = ov.DeviceTotals.Total
  32. }
  33. }
  34. writeJSON(w, http.StatusOK, map[string]any{
  35. "ok": dbOk,
  36. "version": Version,
  37. "mode": mode,
  38. "uptimeSec": int64(time.Since(s.started).Seconds()),
  39. "db": dbStatus,
  40. "agentsConnected": agentsConnected,
  41. "sseConnections": sseConnections,
  42. "devicesTotal": devicesTotal,
  43. })
  44. }
  45. }
  46. // handleHealth: {status, uptime (float segundos), memory:{rss, heap}, db}.
  47. // En Go los bytes salen de runtime.ReadMemStats: rss ≈ Sys (memoria obtenida
  48. // del SO) y heap ≈ HeapAlloc. Los valores absolutos cambian de lenguaje —
  49. // solo el shape es contrato (SPEC §2.2).
  50. func (s *server) handleHealth(w http.ResponseWriter, r *http.Request) {
  51. dbOk := s.db.CheckHealth()
  52. status, dbStatus := "ok", "connected"
  53. if !dbOk {
  54. status, dbStatus = "degraded", "error"
  55. }
  56. var mem runtime.MemStats
  57. runtime.ReadMemStats(&mem)
  58. writeJSON(w, http.StatusOK, map[string]any{
  59. "status": status,
  60. "uptime": time.Since(s.started).Seconds(),
  61. "memory": map[string]any{
  62. "rss": mem.Sys,
  63. "heap": mem.HeapAlloc,
  64. },
  65. "db": dbStatus,
  66. })
  67. }