sseclient.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. // Package sseclient — cliente SSE del agente (Fase 7.3): mantiene una
  2. // conexión SSE abierta al servidor para recibir comandos (refresh, etc.).
  3. // Se reconecta automáticamente con backoff.
  4. package sseclient
  5. import (
  6. "bufio"
  7. "context"
  8. "net/http"
  9. "strings"
  10. "time"
  11. )
  12. // Event representa un comando recibido del servidor vía SSE.
  13. type Event struct {
  14. Name string // "refresh", "connected", "bye", etc.
  15. Data string // payload JSON (puede estar vacío)
  16. }
  17. // Client mantiene una conexión SSE al servidor y notifica comandos vía
  18. // callback. Se reconecta automáticamente con backoff (minRetry → maxRetry).
  19. type Client struct {
  20. url string
  21. token string
  22. hc *http.Client
  23. onEvent func(Event)
  24. minRetry time.Duration
  25. maxRetry time.Duration
  26. logf func(string, ...any)
  27. }
  28. // New crea un cliente SSE. serverURL es la URL base del servidor
  29. // (p. ej. "http://192.168.1.226:3000"). hc permite compartir el transporte
  30. // (incluido el pinning SPKI del agente); nil → http.Client por defecto.
  31. func New(serverURL, slug, token string, hc *http.Client, onEvent func(Event)) *Client {
  32. if hc == nil {
  33. hc = &http.Client{Timeout: 0}
  34. }
  35. return &Client{
  36. url: serverURL + "/api/agents/" + slug + "/stream",
  37. token: token,
  38. hc: hc,
  39. onEvent: onEvent,
  40. minRetry: 5 * time.Second,
  41. maxRetry: 5 * time.Minute,
  42. logf: func(string, ...any) {},
  43. }
  44. }
  45. // SetLogger enchufa el log.
  46. func (c *Client) SetLogger(f func(string, ...any)) { c.logf = f }
  47. // Run conecta al SSE y llama a onEvent por cada comando. Bloquea hasta que
  48. // ctx se cancele. Se reconecta automáticamente si la conexión cae. El backoff
  49. // se RESETEA tras una conexión que llegó a establecerse: solo crece mientras
  50. // los intentos fallan (si no, un agente que sobrevive a varios reinicios del
  51. // server acaba reintentando cada 5 min para siempre, #284).
  52. func (c *Client) Run(ctx context.Context) {
  53. retry := c.minRetry
  54. for {
  55. established, err := c.connect(ctx)
  56. if ctx.Err() != nil {
  57. return
  58. }
  59. if err != nil {
  60. c.logf("[netpulse-agent] SSE desconectado (%v), reintentando en %s", err, retry)
  61. }
  62. delay, next := c.retryDelay(retry, established)
  63. retry = next
  64. select {
  65. case <-ctx.Done():
  66. return
  67. case <-time.After(delay):
  68. }
  69. }
  70. }
  71. // retryDelay decide cuánto esperar antes del siguiente intento y el valor
  72. // acumulado para el siguiente fallo. Una conexión que llegó a establecerse
  73. // reinicia el backoff (#284); solo los fallos consecutivos lo hacen crecer
  74. // hasta maxRetry (#1563: el `retry *= 2` anterior también corría tras una
  75. // conexión limpia, así que el reinicio no servía de nada).
  76. // #1859: "establecerse" lo decide connect(), que devuelve si el stream llegó
  77. // a traer datos, no si terminó sin error. Un reinicio del servidor corta la
  78. // lectura con EOF inesperado, y antes eso contaba como fallo: cada despliegue
  79. // doblaba la espera hasta los cinco minutos.
  80. func (c *Client) retryDelay(current time.Duration, established bool) (delay, next time.Duration) {
  81. if established {
  82. return c.minRetry, c.minRetry
  83. }
  84. next = current * 2
  85. if next > c.maxRetry {
  86. next = c.maxRetry
  87. }
  88. return current, next
  89. }
  90. // connect abre el stream y lo consume hasta que se corta. Devuelve si llegó a
  91. // establecerse (respuesta 200 y al menos una línea leída) junto al error de
  92. // lectura, que es nil cuando el corte fue limpio.
  93. func (c *Client) connect(ctx context.Context) (bool, error) {
  94. req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url, nil)
  95. if err != nil {
  96. return false, err
  97. }
  98. req.Header.Set("Authorization", "Bearer "+c.token)
  99. req.Header.Set("Accept", "text/event-stream")
  100. req.Header.Set("Cache-Control", "no-cache")
  101. res, err := c.hc.Do(req)
  102. if err != nil {
  103. return false, err
  104. }
  105. defer res.Body.Close()
  106. if res.StatusCode != http.StatusOK {
  107. return false, &httpError{res.StatusCode}
  108. }
  109. scanner := bufio.NewScanner(res.Body)
  110. scanner.Buffer(nil, 64<<10)
  111. var ev Event
  112. established := false
  113. for scanner.Scan() {
  114. established = true
  115. line := scanner.Text()
  116. // Comentario (heartbeat) — ignorar
  117. if strings.HasPrefix(line, ":") {
  118. continue
  119. }
  120. // Línea vacía = fin de evento
  121. if line == "" {
  122. if ev.Name != "" {
  123. c.onEvent(ev)
  124. ev = Event{}
  125. }
  126. continue
  127. }
  128. // Campo event:
  129. if strings.HasPrefix(line, "event: ") {
  130. ev.Name = line[7:]
  131. continue
  132. }
  133. // Campo data:
  134. if strings.HasPrefix(line, "data: ") {
  135. ev.Data = line[6:]
  136. continue
  137. }
  138. }
  139. return established, scanner.Err()
  140. }
  141. type httpError struct{ code int }
  142. func (e *httpError) Error() string { return http.StatusText(e.code) }