h2_idle_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package sse
  2. // FORK: a stream served over HTTP/2 survives idle time past the write
  3. // deadline a single write needs.
  4. import (
  5. "bufio"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. "testing"
  10. "time"
  11. )
  12. func TestAStreamOverHTTP2OutlivesTheWriteDeadline(t *testing.T) {
  13. if testing.Short() {
  14. t.Skip("waits past the 10 s write deadline")
  15. }
  16. h := NewAgentHub(func(string, string) bool { return true })
  17. mux := http.NewServeMux()
  18. mux.HandleFunc("GET /api/agents/{slug}/stream", h.HandleStream)
  19. ts := httptest.NewUnstartedServer(mux)
  20. ts.EnableHTTP2 = true
  21. ts.StartTLS()
  22. defer ts.Close()
  23. req, _ := http.NewRequest("GET", ts.URL+"/api/agents/test-router/stream", nil)
  24. req.Header.Set("Authorization", "Bearer x")
  25. res, err := ts.Client().Do(req)
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. defer res.Body.Close()
  30. if res.ProtoMajor != 2 {
  31. t.Fatalf("served over HTTP/%d, the test needs HTTP/2", res.ProtoMajor)
  32. }
  33. lines := make(chan string, 16)
  34. go func() {
  35. sc := bufio.NewScanner(res.Body)
  36. for sc.Scan() {
  37. lines <- sc.Text()
  38. }
  39. close(lines)
  40. }()
  41. waitFor := func(want string, within time.Duration) bool {
  42. deadline := time.After(within)
  43. for {
  44. select {
  45. case l, ok := <-lines:
  46. if !ok {
  47. return false
  48. }
  49. if strings.Contains(l, want) {
  50. return true
  51. }
  52. case <-deadline:
  53. return false
  54. }
  55. }
  56. }
  57. if !waitFor("event: connected", 3*time.Second) {
  58. t.Fatal("no connected event")
  59. }
  60. time.Sleep(12 * time.Second) // past the 10 s a write's deadline allows
  61. if !h.Send("test-router", "ping", map[string]int{"n": 1}) {
  62. t.Fatal("the stream was gone after 12 s idle")
  63. }
  64. if !waitFor("event: ping", 3*time.Second) {
  65. t.Fatal("a command sent after 12 s idle never arrived")
  66. }
  67. }