| 1 | package provider |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "net/http/httptrace" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | "sync/atomic" |
| 14 | "testing" |
| 15 | "time" |
| 16 | ) |
| 17 | |
| 18 | type sendTransportFunc func(*http.Request) (*http.Response, error) |
| 19 | |
| 20 | func (f sendTransportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| 21 | |
| 22 | func sendTestRequest(url, body string) func(context.Context) (*http.Request, error) { |
| 23 | return func(ctx context.Context) (*http.Request, error) { |
| 24 | return http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(body)) |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | func TestRequestSendGuardStalledUpload(t *testing.T) { |
| 29 | for _, h2 := range []bool{false, true} { |
| 30 | for _, observed := range []bool{false, true} { |
| 31 | t.Run(map[bool]string{false: "http1", true: "http2"}[h2]+map[bool]string{false: "-plain", true: "-observed"}[observed], func(t *testing.T) { |
| 32 | arrived := make(chan string, 1) |
| 33 | release := make(chan struct{}) |
| 34 | siblingRelease := make(chan struct{}) |
| 35 | var calls atomic.Int32 |
| 36 | s := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 37 | calls.Add(1) |
| 38 | if r.URL.Path == "/ok" { |
| 39 | if r.URL.RawQuery == "hold" { |
| 40 | w.(http.Flusher).Flush() |
| 41 | <-siblingRelease |
| 42 | } |
| 43 | _, _ = io.WriteString(w, "ok") |
| 44 | return |
| 45 | } |
| 46 | arrived <- r.Proto |
| 47 | <-release // Deliberately never read the upload. |
| 48 | })) |
| 49 | s.EnableHTTP2 = h2 |
| 50 | s.StartTLS() |
| 51 | defer s.Close() |
| 52 | defer close(siblingRelease) |
| 53 | defer close(release) |
| 54 | client := s.Client() |
| 55 | tr := client.Transport.(*http.Transport) |
| 56 | tr.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) { |
| 57 | conn, err := (&net.Dialer{}).DialContext(ctx, network, address) |
| 58 | if err == nil { |
| 59 | _ = conn.(*net.TCPConn).SetWriteBuffer(1024) |
| 60 | } |
| 61 | return conn, err |
| 62 | } |
| 63 | ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) |
| 64 | defer cancel() |
| 65 | ctx = WithRequestAttemptCounter(ctx) |
| 66 | var mu sync.Mutex |
| 67 | var last RequestObservation |
| 68 | if observed { |
| 69 | ctx = WithRequestObserver(ctx, func(o RequestObservation) { mu.Lock(); last = o; mu.Unlock() }) |
| 70 | } |
| 71 | done := make(chan error, 1) |
| 72 | go func() { |
| 73 | _, stale, err := sendAttemptWithTimeout(ctx, client, sendTestRequest(s.URL, strings.Repeat("x", 3_248_572)), 300*time.Millisecond) |
| 74 | if stale { |
| 75 | done <- errors.New("send timeout was classified as stale idle connection") |
| 76 | return |
| 77 | } |
| 78 | done <- err |
| 79 | }() |
| 80 | select { |
| 81 | case proto := <-arrived: |
| 82 | if (proto == "HTTP/2.0") != h2 { |
| 83 | t.Fatalf("protocol = %s", proto) |
| 84 | } |
| 85 | case <-ctx.Done(): |
| 86 | t.Fatal(ctx.Err()) |
| 87 | } |
| 88 | var siblingBody io.ReadCloser |
| 89 | if h2 { |
| 90 | // Reuse the same multiplexed connection while its sibling stalls. |
| 91 | var reused bool |
| 92 | sibling := httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{GotConn: func(i httptrace.GotConnInfo) { reused = i.Reused }}) |
| 93 | r, _, err := sendAttemptWithTimeout(sibling, client, sendTestRequest(s.URL+"/ok?hold", ""), time.Second) |
| 94 | if err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | siblingBody = r.Body |
| 98 | if !reused { |
| 99 | t.Fatal("sibling did not reuse the stalled connection") |
| 100 | } |
| 101 | } |
| 102 | err := <-done |
| 103 | var timeout *RequestSendTimeoutError |
| 104 | if !errors.As(err, &timeout) || errors.Is(err, context.Canceled) || ctx.Err() != nil { |
| 105 | t.Fatalf("send error=%v parent=%v", err, ctx.Err()) |
| 106 | } |
| 107 | if DiagnoseFailure(err).Kind != "request_send_timeout" || ClassifyRecovery(err).Retryable || IsConnReset(err) { |
| 108 | t.Fatalf("wrong timeout classification: %v", err) |
| 109 | } |
| 110 | want := int32(1) |
| 111 | if h2 { |
| 112 | want++ |
| 113 | } |
| 114 | if calls.Load() != want || RequestAttemptCount(ctx) != int(want) { |
| 115 | t.Fatalf("calls=%d attempts=%d", calls.Load(), RequestAttemptCount(ctx)) |
| 116 | } |
| 117 | if observed { |
| 118 | mu.Lock() |
| 119 | v := last |
| 120 | mu.Unlock() |
| 121 | if v.ErrorCode != "request_send_timeout" || v.TimeoutSource != "send_guard" || v.Phase == "canceled" || v.SendTimeoutMs != 300 || !v.WrittenAt.IsZero() { |
| 122 | t.Fatalf("observation: %+v", v) |
| 123 | } |
| 124 | } |
| 125 | if h2 { |
| 126 | // The sibling remains live across cancellation of the stalled stream. |
| 127 | siblingRelease <- struct{}{} |
| 128 | body, err := io.ReadAll(siblingBody) |
| 129 | siblingBody.Close() |
| 130 | if err != nil || string(body) != "ok" { |
| 131 | t.Fatalf("sibling interrupted: body=%q err=%v", body, err) |
| 132 | } |
| 133 | var reused bool |
| 134 | request, _ := http.NewRequestWithContext(httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{GotConn: func(i httptrace.GotConnInfo) { reused = i.Reused }}), http.MethodGet, s.URL+"/ok", nil) |
| 135 | r, err := client.Do(request) |
| 136 | if err != nil { |
| 137 | t.Fatal("timeout broke sibling connection:", err) |
| 138 | } |
| 139 | io.Copy(io.Discard, r.Body) |
| 140 | r.Body.Close() |
| 141 | if !reused { |
| 142 | t.Fatal("timeout closed the shared HTTP/2 connection") |
| 143 | } |
| 144 | } |
| 145 | }) |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | func TestRequestSendGuardHandsOffAfterWrite(t *testing.T) { |
| 151 | for _, stream := range []bool{false, true} { |
| 152 | t.Run(map[bool]string{false: "headers", true: "stream"}[stream], func(t *testing.T) { |
| 153 | release := make(chan struct{}) |
| 154 | s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 155 | io.Copy(io.Discard, r.Body) |
| 156 | if stream { |
| 157 | w.Header().Set("Content-Type", "text/event-stream") |
| 158 | w.(http.Flusher).Flush() |
| 159 | } |
| 160 | <-release |
| 161 | if stream { |
| 162 | _, _ = io.WriteString(w, "data: ok\n\n") |
| 163 | } |
| 164 | })) |
| 165 | defer s.Close() |
| 166 | var once sync.Once |
| 167 | unblock := func() { once.Do(func() { close(release) }) } |
| 168 | defer unblock() |
| 169 | client := s.Client() |
| 170 | client.Transport.(*http.Transport).ResponseHeaderTimeout = 150 * time.Millisecond |
| 171 | var v RequestObservation |
| 172 | var mu sync.Mutex |
| 173 | ctx := WithRequestObserver(t.Context(), func(o RequestObservation) { mu.Lock(); v = o; mu.Unlock() }) |
| 174 | resp, _, err := sendAttemptWithTimeout(ctx, client, sendTestRequest(s.URL, "small"), 80*time.Millisecond) |
| 175 | if !stream { |
| 176 | mu.Lock() |
| 177 | defer mu.Unlock() |
| 178 | if err == nil || DiagnoseFailure(err).Kind != "transport_timeout" || v.ErrorPhase != "response_headers" || v.TimeoutSource != "transport" { |
| 179 | t.Fatalf("err=%v observation=%+v", err, v) |
| 180 | } |
| 181 | return |
| 182 | } |
| 183 | if err != nil { |
| 184 | t.Fatal(err) |
| 185 | } |
| 186 | defer resp.Body.Close() |
| 187 | time.AfterFunc(160*time.Millisecond, unblock) |
| 188 | body, err := io.ReadAll(resp.Body) |
| 189 | mu.Lock() |
| 190 | defer mu.Unlock() |
| 191 | if err != nil || string(body) != "data: ok\n\n" || v.ErrorCode != "" || v.Phase != "body_eof" { |
| 192 | t.Fatalf("body=%q err=%v observation=%+v", body, err, v) |
| 193 | } |
| 194 | }) |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | func TestRequestSendGuardGenerations(t *testing.T) { |
| 199 | ctx, cancel := context.WithCancelCause(t.Context()) |
| 200 | defer cancel(nil) |
| 201 | g := &requestSendGuard{budget: time.Hour, cancel: cancel} |
| 202 | round := g.begin() |
| 203 | g.arm(round) |
| 204 | first := g.generation |
| 205 | g.written(round, httptrace.WroteRequestInfo{}) |
| 206 | g.arm(round) // Transport internal retry after a successful write. |
| 207 | g.expire(first) |
| 208 | if ctx.Err() != nil { |
| 209 | t.Fatal("old timer canceled a new send") |
| 210 | } |
| 211 | round = g.begin() |
| 212 | g.written(round-1, httptrace.WroteRequestInfo{}) |
| 213 | if g.timer == nil { |
| 214 | t.Fatal("late write completion disarmed redirect") |
| 215 | } |
| 216 | g.expire(g.generation) |
| 217 | if !errors.As(context.Cause(ctx), new(*RequestSendTimeoutError)) { |
| 218 | t.Fatal(context.Cause(ctx)) |
| 219 | } |
| 220 | g.finish() |
| 221 | } |
| 222 | |
| 223 | func TestRequestSendGuardRedirectRetryEarlyResponseAndCleanup(t *testing.T) { |
| 224 | for _, mode := range []string{"redirect", "internal-retry", "early-response", "cancel", "deadline"} { |
| 225 | t.Run(mode, func(t *testing.T) { |
| 226 | ctx, cancel := context.WithCancel(t.Context()) |
| 227 | defer cancel() |
| 228 | var requestCtx context.Context |
| 229 | var calls int |
| 230 | client := &http.Client{Transport: sendTransportFunc(func(r *http.Request) (*http.Response, error) { |
| 231 | requestCtx = r.Context() |
| 232 | calls++ |
| 233 | trace := httptrace.ContextClientTrace(r.Context()) |
| 234 | trace.GetConn("provider.test") |
| 235 | if mode == "early-response" { |
| 236 | return &http.Response{StatusCode: http.StatusRequestEntityTooLarge, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("too large")), Request: r}, nil |
| 237 | } |
| 238 | if mode == "redirect" && calls == 1 { |
| 239 | trace.WroteRequest(httptrace.WroteRequestInfo{}) |
| 240 | return &http.Response{StatusCode: http.StatusTemporaryRedirect, Header: http.Header{"Location": {"/next"}}, Body: io.NopCloser(strings.NewReader("")), Request: r}, nil |
| 241 | } |
| 242 | if mode == "internal-retry" { |
| 243 | trace.WroteRequest(httptrace.WroteRequestInfo{}) |
| 244 | trace.GetConn("provider.test") |
| 245 | } |
| 246 | if mode == "cancel" { |
| 247 | cancel() |
| 248 | } |
| 249 | <-r.Context().Done() |
| 250 | return nil, r.Context().Err() |
| 251 | })} |
| 252 | if mode == "deadline" { |
| 253 | var stop context.CancelFunc |
| 254 | ctx, stop = context.WithTimeout(ctx, 10*time.Millisecond) |
| 255 | defer stop() |
| 256 | } |
| 257 | resp, stale, err := sendAttemptWithTimeout(ctx, client, sendTestRequest("https://provider.test/start", "body"), 40*time.Millisecond) |
| 258 | if stale { |
| 259 | t.Fatal("unexpected resend") |
| 260 | } |
| 261 | switch mode { |
| 262 | case "early-response": |
| 263 | if err != nil || resp.StatusCode != http.StatusRequestEntityTooLarge || requestCtx.Err() != nil { |
| 264 | t.Fatalf("response=%v err=%v", resp, err) |
| 265 | } |
| 266 | resp.Body.Close() |
| 267 | case "cancel": |
| 268 | if !errors.Is(err, context.Canceled) { |
| 269 | t.Fatal(err) |
| 270 | } |
| 271 | case "deadline": |
| 272 | if !errors.Is(err, context.DeadlineExceeded) { |
| 273 | t.Fatal(err) |
| 274 | } |
| 275 | default: |
| 276 | if !errors.As(err, new(*RequestSendTimeoutError)) { |
| 277 | t.Fatal(err) |
| 278 | } |
| 279 | } |
| 280 | if mode == "early-response" { |
| 281 | cancel() |
| 282 | if requestCtx.Err() != nil { |
| 283 | t.Fatal("released request is still registered with its caller") |
| 284 | } |
| 285 | } else if requestCtx.Err() == nil { |
| 286 | t.Fatal("request context leaked") |
| 287 | } |
| 288 | want := 1 |
| 289 | if mode == "redirect" { |
| 290 | want = 2 |
| 291 | } |
| 292 | if calls != want { |
| 293 | t.Fatalf("requests=%d", calls) |
| 294 | } |
| 295 | }) |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | func TestSendWithRetryResendsOnceAfterSendTimeout(t *testing.T) { |
| 300 | for _, tc := range []struct { |
| 301 | name string |
| 302 | stalls int |
| 303 | cancel bool |
| 304 | once bool |
| 305 | calls int |
| 306 | timeout bool |
| 307 | }{ |
| 308 | {name: "second-attempt-delivers", stalls: 1, calls: 2}, |
| 309 | {name: "send-once-keeps-first-evidence", stalls: 1, once: true, calls: 1, timeout: true}, |
| 310 | {name: "second-timeout-is-terminal", stalls: 2, calls: 2, timeout: true}, |
| 311 | {name: "user-cancel-is-not-resent", stalls: 2, cancel: true, calls: 1}, |
| 312 | } { |
| 313 | t.Run(tc.name, func(t *testing.T) { |
| 314 | ctx, cancel := context.WithCancel(WithRequestAttemptCounter(t.Context())) |
| 315 | defer cancel() |
| 316 | var calls int |
| 317 | client := &http.Client{Transport: sendTransportFunc(func(r *http.Request) (*http.Response, error) { |
| 318 | calls++ |
| 319 | trace := httptrace.ContextClientTrace(r.Context()) |
| 320 | trace.GetConn("provider.test") |
| 321 | if calls <= tc.stalls { |
| 322 | if tc.cancel { |
| 323 | cancel() |
| 324 | } |
| 325 | <-r.Context().Done() |
| 326 | return nil, r.Context().Err() |
| 327 | } |
| 328 | trace.WroteRequest(httptrace.WroteRequestInfo{}) |
| 329 | return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("ok")), Request: r}, nil |
| 330 | })} |
| 331 | resends := 1 |
| 332 | if tc.once { |
| 333 | resends = 0 |
| 334 | } |
| 335 | resp, err := sendWithResends(ctx, client, SendOptions{Provider: "deepseek", Protocol: "openai"}, sendTestRequest("https://provider.test/v1", "body"), 30*time.Millisecond, resends) |
| 336 | if calls != tc.calls || RequestAttemptCount(ctx) != tc.calls { |
| 337 | t.Fatalf("calls=%d attempts=%d, want %d", calls, RequestAttemptCount(ctx), tc.calls) |
| 338 | } |
| 339 | switch { |
| 340 | case tc.cancel: |
| 341 | if !errors.Is(err, context.Canceled) { |
| 342 | t.Fatalf("err=%v", err) |
| 343 | } |
| 344 | case tc.timeout: |
| 345 | var failure *RequestFailure |
| 346 | if !errors.As(err, &failure) || !errors.As(err, new(*RequestSendTimeoutError)) || DiagnoseFailure(err).Kind != "request_send_timeout" { |
| 347 | t.Fatalf("err=%v", err) |
| 348 | } |
| 349 | default: |
| 350 | if err != nil || resp.StatusCode != http.StatusOK { |
| 351 | t.Fatalf("resp=%v err=%v", resp, err) |
| 352 | } |
| 353 | resp.Body.Close() |
| 354 | } |
| 355 | }) |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | // Cancelling a finished HTTP/2 stream's context races its teardown, and the |
| 360 | // next request can find the pooled connection not yet idle. |
| 361 | func TestRequestSendGuardReleasesWithoutCancellingCompletedStream(t *testing.T) { |
| 362 | for _, mode := range []string{"eof", "close", "parent-cancel-mid-stream"} { |
| 363 | t.Run(mode, func(t *testing.T) { |
| 364 | parent, cancelParent := context.WithCancel(t.Context()) |
| 365 | defer cancelParent() |
| 366 | var requestCtx context.Context |
| 367 | client := &http.Client{Transport: sendTransportFunc(func(r *http.Request) (*http.Response, error) { |
| 368 | requestCtx = r.Context() |
| 369 | httptrace.ContextClientTrace(r.Context()).WroteRequest(httptrace.WroteRequestInfo{}) |
| 370 | return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("data")), Request: r}, nil |
| 371 | })} |
| 372 | resp, _, err := sendAttemptWithTimeout(parent, client, sendTestRequest("https://provider.test/v1", "body"), time.Hour) |
| 373 | if err != nil { |
| 374 | t.Fatal(err) |
| 375 | } |
| 376 | if mode == "parent-cancel-mid-stream" { |
| 377 | cancelParent() |
| 378 | select { |
| 379 | case <-requestCtx.Done(): |
| 380 | case <-time.After(5 * time.Second): |
| 381 | t.Fatal("caller cancellation did not reach the open stream") |
| 382 | } |
| 383 | resp.Body.Close() |
| 384 | return |
| 385 | } |
| 386 | if mode == "eof" { |
| 387 | _, _ = io.ReadAll(resp.Body) |
| 388 | } |
| 389 | resp.Body.Close() |
| 390 | if requestCtx.Err() != nil { |
| 391 | t.Fatal("completed stream was cancelled") |
| 392 | } |
| 393 | cancelParent() |
| 394 | if requestCtx.Err() != nil { |
| 395 | t.Fatal("released request is still registered with its caller") |
| 396 | } |
| 397 | }) |
| 398 | } |
| 399 | } |
| 400 |