4
0

push.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. // Package push — cliente HTTPS del agente (SPEC-AGENTE-PILOTO §2): POST del
  2. // payload a /api/ingest/agent con Bearer; si falla, backoff exponencial
  3. // 5 s → 5 min y buffer en RAM acotado (cap 100, drop-oldest + contador en
  4. // log; mismo patrón que el fix del buffer del collector). Stateless: el
  5. // buffer vive SOLO en memoria (nada en flash).
  6. package push
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/hmac"
  11. "crypto/sha256"
  12. "encoding/hex"
  13. "encoding/json"
  14. "fmt"
  15. "io"
  16. "net/http"
  17. "sync"
  18. "time"
  19. "github.com/gnacho/netpulse/agent/probe"
  20. )
  21. const (
  22. // MinBackoff / MaxBackoff: 5 s → 5 min (SPEC §2).
  23. MinBackoff = 5 * time.Second
  24. MaxBackoff = 5 * time.Minute
  25. // BufferCap: payloads retenidos en RAM durante una caída del servidor.
  26. BufferCap = 100
  27. // StaleAfter: un payload buffered con más edad que esto JAMÁS superará la
  28. // ventana anti-replay del server (maxTsDrift = 5 min): reintentarlo para
  29. // siempre convierte una caída >5 min en un deadlock (issue #680). Se
  30. // descarta en el drenado en vez de reintentarlo.
  31. StaleAfter = 4 * time.Minute
  32. )
  33. // Client empuja payloads con token, backoff y buffer acotado.
  34. type Client struct {
  35. url string
  36. token string
  37. hc *http.Client
  38. minBackoff time.Duration
  39. maxBackoff time.Duration
  40. bufCap int
  41. logf func(string, ...any)
  42. mu sync.Mutex
  43. backoff time.Duration
  44. buf []*probe.Payload
  45. dropped uint64
  46. droppedStale uint64
  47. }
  48. // New crea el cliente contra serverURL (p. ej. "https://192.168.8.1:3000")
  49. // con el token del equipo. hc nil → cliente por defecto con timeout 10 s.
  50. func New(serverURL, token string, hc *http.Client) *Client {
  51. if hc == nil {
  52. hc = &http.Client{Timeout: 10 * time.Second}
  53. }
  54. return &Client{
  55. url: serverURL + "/api/ingest/agent",
  56. token: token,
  57. hc: hc,
  58. minBackoff: MinBackoff, maxBackoff: MaxBackoff, bufCap: BufferCap,
  59. logf: func(string, ...any) {},
  60. }
  61. }
  62. // SetBackoffBounds ajusta los límites (tests; producción usa 5 s→5 min).
  63. func (c *Client) SetBackoffBounds(min, max time.Duration) { c.minBackoff, c.maxBackoff = min, max }
  64. // SetBufferCap ajusta el cap del buffer (tests).
  65. func (c *Client) SetBufferCap(n int) { c.bufCap = n }
  66. // SetLogger enchufa el log (stderr en producción).
  67. func (c *Client) SetLogger(f func(string, ...any)) { c.logf = f }
  68. // Dropped: payloads descartados por buffer lleno (drop-oldest).
  69. func (c *Client) Dropped() uint64 {
  70. c.mu.Lock()
  71. defer c.mu.Unlock()
  72. return c.dropped
  73. }
  74. // DroppedStale: payloads buffered descartados por superar StaleAfter (#680).
  75. func (c *Client) DroppedStale() uint64 {
  76. c.mu.Lock()
  77. defer c.mu.Unlock()
  78. return c.droppedStale
  79. }
  80. // Buffered: payloads pendientes de envío.
  81. func (c *Client) Buffered() int {
  82. c.mu.Lock()
  83. defer c.mu.Unlock()
  84. return len(c.buf)
  85. }
  86. // Delay: cuánto dormir hasta el próximo ciclo (max(interval, backoff)).
  87. func (c *Client) Delay(interval time.Duration) time.Duration {
  88. c.mu.Lock()
  89. defer c.mu.Unlock()
  90. if c.backoff > interval {
  91. return c.backoff
  92. }
  93. return interval
  94. }
  95. // Push envía el payload; si hay buffer pendiente lo drena primero (FIFO:
  96. // los payloads llevan su propio ts). Devuelve error si el payload quedó
  97. // buffered sin confirmar (el caller duerme Delay y reintenta en el próximo
  98. // ciclo — el payload NO se pierde mientras quepa en el buffer).
  99. func (c *Client) Push(ctx context.Context, p *probe.Payload) error {
  100. c.mu.Lock()
  101. if len(c.buf) > 0 {
  102. // Hay pendientes: drena primero (FIFO) y luego envía el nuevo; si el
  103. // drenado falla, el nuevo entra al buffer (drop-oldest si está lleno).
  104. if err := c.flushLocked(ctx); err != nil {
  105. c.enqueueLocked(p)
  106. c.mu.Unlock()
  107. return err
  108. }
  109. if err := c.post(ctx, p); err != nil {
  110. c.enqueueLocked(p)
  111. c.growBackoffLocked()
  112. c.mu.Unlock()
  113. return err
  114. }
  115. c.mu.Unlock()
  116. return nil
  117. }
  118. c.mu.Unlock()
  119. if err := c.post(ctx, p); err != nil {
  120. c.mu.Lock()
  121. c.enqueueLocked(p)
  122. c.growBackoffLocked()
  123. c.mu.Unlock()
  124. return err
  125. }
  126. c.mu.Lock()
  127. c.backoff = 0
  128. c.mu.Unlock()
  129. return nil
  130. }
  131. // enqueueLocked mete en el buffer con drop-oldest + contador en log.
  132. func (c *Client) enqueueLocked(p *probe.Payload) {
  133. if len(c.buf) >= c.bufCap {
  134. c.buf = c.buf[1:]
  135. c.dropped++
  136. c.logf("[netpulse-agent] buffer lleno (%d): descartado el payload más viejo (total descartados: %d)", c.bufCap, c.dropped)
  137. }
  138. c.buf = append(c.buf, p)
  139. }
  140. // flushLocked intenta drenar el buffer en orden; para al primer fallo. Los
  141. // heads más viejos que StaleAfter se descartan sin reintentar (#680): el
  142. // server los rechazaría con 401 stale_payload y bloquearían el drenado para
  143. // siempre.
  144. func (c *Client) flushLocked(ctx context.Context) error {
  145. posted := false
  146. for len(c.buf) > 0 {
  147. if staleSince(c.buf[0], time.Now()) {
  148. c.logf("[netpulse-agent] descartado payload buffered stale (ts %d, %s de edad, ventana anti-replay agotada; total descartados por stale: %d)",
  149. c.buf[0].Ts, time.Since(time.Unix(c.buf[0].Ts, 0)).Round(time.Second), c.droppedStale+1)
  150. c.buf = c.buf[1:]
  151. c.droppedStale++
  152. continue
  153. }
  154. if err := c.post(ctx, c.buf[0]); err != nil {
  155. c.growBackoffLocked()
  156. return err
  157. }
  158. posted = true
  159. c.buf = c.buf[1:]
  160. }
  161. // El backoff solo se resetea si hubo ALGÚN post con éxito: un drenado que
  162. // solo descartó stales no prueba que la conectividad se haya recuperado
  163. // (el siguiente post fresco decidirá).
  164. if posted {
  165. c.backoff = 0
  166. c.logf("[netpulse-agent] buffer drenado tras reconexión")
  167. }
  168. return nil
  169. }
  170. // growBackoffLocked: 5 s → 10 → 20 → … → 5 min (cap).
  171. func (c *Client) growBackoffLocked() {
  172. if c.backoff == 0 {
  173. c.backoff = c.minBackoff
  174. return
  175. }
  176. c.backoff *= 2
  177. if c.backoff > c.maxBackoff {
  178. c.backoff = c.maxBackoff
  179. }
  180. }
  181. // staleSince: true si el payload lleva más de StaleAfter generado (un Ts no
  182. // positivo se considera siempre fresco: no hay dato para valorar).
  183. func staleSince(p *probe.Payload, now time.Time) bool {
  184. if p.Ts <= 0 {
  185. return false
  186. }
  187. return now.Sub(time.Unix(p.Ts, 0)) > StaleAfter
  188. }
  189. // hmacSign devuelve HMAC-SHA256(token, body) en hex.
  190. func hmacSign(token string, body []byte) string {
  191. mac := hmac.New(sha256.New, []byte(token))
  192. mac.Write(body)
  193. return hex.EncodeToString(mac.Sum(nil))
  194. }
  195. // post hace el POST con Bearer + HMAC; error si no hay 2xx.
  196. func (c *Client) post(ctx context.Context, p *probe.Payload) error {
  197. body, err := json.Marshal(p)
  198. if err != nil {
  199. return err
  200. }
  201. req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(body))
  202. if err != nil {
  203. return err
  204. }
  205. req.Header.Set("Content-Type", "application/json")
  206. req.Header.Set("Authorization", "Bearer "+c.token)
  207. req.Header.Set("X-Agent-Signature", hmacSign(c.token, body))
  208. res, err := c.hc.Do(req)
  209. if err != nil {
  210. return err
  211. }
  212. defer res.Body.Close()
  213. _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<16))
  214. if res.StatusCode < 200 || res.StatusCode > 299 {
  215. return fmt.Errorf("ingest HTTP %d", res.StatusCode)
  216. }
  217. return nil
  218. }