push.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. )
  28. // Client empuja payloads con token, backoff y buffer acotado.
  29. type Client struct {
  30. url string
  31. token string
  32. hc *http.Client
  33. minBackoff time.Duration
  34. maxBackoff time.Duration
  35. bufCap int
  36. logf func(string, ...any)
  37. mu sync.Mutex
  38. backoff time.Duration
  39. buf []*probe.Payload
  40. dropped uint64
  41. }
  42. // New crea el cliente contra serverURL (p. ej. "https://192.168.8.1:3000")
  43. // con el token del equipo. hc nil → cliente por defecto con timeout 10 s.
  44. func New(serverURL, token string, hc *http.Client) *Client {
  45. if hc == nil {
  46. hc = &http.Client{Timeout: 10 * time.Second}
  47. }
  48. return &Client{
  49. url: serverURL + "/api/ingest/agent",
  50. token: token,
  51. hc: hc,
  52. minBackoff: MinBackoff, maxBackoff: MaxBackoff, bufCap: BufferCap,
  53. logf: func(string, ...any) {},
  54. }
  55. }
  56. // SetBackoffBounds ajusta los límites (tests; producción usa 5 s→5 min).
  57. func (c *Client) SetBackoffBounds(min, max time.Duration) { c.minBackoff, c.maxBackoff = min, max }
  58. // SetBufferCap ajusta el cap del buffer (tests).
  59. func (c *Client) SetBufferCap(n int) { c.bufCap = n }
  60. // SetLogger enchufa el log (stderr en producción).
  61. func (c *Client) SetLogger(f func(string, ...any)) { c.logf = f }
  62. // Dropped: payloads descartados por buffer lleno (drop-oldest).
  63. func (c *Client) Dropped() uint64 {
  64. c.mu.Lock()
  65. defer c.mu.Unlock()
  66. return c.dropped
  67. }
  68. // Buffered: payloads pendientes de envío.
  69. func (c *Client) Buffered() int {
  70. c.mu.Lock()
  71. defer c.mu.Unlock()
  72. return len(c.buf)
  73. }
  74. // Delay: cuánto dormir hasta el próximo ciclo (max(interval, backoff)).
  75. func (c *Client) Delay(interval time.Duration) time.Duration {
  76. c.mu.Lock()
  77. defer c.mu.Unlock()
  78. if c.backoff > interval {
  79. return c.backoff
  80. }
  81. return interval
  82. }
  83. // Push envía el payload; si hay buffer pendiente lo drena primero (FIFO:
  84. // los payloads llevan su propio ts). Devuelve error si el payload quedó
  85. // buffered sin confirmar (el caller duerme Delay y reintenta en el próximo
  86. // ciclo — el payload NO se pierde mientras quepa en el buffer).
  87. func (c *Client) Push(ctx context.Context, p *probe.Payload) error {
  88. c.mu.Lock()
  89. if len(c.buf) > 0 {
  90. // Hay pendientes: drena primero (FIFO) y luego envía el nuevo; si el
  91. // drenado falla, el nuevo entra al buffer (drop-oldest si está lleno).
  92. if err := c.flushLocked(ctx); err != nil {
  93. c.enqueueLocked(p)
  94. c.mu.Unlock()
  95. return err
  96. }
  97. if err := c.post(ctx, p); err != nil {
  98. c.enqueueLocked(p)
  99. c.growBackoffLocked()
  100. c.mu.Unlock()
  101. return err
  102. }
  103. c.mu.Unlock()
  104. return nil
  105. }
  106. c.mu.Unlock()
  107. if err := c.post(ctx, p); err != nil {
  108. c.mu.Lock()
  109. c.enqueueLocked(p)
  110. c.growBackoffLocked()
  111. c.mu.Unlock()
  112. return err
  113. }
  114. c.mu.Lock()
  115. c.backoff = 0
  116. c.mu.Unlock()
  117. return nil
  118. }
  119. // enqueueLocked mete en el buffer con drop-oldest + contador en log.
  120. func (c *Client) enqueueLocked(p *probe.Payload) {
  121. if len(c.buf) >= c.bufCap {
  122. c.buf = c.buf[1:]
  123. c.dropped++
  124. c.logf("[netpulse-agent] buffer lleno (%d): descartado el payload más viejo (total descartados: %d)", c.bufCap, c.dropped)
  125. }
  126. c.buf = append(c.buf, p)
  127. }
  128. // flushLocked intenta drenar el buffer en orden; para al primer fallo.
  129. func (c *Client) flushLocked(ctx context.Context) error {
  130. for len(c.buf) > 0 {
  131. if err := c.post(ctx, c.buf[0]); err != nil {
  132. c.growBackoffLocked()
  133. return err
  134. }
  135. c.buf = c.buf[1:]
  136. }
  137. c.backoff = 0
  138. c.logf("[netpulse-agent] buffer drenado tras reconexión")
  139. return nil
  140. }
  141. // growBackoffLocked: 5 s → 10 → 20 → … → 5 min (cap).
  142. func (c *Client) growBackoffLocked() {
  143. if c.backoff == 0 {
  144. c.backoff = c.minBackoff
  145. return
  146. }
  147. c.backoff *= 2
  148. if c.backoff > c.maxBackoff {
  149. c.backoff = c.maxBackoff
  150. }
  151. }
  152. // hmacSign devuelve HMAC-SHA256(token, body) en hex.
  153. func hmacSign(token string, body []byte) string {
  154. mac := hmac.New(sha256.New, []byte(token))
  155. mac.Write(body)
  156. return hex.EncodeToString(mac.Sum(nil))
  157. }
  158. // post hace el POST con Bearer + HMAC; error si no hay 2xx.
  159. func (c *Client) post(ctx context.Context, p *probe.Payload) error {
  160. body, err := json.Marshal(p)
  161. if err != nil {
  162. return err
  163. }
  164. req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(body))
  165. if err != nil {
  166. return err
  167. }
  168. req.Header.Set("Content-Type", "application/json")
  169. req.Header.Set("Authorization", "Bearer "+c.token)
  170. req.Header.Set("X-Agent-Signature", hmacSign(c.token, body))
  171. res, err := c.hc.Do(req)
  172. if err != nil {
  173. return err
  174. }
  175. defer res.Body.Close()
  176. _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<16))
  177. if res.StatusCode < 200 || res.StatusCode > 299 {
  178. return fmt.Errorf("ingest HTTP %d", res.StatusCode)
  179. }
  180. return nil
  181. }