sseclient_test.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. package sseclient
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/http/httptest"
  7. "testing"
  8. "time"
  9. )
  10. // #1859: un stream que llegó a traer datos reinicia el backoff aunque el corte
  11. // sea sucio (reinicio del servidor = EOF inesperado). Antes solo lo reiniciaba
  12. // un cierre limpio, así que cada despliegue doblaba la espera hasta 5 minutos.
  13. func TestConnectMarksEstablishedWhenTheStreamCarriesData(t *testing.T) {
  14. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  15. w.Header().Set("Content-Type", "text/event-stream")
  16. w.WriteHeader(http.StatusOK)
  17. fmt.Fprint(w, "event: connected\ndata: {}\n\n")
  18. w.(http.Flusher).Flush()
  19. panic(http.ErrAbortHandler) // corta la conexión como un reinicio
  20. }))
  21. defer srv.Close()
  22. c := &Client{
  23. url: srv.URL + "/api/agents/rt1/stream",
  24. token: "t",
  25. hc: srv.Client(),
  26. onEvent: func(Event) {},
  27. minRetry: 5 * time.Second,
  28. maxRetry: 5 * time.Minute,
  29. logf: func(string, ...any) {},
  30. }
  31. established, err := c.connect(context.Background())
  32. if !established {
  33. t.Fatal("un stream que trajo datos debe contar como establecido")
  34. }
  35. if err == nil {
  36. t.Fatal("un corte sucio debe devolver error de lectura")
  37. }
  38. if delay, next := c.retryDelay(5*time.Minute, established); delay != c.minRetry || next != c.minRetry {
  39. t.Fatalf("tras un stream establecido el backoff debe volver a %s, salió delay=%s next=%s",
  40. c.minRetry, delay, next)
  41. }
  42. }
  43. // Un cierre limpio también cuenta como establecido, y no hay error.
  44. func TestConnectMarksEstablishedOnCleanClose(t *testing.T) {
  45. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  46. w.Header().Set("Content-Type", "text/event-stream")
  47. w.WriteHeader(http.StatusOK)
  48. fmt.Fprint(w, "event: connected\ndata: {}\n\n")
  49. }))
  50. defer srv.Close()
  51. c := &Client{
  52. url: srv.URL + "/api/agents/rt1/stream",
  53. token: "t",
  54. hc: srv.Client(),
  55. onEvent: func(Event) {},
  56. minRetry: 5 * time.Second,
  57. maxRetry: 5 * time.Minute,
  58. logf: func(string, ...any) {},
  59. }
  60. established, err := c.connect(context.Background())
  61. if !established || err != nil {
  62. t.Fatalf("cierre limpio: established=%v err=%v, quería true/nil", established, err)
  63. }
  64. }
  65. // Si el servidor no responde no hubo stream: el backoff debe seguir creciendo.
  66. func TestConnectNotEstablishedWhenTheServerIsDown(t *testing.T) {
  67. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
  68. url := srv.URL
  69. srv.Close()
  70. c := &Client{
  71. url: url + "/api/agents/rt1/stream",
  72. token: "t",
  73. hc: &http.Client{Timeout: time.Second},
  74. onEvent: func(Event) {},
  75. minRetry: 5 * time.Second,
  76. maxRetry: 5 * time.Minute,
  77. logf: func(string, ...any) {},
  78. }
  79. established, err := c.connect(context.Background())
  80. if established {
  81. t.Fatal("sin servidor no hay stream establecido")
  82. }
  83. if err == nil {
  84. t.Fatal("sin servidor debe devolver error")
  85. }
  86. if delay, _ := c.retryDelay(10*time.Second, established); delay != 10*time.Second {
  87. t.Fatalf("un fallo debe mantener la espera actual, salió %s", delay)
  88. }
  89. }
  90. // #1563: una conexión que llegó a establecerse reinicia el backoff, sin
  91. // importar cuántos cortes limpios hubiera antes.
  92. func TestRetryDelayResetsAfterCleanDisconnect(t *testing.T) {
  93. c := &Client{minRetry: 5 * time.Second, maxRetry: 5 * time.Minute}
  94. for _, current := range []time.Duration{5 * time.Second, 40 * time.Second, 5 * time.Minute} {
  95. delay, next := c.retryDelay(current, true)
  96. if delay != c.minRetry || next != c.minRetry {
  97. t.Fatalf("corte limpio con current=%s: delay=%s next=%s, quería %s/%s",
  98. current, delay, next, c.minRetry, c.minRetry)
  99. }
  100. }
  101. }
  102. // Solo los fallos consecutivos hacen crecer la espera, y nunca por encima de
  103. // maxRetry.
  104. func TestRetryDelayGrowsOnFailures(t *testing.T) {
  105. c := &Client{minRetry: 5 * time.Second, maxRetry: 5 * time.Minute}
  106. cases := []struct {
  107. current time.Duration
  108. delay time.Duration
  109. next time.Duration
  110. }{
  111. {5 * time.Second, 5 * time.Second, 10 * time.Second},
  112. {10 * time.Second, 10 * time.Second, 20 * time.Second},
  113. {4 * time.Minute, 4 * time.Minute, 5 * time.Minute},
  114. {5 * time.Minute, 5 * time.Minute, 5 * time.Minute},
  115. }
  116. for _, tc := range cases {
  117. delay, next := c.retryDelay(tc.current, false)
  118. if delay != tc.delay || next != tc.next {
  119. t.Fatalf("fallo con current=%s: delay=%s next=%s, quería %s/%s",
  120. tc.current, delay, next, tc.delay, tc.next)
  121. }
  122. }
  123. }