sseclient.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. 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, err == nil)
  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. func (c *Client) retryDelay(current time.Duration, established bool) (delay, next time.Duration) {
  77. if established {
  78. return c.minRetry, c.minRetry
  79. }
  80. next = current * 2
  81. if next > c.maxRetry {
  82. next = c.maxRetry
  83. }
  84. return current, next
  85. }
  86. func (c *Client) connect(ctx context.Context) error {
  87. req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url, nil)
  88. if err != nil {
  89. return err
  90. }
  91. req.Header.Set("Authorization", "Bearer "+c.token)
  92. req.Header.Set("Accept", "text/event-stream")
  93. req.Header.Set("Cache-Control", "no-cache")
  94. res, err := c.hc.Do(req)
  95. if err != nil {
  96. return err
  97. }
  98. defer res.Body.Close()
  99. if res.StatusCode != http.StatusOK {
  100. return &httpError{res.StatusCode}
  101. }
  102. scanner := bufio.NewScanner(res.Body)
  103. scanner.Buffer(nil, 64<<10)
  104. var ev Event
  105. for scanner.Scan() {
  106. line := scanner.Text()
  107. // Comentario (heartbeat) — ignorar
  108. if strings.HasPrefix(line, ":") {
  109. continue
  110. }
  111. // Línea vacía = fin de evento
  112. if line == "" {
  113. if ev.Name != "" {
  114. c.onEvent(ev)
  115. ev = Event{}
  116. }
  117. continue
  118. }
  119. // Campo event:
  120. if strings.HasPrefix(line, "event: ") {
  121. ev.Name = line[7:]
  122. continue
  123. }
  124. // Campo data:
  125. if strings.HasPrefix(line, "data: ") {
  126. ev.Data = line[6:]
  127. continue
  128. }
  129. }
  130. return scanner.Err()
  131. }
  132. type httpError struct{ code int }
  133. func (e *httpError) Error() string { return http.StatusText(e.code) }