Repository navigation
Expand file tree
/
Copy pathasync_header_test.go
More file actions
347 lines (337 loc) · 10.5 KB
/
Copy pathasync_header_test.go
File metadata and controls
347 lines (337 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//go:build linux || darwin || dragonfly || freebsd || netbsd || openbsd || windows
package http
import (
"bytes"
"context"
"io"
stdhttp "net/http"
"runtime"
"strings"
"sync/atomic"
"testing"
"time"
)
// asyncHeaderLater resumes after d on a goroutine of its own, having set
// X-Async in the header, as a hook handing its work to a pool does.
func asyncHeaderLater(d time.Duration, err error) func(int, stdhttp.Header, func(error)) {
return func(status int, h stdhttp.Header, resume func(error)) {
go func() {
time.Sleep(d)
h.Set("X-Async", "set")
resume(err)
}()
}
}
// TestOnHeaderAsync has a response written each way a handler writes one,
// with its header held by an OnHeaderAsync hook that resumes after the
// handler has returned, and checks over HTTP/1 and HTTP/2 that the header
// carries what the hook set, after the hooks registered after it and before
// those registered before it, and the body is whole.
func TestOnHeaderAsync(t *testing.T) {
long := strings.Repeat("y", 200*1000) // three times what is held
write := map[string]struct {
body string
fn func(c *Context)
}{
"respond": {"body", func(c *Context) {
body := []byte("body")
_ = c.Respond(stdhttp.StatusAccepted, "text/plain", body)
// The held response has a copy of its own.
copy(body, "XXXX")
}},
"writer": {"bo" + "dy", func(c *Context) {
c.WriteHeader(stdhttp.StatusAccepted)
_, _ = io.WriteString(c, "bo")
c.Flush()
_, _ = io.WriteString(c, "dy")
}},
"long": {long, func(c *Context) {
// Past what is held, Write waits for the resume.
c.WriteHeader(stdhttp.StatusAccepted)
for i := 0; i < len(long); i += 1000 {
_, _ = io.WriteString(c, long[i:i+1000])
}
}},
"nothing": {"", func(c *Context) { c.WriteHeader(stdhttp.StatusAccepted) }},
}
addr := serve(t, NewHandler(HandlerFunc(func(c *Context) {
var order []string
c.OnHeader(func(status int, h stdhttp.Header) {
order = append(order, "outer:"+h.Get("X-Async"))
h.Set("X-Order", strings.Join(order, ","))
})
c.OnHeaderAsync(asyncHeaderLater(50*time.Millisecond, nil))
c.OnHeader(func(status int, h stdhttp.Header) {
order = append(order, "inner:"+h.Get("X-Async"))
})
write[strings.TrimPrefix(c.Request.URL.Path, "/")].fn(c)
})))
for _, client := range hookClients(t) {
for name, tt := range write {
t.Run(client.proto+"/"+name, func(t *testing.T) {
resp, err := client.Get("http://" + addr + "/" + name)
if err != nil {
t.Fatal(err)
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != stdhttp.StatusAccepted || resp.Proto != client.proto {
t.Fatalf("%s %d", resp.Proto, resp.StatusCode)
}
if got := resp.Header.Get("X-Async"); got != "set" {
t.Fatalf("X-Async %q", got)
}
if got := resp.Header.Get("X-Order"); got != "inner:,outer:set" {
t.Fatalf("X-Order %q", got)
}
if string(body) != tt.body {
t.Fatalf("body of %d bytes, want %d", len(body), len(tt.body))
}
})
}
}
}
// TestOnHeaderAsyncResumesInPlace checks that a hook that resumes from
// inside its call, as one that decides at once does, sends the response as
// an OnHeader hook would have.
func TestOnHeaderAsyncResumesInPlace(t *testing.T) {
addr := serve(t, NewHandler(HandlerFunc(func(c *Context) {
c.OnHeaderAsync(func(status int, h stdhttp.Header, resume func(error)) {
h.Set("X-Async", "now")
resume(nil)
resume(nil)
})
if c.Request.URL.Path == "/writer" {
_, _ = io.WriteString(c, "writer")
return
}
_ = c.Respond(stdhttp.StatusOK, "text/plain", []byte("respond"))
})))
for _, client := range hookClients(t) {
for _, path := range []string{"writer", "respond"} {
resp, err := client.Get("http://" + addr + "/" + path)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.Header.Get("X-Async") != "now" || string(body) != path {
t.Fatalf("%s /%s: %v %q", client.proto, path, resp.Header, body)
}
}
}
}
// TestOnHeaderAsyncFails checks that a hook resuming with an error fails the
// response: the HTTP/1 connection closes, and the HTTP/2 stream is reset,
// with nothing sent.
func TestOnHeaderAsyncFails(t *testing.T) {
addr := serve(t, NewHandler(HandlerFunc(func(c *Context) {
c.OnHeaderAsync(asyncHeaderLater(10*time.Millisecond, io.ErrUnexpectedEOF))
if c.Request.URL.Path == "/writer" {
_, _ = io.WriteString(c, "writer")
return
}
_ = c.Respond(stdhttp.StatusOK, "text/plain", []byte("respond"))
})))
for _, client := range hookClients(t) {
for _, path := range []string{"writer", "respond"} {
resp, err := client.Get("http://" + addr + "/" + path)
if err == nil {
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf("%s /%s answered %d %q", client.proto, path, resp.StatusCode, body)
}
}
}
}
// TestOnHeaderAsyncFailsWhileWriting has a hook's resume fail the response
// on another goroutine while the handler goes on writing and flushing, which
// must not race: every write after the failure reports it.
func TestOnHeaderAsyncFailsWhileWriting(t *testing.T) {
failed := make(chan error, 1)
addr := serve(t, NewHandler(HandlerFunc(func(c *Context) {
start := make(chan struct{})
c.OnHeaderAsync(func(status int, h stdhttp.Header, resume func(error)) {
go func() {
<-start
resume(io.ErrUnexpectedEOF)
}()
})
c.WriteHeader(stdhttp.StatusOK)
c.Flush()
close(start)
var err error
for i := 0; i < 1000 && err == nil; i++ {
switch i % 3 {
case 0:
_, err = c.Write([]byte("x"))
case 1:
_, err = c.WriteNoWait([]byte("x"))
default:
err = c.FlushError()
}
runtime.Gosched()
}
for err == nil {
// Held, the writes went on; once the resume has run, they fail.
_, err = c.Write([]byte("x"))
runtime.Gosched()
}
failed <- err
})))
for _, client := range hookClients(t) {
resp, err := client.Get("http://" + addr + "/")
if err == nil {
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf("%s answered %d %q", client.proto, resp.StatusCode, body)
}
select {
case err := <-failed:
if err != io.ErrUnexpectedEOF {
t.Errorf("%s: the handler's writes failed with %v, want %v", client.proto, err, io.ErrUnexpectedEOF)
}
case <-time.After(10 * time.Second):
t.Fatalf("%s: the handler never saw its response fail", client.proto)
}
}
}
// TestOnHeaderAsyncNoWait checks that WriteNoWait reports above once more
// than is held is written while the header is held, and that the function
// OnWritable is given then runs once the resume has sent it.
func TestOnHeaderAsyncNoWait(t *testing.T) {
var aboveSeen, writable atomic.Bool
chunk := bytes.Repeat([]byte("z"), 16<<10)
const chunks = 8
addr := serve(t, NewHandler(HandlerFunc(func(c *Context) {
c.OnHeaderAsync(asyncHeaderLater(50*time.Millisecond, nil))
c.Retain()
var write func()
sent := 0
write = func() {
for sent < chunks {
above, err := c.WriteNoWait(chunk)
sent++
if err != nil {
c.Release()
return
}
if above {
aboveSeen.Store(true)
if c.OnWritable(func(err error) {
writable.Store(true)
if err != nil {
c.Release()
return
}
write()
}) {
return
}
}
}
c.Release()
}
write()
})))
for _, client := range hookClients(t) {
aboveSeen.Store(false)
writable.Store(false)
resp, err := client.Get("http://" + addr + "/")
if err != nil {
t.Fatal(err)
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
t.Fatal(err)
}
if len(body) != chunks*len(chunk) || resp.Header.Get("X-Async") != "set" {
t.Fatalf("%s: %d bytes, %v", client.proto, len(body), resp.Header)
}
if !aboveSeen.Load() || !writable.Load() {
t.Fatalf("%s: above %v, writable %v", client.proto, aboveSeen.Load(), writable.Load())
}
}
}
// TestOnHeaderAsyncWholeHeldByOnResponse checks that a response an
// OnResponse hook holds whole, which is sent as the handler returns, is held
// at the OnHeaderAsync hook all the same.
func TestOnHeaderAsyncWholeHeldByOnResponse(t *testing.T) {
addr := serve(t, NewHandler(HandlerFunc(func(c *Context) {
c.OnHeaderAsync(asyncHeaderLater(20*time.Millisecond, nil))
c.OnResponse(func(r *Response) { r.Body = append(r.Body, "!"...) })
_, _ = io.WriteString(c, "whole")
})))
for _, client := range hookClients(t) {
resp, err := client.Get("http://" + addr + "/")
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.Header.Get("X-Async") != "set" || string(body) != "whole!" {
t.Fatalf("%s: %v %q", client.proto, resp.Header, body)
}
}
}
// TestOnHeaderAsyncWriteEndsOnCancel checks that a Write waiting for the
// resume of a hook that never resumes, past what is held, returns the
// request's error once the client goes, as it closes an HTTP/1 connection
// and resets an HTTP/2 stream, so that the handler finishes. On Windows an
// HTTP/1 handler hears its client go only once its round ends, since the
// backend arms a connection's read only between rounds (see
// fib.HangupHandler), and this one waits in its round; an HTTP/2 stream's
// reset comes in a frame, which the connection reads all the same.
func TestOnHeaderAsyncWriteEndsOnCancel(t *testing.T) {
type result struct {
n int
err error
}
started := make(chan struct{}, 1)
done := make(chan result, 1)
addr := serve(t, NewHandler(HandlerFunc(func(c *Context) {
c.OnHeaderAsync(func(int, stdhttp.Header, func(error)) {})
started <- struct{}{}
chunk := bytes.Repeat([]byte("w"), 1000)
n := 0
var err error
for n < 200*1000 && err == nil {
var m int
m, err = c.Write(chunk)
n += m
}
done <- result{n, err}
})))
for _, client := range hookClients(t) {
if runtime.GOOS == "windows" && client.proto == "HTTP/1.1" {
t.Logf("%s skipped: Windows arms a connection's read only between its rounds; see fib.HangupHandler", client.proto)
continue
}
ctx, cancel := context.WithCancel(context.Background())
req, err := stdhttp.NewRequestWithContext(ctx, stdhttp.MethodGet, "http://"+addr+"/", nil)
if err != nil {
t.Fatal(err)
}
go func() {
<-started
cancel()
}()
if resp, err := client.Do(req); err == nil {
resp.Body.Close()
t.Fatalf("%s: answered %d", client.proto, resp.StatusCode)
}
select {
case r := <-done:
if r.err == nil || r.n > maxHeldBody {
t.Fatalf("%s: wrote %d, %v", client.proto, r.n, r.err)
}
case <-time.After(5 * time.Second):
t.Fatalf("%s: Write still waits after the client went", client.proto)
}
cancel()
}
}