|
3 | 3 | package websocket_test
|
4 | 4 |
|
5 | 5 | import (
|
| 6 | + "bufio" |
6 | 7 | "context"
|
7 | 8 | "crypto/rand"
|
8 | 9 | "io"
|
9 | 10 | "math/big"
|
| 11 | + "net" |
10 | 12 | "net/http"
|
11 | 13 | "net/http/httptest"
|
12 |
| - "strings" |
13 |
| - "sync/atomic" |
14 | 14 | "testing"
|
15 | 15 | "time"
|
16 | 16 |
|
17 | 17 | "cdr.dev/slog/sloggers/slogtest/assert"
|
18 |
| - "golang.org/x/xerrors" |
19 | 18 |
|
20 | 19 | "nhooyr.io/websocket"
|
21 | 20 | )
|
22 | 21 |
|
| 22 | +func goFn(fn func()) func() { |
| 23 | + done := make(chan struct{}) |
| 24 | + go func() { |
| 25 | + defer close(done) |
| 26 | + fn() |
| 27 | + }() |
| 28 | + |
| 29 | + return func() { |
| 30 | + <-done |
| 31 | + } |
| 32 | +} |
| 33 | + |
23 | 34 | func TestConn(t *testing.T) {
|
24 | 35 | t.Parallel()
|
25 | 36 |
|
26 | 37 | t.Run("json", func(t *testing.T) {
|
27 | 38 | t.Parallel()
|
28 | 39 |
|
29 |
| - s, closeFn := testEchoLoop(t) |
30 |
| - defer closeFn() |
| 40 | + for i := 0; i < 1; i++ { |
| 41 | + t.Run("", func(t *testing.T) { |
| 42 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 43 | + defer cancel() |
31 | 44 |
|
32 |
| - c, _ := dialWebSocket(t, s, nil) |
33 |
| - defer c.Close(websocket.StatusInternalError, "") |
34 |
| - |
35 |
| - c.SetReadLimit(1 << 30) |
36 |
| - |
37 |
| - for i := 0; i < 10; i++ { |
38 |
| - n := randInt(t, 1_048_576) |
39 |
| - echoJSON(t, c, n) |
40 |
| - } |
| 45 | + c1, c2 := websocketPipe(t) |
41 | 46 |
|
42 |
| - c.Close(websocket.StatusNormalClosure, "") |
43 |
| - }) |
44 |
| -} |
45 |
| - |
46 |
| -func testServer(tb testing.TB, fn func(w http.ResponseWriter, r *http.Request)) (s *httptest.Server, closeFn func()) { |
47 |
| - h := http.HandlerFunc(fn) |
48 |
| - if randInt(tb, 2) == 1 { |
49 |
| - s = httptest.NewTLSServer(h) |
50 |
| - } else { |
51 |
| - s = httptest.NewServer(h) |
52 |
| - } |
53 |
| - closeFn2 := wsgrace(s.Config) |
54 |
| - return s, func() { |
55 |
| - err := closeFn2() |
56 |
| - assert.Success(tb, "closeFn", err) |
57 |
| - } |
58 |
| -} |
| 47 | + wait := goFn(func() { |
| 48 | + err := echoLoop(ctx, c1) |
| 49 | + assertCloseStatus(t, websocket.StatusNormalClosure, err) |
| 50 | + }) |
| 51 | + defer wait() |
59 | 52 |
|
60 |
| -// grace wraps s.Handler to gracefully shutdown WebSocket connections. |
61 |
| -// The returned function must be used to close the server instead of s.Close. |
62 |
| -func wsgrace(s *http.Server) (closeFn func() error) { |
63 |
| - h := s.Handler |
64 |
| - var conns int64 |
65 |
| - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
66 |
| - atomic.AddInt64(&conns, 1) |
67 |
| - defer atomic.AddInt64(&conns, -1) |
| 53 | + c2.SetReadLimit(1 << 30) |
68 | 54 |
|
69 |
| - ctx, cancel := context.WithTimeout(r.Context(), time.Second*5) |
70 |
| - defer cancel() |
71 |
| - |
72 |
| - r = r.WithContext(ctx) |
| 55 | + for i := 0; i < 10; i++ { |
| 56 | + n := randInt(t, 131_072) |
| 57 | + echoJSON(t, c2, n) |
| 58 | + } |
73 | 59 |
|
74 |
| - h.ServeHTTP(w, r) |
| 60 | + c2.Close(websocket.StatusNormalClosure, "") |
| 61 | + }) |
| 62 | + } |
75 | 63 | })
|
| 64 | +} |
76 | 65 |
|
77 |
| - return func() error { |
78 |
| - ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
79 |
| - defer cancel() |
80 |
| - |
81 |
| - err := s.Shutdown(ctx) |
82 |
| - if err != nil { |
83 |
| - return xerrors.Errorf("server shutdown failed: %v", err) |
84 |
| - } |
| 66 | +type writerFunc func(p []byte) (int, error) |
85 | 67 |
|
86 |
| - t := time.NewTicker(time.Millisecond * 10) |
87 |
| - defer t.Stop() |
88 |
| - for { |
89 |
| - select { |
90 |
| - case <-t.C: |
91 |
| - if atomic.LoadInt64(&conns) == 0 { |
92 |
| - return nil |
93 |
| - } |
94 |
| - case <-ctx.Done(): |
95 |
| - return xerrors.Errorf("failed to wait for WebSocket connections: %v", ctx.Err()) |
96 |
| - } |
97 |
| - } |
98 |
| - } |
| 68 | +func (f writerFunc) Write(p []byte) (int, error) { |
| 69 | + return f(p) |
99 | 70 | }
|
100 | 71 |
|
101 | 72 | // echoLoop echos every msg received from c until an error
|
@@ -133,22 +104,74 @@ func echoLoop(ctx context.Context, c *websocket.Conn) error {
|
133 | 104 | }
|
134 | 105 | }
|
135 | 106 |
|
136 |
| -func wsURL(s *httptest.Server) string { |
137 |
| - return strings.Replace(s.URL, "http", "ws", 1) |
138 |
| -} |
139 |
| - |
140 |
| -func testEchoLoop(t testing.TB) (*httptest.Server, func()) { |
141 |
| - return testServer(t, func(w http.ResponseWriter, r *http.Request) { |
142 |
| - c := acceptWebSocket(t, r, w, nil) |
143 |
| - defer c.Close(websocket.StatusInternalError, "") |
144 |
| - |
145 |
| - err := echoLoop(r.Context(), c) |
146 |
| - assertCloseStatus(t, websocket.StatusNormalClosure, err) |
147 |
| - }) |
| 107 | +func randBool(t testing.TB) bool { |
| 108 | + return randInt(t, 2) == 1 |
148 | 109 | }
|
149 | 110 |
|
150 | 111 | func randInt(t testing.TB, max int) int {
|
151 | 112 | x, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
|
152 | 113 | assert.Success(t, "rand.Int", err)
|
153 | 114 | return int(x.Int64())
|
154 | 115 | }
|
| 116 | + |
| 117 | +type testHijacker struct { |
| 118 | + *httptest.ResponseRecorder |
| 119 | + serverConn net.Conn |
| 120 | + hijacked chan struct{} |
| 121 | +} |
| 122 | + |
| 123 | +var _ http.Hijacker = testHijacker{} |
| 124 | + |
| 125 | +func (hj testHijacker) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
| 126 | + close(hj.hijacked) |
| 127 | + return hj.serverConn, bufio.NewReadWriter(bufio.NewReader(hj.serverConn), bufio.NewWriter(hj.serverConn)), nil |
| 128 | +} |
| 129 | + |
| 130 | +func websocketPipe(t *testing.T) (*websocket.Conn, *websocket.Conn) { |
| 131 | + var serverConn *websocket.Conn |
| 132 | + tt := testTransport{ |
| 133 | + h: func(w http.ResponseWriter, r *http.Request) { |
| 134 | + serverConn = acceptWebSocket(t, r, w, nil) |
| 135 | + }, |
| 136 | + } |
| 137 | + |
| 138 | + dialOpts := &websocket.DialOptions{ |
| 139 | + HTTPClient: &http.Client{ |
| 140 | + Transport: tt, |
| 141 | + }, |
| 142 | + } |
| 143 | + |
| 144 | + clientConn, _, err := websocket.Dial(context.Background(), "ws://example.com", dialOpts) |
| 145 | + assert.Success(t, "websocket.Dial", err) |
| 146 | + |
| 147 | + if randBool(t) { |
| 148 | + return serverConn, clientConn |
| 149 | + } |
| 150 | + return clientConn, serverConn |
| 151 | +} |
| 152 | + |
| 153 | +type testTransport struct { |
| 154 | + h http.HandlerFunc |
| 155 | +} |
| 156 | + |
| 157 | +func (t testTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| 158 | + clientConn, serverConn := net.Pipe() |
| 159 | + |
| 160 | + hj := testHijacker{ |
| 161 | + ResponseRecorder: httptest.NewRecorder(), |
| 162 | + serverConn: serverConn, |
| 163 | + hijacked: make(chan struct{}), |
| 164 | + } |
| 165 | + |
| 166 | + done := make(chan struct{}) |
| 167 | + t.h.ServeHTTP(hj, r) |
| 168 | + |
| 169 | + select { |
| 170 | + case <-hj.hijacked: |
| 171 | + resp := hj.ResponseRecorder.Result() |
| 172 | + resp.Body = clientConn |
| 173 | + return resp, nil |
| 174 | + case <-done: |
| 175 | + return hj.ResponseRecorder.Result(), nil |
| 176 | + } |
| 177 | +} |
0 commit comments