store.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. package pathanalysis
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. "fmt"
  6. "time"
  7. "github.com/gnacho/netpulse/server-go/internal/db"
  8. )
  9. type Hop struct {
  10. Index int `json:"index"`
  11. Host string `json:"host"`
  12. LossPct float64 `json:"lossPct"`
  13. AvgMs float64 `json:"avgMs"`
  14. BestMs float64 `json:"bestMs"`
  15. WorstMs float64 `json:"worstMs"`
  16. StdevMs float64 `json:"stdevMs"`
  17. }
  18. type PathResult struct {
  19. ID int64 `json:"id"`
  20. RouterID string `json:"routerId"`
  21. Destination string `json:"destination"`
  22. TS int64 `json:"ts"`
  23. Hops []Hop `json:"hops"`
  24. HopCount int `json:"hopCount"`
  25. TotalMs float64 `json:"totalMs"`
  26. }
  27. type PathSummary struct {
  28. Destination string `json:"destination"`
  29. LastRun int64 `json:"lastRun"`
  30. HopCount int `json:"hopCount"`
  31. TotalMs float64 `json:"totalMs"`
  32. WorstHop int `json:"worstHop"`
  33. WorstLoss float64 `json:"worstLoss"`
  34. }
  35. type Store struct {
  36. db *db.DB
  37. }
  38. func NewStore(d *db.DB) *Store {
  39. return &Store{db: d}
  40. }
  41. func EnsureSchema(d *db.DB) error {
  42. _, err := d.Exec(`
  43. CREATE TABLE IF NOT EXISTS path_results (
  44. id INTEGER PRIMARY KEY AUTOINCREMENT,
  45. router_id TEXT NOT NULL,
  46. destination TEXT NOT NULL,
  47. ts INTEGER NOT NULL,
  48. hops_json TEXT NOT NULL,
  49. hop_count INTEGER NOT NULL,
  50. total_ms REAL NOT NULL DEFAULT 0
  51. );
  52. CREATE INDEX IF NOT EXISTS idx_path_results_lookup ON path_results(router_id, destination, ts DESC);
  53. `)
  54. return err
  55. }
  56. func (s *Store) Insert(r PathResult) error {
  57. hopsJSON, err := json.Marshal(r.Hops)
  58. if err != nil {
  59. return err
  60. }
  61. _, err = s.db.Exec(
  62. `INSERT INTO path_results (router_id, destination, ts, hops_json, hop_count, total_ms)
  63. VALUES (?, ?, ?, ?, ?, ?)`,
  64. r.RouterID, r.Destination, r.TS, string(hopsJSON), r.HopCount, r.TotalMs,
  65. )
  66. return err
  67. }
  68. func (s *Store) Latest(routerID, destination string) (*PathResult, error) {
  69. var r PathResult
  70. var hopsJSON string
  71. err := s.db.QueryRow(
  72. `SELECT id, router_id, destination, ts, hops_json, hop_count, total_ms
  73. FROM path_results WHERE router_id = ? AND destination = ?
  74. ORDER BY ts DESC LIMIT 1`,
  75. routerID, destination,
  76. ).Scan(&r.ID, &r.RouterID, &r.Destination, &r.TS, &hopsJSON, &r.HopCount, &r.TotalMs)
  77. if err != nil {
  78. return nil, err
  79. }
  80. if err := json.Unmarshal([]byte(hopsJSON), &r.Hops); err != nil {
  81. return nil, err
  82. }
  83. return &r, nil
  84. }
  85. func (s *Store) History(routerID, destination string, limit int) ([]PathResult, error) {
  86. if limit <= 0 || limit > 100 {
  87. limit = 20
  88. }
  89. rows, err := s.db.Query(
  90. `SELECT id, router_id, destination, ts, hops_json, hop_count, total_ms
  91. FROM path_results WHERE router_id = ? AND destination = ?
  92. ORDER BY ts DESC LIMIT ?`,
  93. routerID, destination, limit,
  94. )
  95. if err != nil {
  96. return nil, err
  97. }
  98. defer rows.Close()
  99. var out []PathResult
  100. for rows.Next() {
  101. var r PathResult
  102. var hopsJSON string
  103. if err := rows.Scan(&r.ID, &r.RouterID, &r.Destination, &r.TS, &hopsJSON, &r.HopCount, &r.TotalMs); err != nil {
  104. return nil, err
  105. }
  106. if err := json.Unmarshal([]byte(hopsJSON), &r.Hops); err != nil {
  107. continue
  108. }
  109. out = append(out, r)
  110. }
  111. return out, rows.Err()
  112. }
  113. func (s *Store) Summaries(routerID string) ([]PathSummary, error) {
  114. rows, err := s.db.Query(
  115. `SELECT destination, MAX(ts), hop_count, total_ms
  116. FROM path_results WHERE router_id = ?
  117. GROUP BY destination ORDER BY destination`,
  118. routerID,
  119. )
  120. if err != nil {
  121. return nil, err
  122. }
  123. defer rows.Close()
  124. var out []PathSummary
  125. for rows.Next() {
  126. var ps PathSummary
  127. if err := rows.Scan(&ps.Destination, &ps.LastRun, &ps.HopCount, &ps.TotalMs); err != nil {
  128. continue
  129. }
  130. out = append(out, ps)
  131. }
  132. if err := rows.Err(); err != nil {
  133. return nil, err
  134. }
  135. // Cerrar SIEMPRE el primer cursor antes de las queries anidadas: el
  136. // server corre con MaxOpenConns(1) y una query dentro del bucle de rows
  137. // abiertos es un deadlock (lo bloqueaba todo, incluido el CI de release).
  138. rows.Close()
  139. for i := range out {
  140. var hopsJSON string
  141. err := s.db.QueryRow(
  142. `SELECT hops_json FROM path_results WHERE router_id = ? AND destination = ? ORDER BY ts DESC LIMIT 1`,
  143. routerID, out[i].Destination,
  144. ).Scan(&hopsJSON)
  145. if err != nil {
  146. continue
  147. }
  148. var hops []Hop
  149. if json.Unmarshal([]byte(hopsJSON), &hops) != nil {
  150. continue
  151. }
  152. for _, h := range hops {
  153. if h.LossPct > out[i].WorstLoss {
  154. out[i].WorstLoss = h.LossPct
  155. out[i].WorstHop = h.Index
  156. }
  157. }
  158. }
  159. return out, nil
  160. }
  161. func (s *Store) AllDestinations() ([]string, error) {
  162. rows, err := s.db.Query("SELECT DISTINCT destination FROM path_results ORDER BY destination")
  163. if err != nil {
  164. return nil, err
  165. }
  166. defer rows.Close()
  167. var out []string
  168. for rows.Next() {
  169. var d string
  170. if err := rows.Scan(&d); err != nil {
  171. continue
  172. }
  173. out = append(out, d)
  174. }
  175. return out, rows.Err()
  176. }
  177. func (s *Store) Purge(olderThan time.Duration) (int64, error) {
  178. cutoff := db.NowMS() - olderThan.Milliseconds()
  179. res, err := s.db.Exec("DELETE FROM path_results WHERE ts < ?", cutoff)
  180. if err != nil {
  181. return 0, err
  182. }
  183. return res.RowsAffected()
  184. }
  185. var _ = sql.ErrNoRows
  186. var _ = fmt.Sprintf