reports.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // reports.go — GET /api/reports/weekly: informe de disponibilidad semanal.
  2. // Calculado de metrics_daily (rollup nocturno de Fase 8.3): un daily por
  3. // router y día con el nº de muestras recolectadas (n), medias de
  4. // latencia/cpu/ram y totales de tráfico. El corte temporal (semana ISO
  5. // lunes-domingo) se normaliza aquí para que el frontend no haga aritmética
  6. // de fechas.
  7. //
  8. // Semántica de disponibilidad (verificada contra datos reales de prod):
  9. // - `n` = suma de muestras del día (poll de 5 s; día completo ≈ 17280).
  10. // - minutos de recolección = n * 5 / 60.
  11. // - upPct = minutos / (días con datos * 1440), clavado a 100 (issue #207):
  12. // un bucket sobre-poblado (más muestras que minutos) no puede superar el
  13. // 100%, igual que availability. La semana en curso queda parcial y se
  14. // normaliza solo sobre los días que tienen datos.
  15. // - `up_count` del daily NO es fiable como base (es COUNT(*) de filas
  16. // bucket, que en prod coincide con muestras porque el rollup no agrega);
  17. // `up_min` del daily es MIN(min_ts) (timestamp), no minutos.
  18. package httpapi
  19. import (
  20. "database/sql"
  21. "fmt"
  22. "net/http"
  23. "strconv"
  24. "time"
  25. )
  26. // weeklyReportEntry es una fila del informe: un router durante una semana.
  27. type weeklyReportEntry struct {
  28. RouterID string `json:"routerId"`
  29. Week string `json:"week"` // semana ISO, formato "2026-W31" (lunes-domingo)
  30. Days int `json:"days"` // días con datos en esa semana (≤7)
  31. UpMin int64 `json:"upMin"` // minutos de recolección en la semana
  32. UpPct float64 `json:"upPct"` // % de disponibilidad sobre los días con datos
  33. LatAvg *float64 `json:"latAvg"` // media de latencia (null si no hay datos)
  34. RxTotal float64 `json:"rxTotal"`
  35. TxTotal float64 `json:"txTotal"`
  36. CPUAvg float64 `json:"cpuAvg"`
  37. RAMAvg float64 `json:"ramAvg"`
  38. }
  39. // handleWeeklyReport sirve GET /api/reports/weekly?weeks=4. weeks ∈ [1,52].
  40. func (s *server) handleWeeklyReport(w http.ResponseWriter, r *http.Request) {
  41. weeks := 4
  42. if raw := r.URL.Query().Get("weeks"); raw != "" {
  43. n, err := strconv.Atoi(raw)
  44. if err != nil || n < 1 || n > 52 {
  45. writeError(w, http.StatusBadRequest, "invalid_query", "weeks must be an integer between 1 and 52")
  46. return
  47. }
  48. weeks = n
  49. }
  50. // El daily se agrupa por día UTC (unixepoch en el rollup). La ventana se
  51. // recorta con la fecha UTC de hoy; la semana en curso queda parcial y
  52. // upPct se calcula solo sobre los días con datos (no penaliza).
  53. since := time.Now().UTC().AddDate(0, 0, -7*weeks).Format("2006-01-02")
  54. rows, err := s.db.Query(`
  55. SELECT
  56. router_id,
  57. strftime('%G-W%V', date) AS week,
  58. COUNT(*),
  59. SUM(n) * 5 / 60,
  60. AVG(lat_avg),
  61. SUM(rx_total),
  62. SUM(tx_total),
  63. AVG(cpu_avg),
  64. AVG(ram_avg)
  65. FROM metrics_daily
  66. WHERE date >= ?
  67. GROUP BY router_id, strftime('%G-W%V', date)
  68. ORDER BY week DESC, router_id`, since)
  69. if err != nil {
  70. writeError(w, http.StatusInternalServerError, "db_error")
  71. return
  72. }
  73. defer rows.Close()
  74. out := []weeklyReportEntry{}
  75. for rows.Next() {
  76. var e weeklyReportEntry
  77. var upMin int64
  78. var lat sql.NullFloat64
  79. if err := rows.Scan(&e.RouterID, &e.Week, &e.Days, &upMin,
  80. &lat, &e.RxTotal, &e.TxTotal, &e.CPUAvg, &e.RAMAvg); err != nil {
  81. continue
  82. }
  83. e.UpMin = upMin
  84. if lat.Valid {
  85. e.LatAvg = &lat.Float64
  86. }
  87. if e.Days > 0 {
  88. e.UpPct = float64(upMin) / (float64(e.Days) * 24 * 60) * 100
  89. if e.UpPct > 100 {
  90. e.UpPct = 100
  91. }
  92. }
  93. out = append(out, e)
  94. }
  95. if err := rows.Err(); err != nil {
  96. writeError(w, http.StatusInternalServerError, "db_error")
  97. return
  98. }
  99. writeJSON(w, http.StatusOK, map[string]any{"items": out, "weeks": weeks})
  100. }
  101. // ---------------------------------------------------------------------------
  102. // GET /api/reports/availability?range=day|week|month&n=N — Fase 15.1
  103. //
  104. // Disponibilidad por router agregada por día, semana ISO o mes, sobre los
  105. // últimos N buckets (day: 30, week: 8, month: 12 por defecto). Reutiliza la
  106. // semántica de upMin/upPct del weekly. El día actual parcial se normaliza por
  107. // los minutos transcurridos (no penaliza); el mes en curso, por días con datos.
  108. // ---------------------------------------------------------------------------
  109. type availabilityEntry struct {
  110. RouterID string `json:"routerId"`
  111. Bucket string `json:"bucket"` // day "2026-08-07" | week "2026-W31" | month "2026-07"
  112. Days int `json:"days"` // días con datos en el bucket
  113. UpMin int64 `json:"upMin"` // minutos de recolección en el bucket
  114. UpPct float64 `json:"upPct"` // % de disponibilidad
  115. LatAvg *float64 `json:"latAvg"`
  116. RxTotal float64 `json:"rxTotal"`
  117. TxTotal float64 `json:"txTotal"`
  118. CPUAvg float64 `json:"cpuAvg"`
  119. RAMAvg float64 `json:"ramAvg"`
  120. }
  121. // handleAvailabilityReport sirve GET /api/reports/availability.
  122. func (s *server) handleAvailabilityReport(w http.ResponseWriter, r *http.Request) {
  123. q := r.URL.Query()
  124. rangeParam := q.Get("range")
  125. if rangeParam == "" {
  126. rangeParam = "week"
  127. }
  128. // Expresión SQL de agrupación + ventana por defecto según el rango.
  129. var groupExpr string
  130. nDef, nMax := 8, 52
  131. switch rangeParam {
  132. case "day":
  133. groupExpr = "strftime('%Y-%m-%d', date)"
  134. nDef, nMax = 30, 90
  135. case "week":
  136. groupExpr = "strftime('%G-W%V', date)"
  137. nDef, nMax = 8, 52
  138. case "month":
  139. groupExpr = "strftime('%Y-%m', date)"
  140. nDef, nMax = 12, 24
  141. default:
  142. writeError(w, http.StatusBadRequest, "invalid_query", "range must be day, week or month")
  143. return
  144. }
  145. n := nDef
  146. if raw := q.Get("n"); raw != "" {
  147. v, err := strconv.Atoi(raw)
  148. if err != nil || v < 1 || v > nMax {
  149. writeError(w, http.StatusBadRequest, "invalid_query",
  150. fmt.Sprintf("n must be an integer between 1 and %d", nMax))
  151. return
  152. }
  153. n = v
  154. }
  155. // Ventana hacia atrás desde hoy (UTC).
  156. now := time.Now().UTC()
  157. var since string
  158. switch rangeParam {
  159. case "day":
  160. since = now.AddDate(0, 0, -n).Format("2006-01-02")
  161. case "week":
  162. since = now.AddDate(0, 0, -7*n).Format("2006-01-02")
  163. case "month":
  164. since = now.AddDate(0, -n, 0).Format("2006-01-02")
  165. }
  166. query := fmt.Sprintf(`
  167. SELECT
  168. router_id,
  169. %s AS bucket,
  170. COUNT(*),
  171. SUM(n) * 5 / 60,
  172. AVG(lat_avg),
  173. SUM(rx_total),
  174. SUM(tx_total),
  175. AVG(cpu_avg),
  176. AVG(ram_avg)
  177. FROM metrics_daily
  178. WHERE date >= ?
  179. GROUP BY router_id, %s
  180. ORDER BY bucket DESC, router_id`, groupExpr, groupExpr)
  181. rows, err := s.db.Query(query, since)
  182. if err != nil {
  183. writeError(w, http.StatusInternalServerError, "db_error")
  184. return
  185. }
  186. defer rows.Close()
  187. // Para el día actual parcial: divisor = minutos transcurridos del día UTC.
  188. today := now.Format("2006-01-02")
  189. nowMin := now.Hour()*60 + now.Minute()
  190. out := []availabilityEntry{}
  191. for rows.Next() {
  192. var e availabilityEntry
  193. var upMin int64
  194. var lat sql.NullFloat64
  195. if err := rows.Scan(&e.RouterID, &e.Bucket, &e.Days, &upMin,
  196. &lat, &e.RxTotal, &e.TxTotal, &e.CPUAvg, &e.RAMAvg); err != nil {
  197. continue
  198. }
  199. e.UpMin = upMin
  200. if lat.Valid {
  201. e.LatAvg = &lat.Float64
  202. }
  203. var divisor float64
  204. if rangeParam == "day" {
  205. if e.Bucket == today && nowMin > 0 {
  206. divisor = float64(nowMin)
  207. } else {
  208. divisor = 1440
  209. }
  210. } else {
  211. divisor = float64(e.Days) * 1440
  212. }
  213. if divisor > 0 {
  214. e.UpPct = float64(upMin) / divisor * 100
  215. if e.UpPct > 100 {
  216. e.UpPct = 100
  217. }
  218. }
  219. out = append(out, e)
  220. }
  221. if err := rows.Err(); err != nil {
  222. writeError(w, http.StatusInternalServerError, "db_error")
  223. return
  224. }
  225. writeJSON(w, http.StatusOK, map[string]any{"items": out, "range": rangeParam, "n": n})
  226. }