hub_hol_test.go 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package sse
  2. import (
  3. "net/http"
  4. "testing"
  5. "time"
  6. "github.com/gnacho/netpulse/server-go/internal/auth"
  7. "github.com/gnacho/netpulse/server-go/internal/config"
  8. "github.com/gnacho/netpulse/server-go/internal/db"
  9. )
  10. // slowWriter es un ResponseWriter que bloquea la escritura (ventana TCP
  11. // llena): nunca completa Fprint, simula un cliente que no drena el socket.
  12. type slowWriter struct{}
  13. func (slowWriter) Header() http.Header { return http.Header{} }
  14. func (slowWriter) Write(p []byte) (int, error) {
  15. time.Sleep(2500 * time.Millisecond) // bloquea el write como un socket atascado
  16. return len(p), nil
  17. }
  18. func (slowWriter) WriteHeader(int) {}
  19. func (slowWriter) Flush() {}
  20. // chanWriter notifica por canal cuando recibe un write (sin compartir buffer
  21. // entre la goroutine de Broadcast y el test: evita la data race del recorder).
  22. type chanWriter struct {
  23. ch chan string
  24. }
  25. func (chanWriter) Header() http.Header { return http.Header{} }
  26. func (w chanWriter) Write(p []byte) (int, error) {
  27. w.ch <- string(p)
  28. return len(p), nil
  29. }
  30. func (chanWriter) WriteHeader(int) {}
  31. func (chanWriter) Flush() {}
  32. // TestBroadcastNoBloqueadoPorClienteLento reproduce el bug #200: un cliente
  33. // lento no debe bloquear la entrega del broadcast (el poller lanza el
  34. // broadcast desde su tick). Con el fix, Broadcast con un cliente lento y uno
  35. // rápido debe devolver en <2s y el rápido recibir el payload.
  36. func TestBroadcastNoBloqueadoPorClienteLento(t *testing.T) {
  37. d, err := db.Open(t.TempDir())
  38. if err != nil {
  39. t.Fatal(err)
  40. }
  41. defer d.Close()
  42. cfg := &config.Config{AuthUser: "admin", AuthPass: "test1234"}
  43. _, err = auth.EnsureSessionSecret(d, cfg)
  44. if err != nil {
  45. t.Fatal(err)
  46. }
  47. // Sesiones válidas para que Broadcast no descarte por revocada.
  48. fastSess := auth.CreateSession(d, "test", 1)
  49. slowSess := auth.CreateSession(d, "test", 1)
  50. // Cliente rápido (notifica por canal al recibir).
  51. fastRecv := make(chan string, 4)
  52. fast := &client{id: 1, sessionID: fastSess, w: chanWriter{ch: fastRecv}, flusher: chanWriter{ch: fastRecv}, done: make(chan struct{})}
  53. // Cliente lento (write bloqueante).
  54. slow := &client{id: 2, sessionID: slowSess, w: slowWriter{}, flusher: slowWriter{}, done: make(chan struct{})}
  55. h := NewHub(d, 10, nil)
  56. h.mu.Lock()
  57. h.clients[fast.id] = fast
  58. h.clients[slow.id] = slow
  59. h.mu.Unlock()
  60. start := time.Now()
  61. h.Broadcast("snapshot", map[string]any{"x": 1})
  62. elapsed := time.Since(start)
  63. // Broadcast debe volver pronto (no esperar al cliente lento).
  64. if elapsed > 2*time.Second {
  65. t.Fatalf("Broadcast bloqueado por el cliente lento: tardó %v", elapsed)
  66. }
  67. // El cliente rápido debe recibir el payload.
  68. select {
  69. case msg := <-fastRecv:
  70. if msg != "event: snapshot\ndata: {\"x\":1}\n\n" {
  71. t.Fatalf("payload inesperado: %q", msg)
  72. }
  73. case <-time.After(3 * time.Second):
  74. t.Fatal("el cliente rápido no recibió el snapshot")
  75. }
  76. }