| 1 | package provider |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "io" |
| 6 | "net" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "net/url" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "sync/atomic" |
| 13 | "testing" |
| 14 | "time" |
| 15 | ) |
| 16 | |
| 17 | func compatibilityTestClient(t *testing.T, server *httptest.Server) *http.Client { |
| 18 | t.Helper() |
| 19 | c := WithProtocolCompatibility(server.Client(), RequestIdentity{Provider: t.Name(), Protocol: "openai"}) |
| 20 | tr := c.Transport.(*protocolTransport) |
| 21 | tr.hints = freshProtocolHints() |
| 22 | t.Cleanup(c.CloseIdleConnections) |
| 23 | return c |
| 24 | } |
| 25 | |
| 26 | // primeCompatibility fails two separate requests with INTERNAL_ERROR, the |
| 27 | // evidence a route needs before a later request may try HTTP/1.1. |
| 28 | func primeCompatibility(t *testing.T, client *http.Client, endpoint string) { |
| 29 | t.Helper() |
| 30 | for range 2 { |
| 31 | resp, err := compatibilityPost(t.Context(), client, endpoint) |
| 32 | if resp != nil { |
| 33 | _, err = io.ReadAll(resp.Body) |
| 34 | resp.Body.Close() |
| 35 | } |
| 36 | if HTTP2TransportCode(err) != "INTERNAL_ERROR" { |
| 37 | t.Fatalf("missing typed HTTP/2 failure: %v", err) |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | func compatibilityPost(ctx context.Context, client *http.Client, endpoint string) (*http.Response, error) { |
| 43 | return SendWithRetry(ctx, client, SendOptions{Provider: "test", Protocol: "openai"}, func(ctx context.Context) (*http.Request, error) { |
| 44 | return http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(`{"messages":[{"role":"user","content":"unchanged"}]}`)) |
| 45 | }) |
| 46 | } |
| 47 | |
| 48 | func TestProtocolCompatibilityUsesOnlySubsequentRequests(t *testing.T) { |
| 49 | for _, bodyFailure := range []bool{false, true} { |
| 50 | t.Run(map[bool]string{false: "headers-no-observer", true: "partial-stream-observed"}[bodyFailure], func(t *testing.T) { |
| 51 | var requests, proxies atomic.Int32 |
| 52 | server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 53 | requests.Add(1) |
| 54 | b, err := io.ReadAll(r.Body) |
| 55 | if err != nil || string(b) != `{"messages":[{"role":"user","content":"unchanged"}]}` { |
| 56 | t.Error("request body changed") |
| 57 | } |
| 58 | if r.ProtoMajor == 2 { |
| 59 | if bodyFailure { |
| 60 | _, _ = io.WriteString(w, "data: partial\n\n") |
| 61 | w.(http.Flusher).Flush() |
| 62 | } |
| 63 | panic(http.ErrAbortHandler) // real HTTP/2 RST_STREAM INTERNAL_ERROR |
| 64 | } |
| 65 | _, _ = io.WriteString(w, "data: complete\n\n") |
| 66 | })) |
| 67 | server.EnableHTTP2 = true |
| 68 | server.StartTLS() |
| 69 | defer server.Close() |
| 70 | client := compatibilityTestClient(t, server) |
| 71 | client.Transport.(*protocolTransport).proxy = func(*http.Request) (*url.URL, error) { |
| 72 | proxies.Add(1) |
| 73 | return nil, nil |
| 74 | } |
| 75 | var mu sync.Mutex |
| 76 | var last RequestObservation |
| 77 | baseCtx := t.Context() |
| 78 | if bodyFailure { |
| 79 | baseCtx = WithRequestObserver(baseCtx, func(v RequestObservation) { mu.Lock(); last = v; mu.Unlock() }) |
| 80 | } |
| 81 | for attempt := 1; attempt <= 4; attempt++ { |
| 82 | ctx := WithRequestAttemptCounter(baseCtx) |
| 83 | resp, err := compatibilityPost(ctx, client, server.URL+"/chat") |
| 84 | if resp != nil { |
| 85 | _, err = io.ReadAll(resp.Body) |
| 86 | resp.Body.Close() |
| 87 | } |
| 88 | if attempt <= 2 { |
| 89 | // One INTERNAL_ERROR is a server's generic stream reset as often |
| 90 | // as an incompatibility; only a later request failing confirms it. |
| 91 | if HTTP2TransportCode(err) != "INTERNAL_ERROR" { |
| 92 | t.Fatalf("attempt %d did not stay on HTTP/2: %v", attempt, err) |
| 93 | } |
| 94 | } else if err != nil || resp.ProtoMajor != 1 { |
| 95 | t.Fatalf("subsequent request did not use HTTP/1.1: resp=%v err=%v", resp, err) |
| 96 | } |
| 97 | if requests.Load() != int32(attempt) || proxies.Load() != int32(attempt) || RequestAttemptCount(ctx) != 1 { |
| 98 | t.Fatalf("replayed request or resolved proxy twice: requests=%d proxies=%d count=%d", requests.Load(), proxies.Load(), RequestAttemptCount(ctx)) |
| 99 | } |
| 100 | } |
| 101 | mu.Lock() |
| 102 | if bodyFailure && (last.ProtocolFallbackReason != "INTERNAL_ERROR" || last.HTTPProtocol != "HTTP/1.1" || last.TransportCode != "") { |
| 103 | t.Errorf("lost compatibility evidence: %+v", last) |
| 104 | } |
| 105 | mu.Unlock() |
| 106 | // Another endpoint remains HTTP/2, even with the same client and provider. |
| 107 | primeCompatibility(t, client, server.URL+"/other") |
| 108 | }) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | func TestProtocolCompatibilityFailureKeepsExistingRecovery(t *testing.T) { |
| 113 | for _, failure := range []string{"headers-eof", "body-eof", "send-timeout"} { |
| 114 | t.Run(failure, func(t *testing.T) { |
| 115 | var requests atomic.Int32 |
| 116 | var primed atomic.Bool |
| 117 | release := make(chan struct{}) |
| 118 | server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 119 | requests.Add(1) |
| 120 | if r.ProtoMajor == 2 { |
| 121 | panic(http.ErrAbortHandler) |
| 122 | } |
| 123 | if !primed.Load() { |
| 124 | t.Error("HTTP/1.1 selected before the route was confirmed") |
| 125 | return |
| 126 | } |
| 127 | switch failure { |
| 128 | case "send-timeout": |
| 129 | <-release |
| 130 | return |
| 131 | case "body-eof": |
| 132 | _, _ = io.WriteString(w, "data: partial\n\n") |
| 133 | w.(http.Flusher).Flush() |
| 134 | } |
| 135 | conn, _, _ := w.(http.Hijacker).Hijack() |
| 136 | conn.Close() |
| 137 | })) |
| 138 | server.EnableHTTP2 = true |
| 139 | server.StartTLS() |
| 140 | defer server.Close() |
| 141 | defer close(release) |
| 142 | server.Client().Transport.(*http.Transport).DialContext = func(ctx context.Context, network, address string) (net.Conn, error) { |
| 143 | conn, err := (&net.Dialer{}).DialContext(ctx, network, address) |
| 144 | if err == nil { |
| 145 | _ = conn.(*net.TCPConn).SetWriteBuffer(1024) |
| 146 | } |
| 147 | return conn, err |
| 148 | } |
| 149 | client := compatibilityTestClient(t, server) |
| 150 | primeCompatibility(t, client, server.URL) |
| 151 | primed.Store(true) |
| 152 | var mu sync.Mutex |
| 153 | observed := map[uint64]RequestObservation{} |
| 154 | ctx := WithRequestAttemptCounter(WithRequestObserver(t.Context(), func(v RequestObservation) { |
| 155 | mu.Lock() |
| 156 | observed[v.ID] = v |
| 157 | mu.Unlock() |
| 158 | })) |
| 159 | resp, err := sendWithResends(ctx, client, SendOptions{}, func(ctx context.Context) (*http.Request, error) { |
| 160 | body := "small" |
| 161 | if failure == "send-timeout" { |
| 162 | body = strings.Repeat("x", 3_248_572) |
| 163 | } |
| 164 | return http.NewRequestWithContext(ctx, http.MethodPost, server.URL, strings.NewReader(body)) |
| 165 | }, 500*time.Millisecond, 1) |
| 166 | if resp != nil { |
| 167 | _, err = io.ReadAll(resp.Body) |
| 168 | resp.Body.Close() |
| 169 | } |
| 170 | var probe RequestObservation |
| 171 | mu.Lock() |
| 172 | for _, v := range observed { |
| 173 | if v.ProtocolFallbackReason != "" { |
| 174 | probe = v |
| 175 | } |
| 176 | } |
| 177 | mu.Unlock() |
| 178 | if probe.ProtocolFallbackReason != "INTERNAL_ERROR" || probe.TransportCode != "" { |
| 179 | t.Fatalf("lost compatibility evidence: %+v", probe) |
| 180 | } |
| 181 | if failure == "send-timeout" { |
| 182 | // The upload never finished, so the existing resend allowance still |
| 183 | // owns it; the failed probe has already returned the route to HTTP/2. |
| 184 | if RequestAttemptCount(ctx) != 2 || requests.Load() != 4 { |
| 185 | t.Fatalf("send timeout lost its resend: server=%d count=%d err=%v", requests.Load(), RequestAttemptCount(ctx), err) |
| 186 | } |
| 187 | if probe.ErrorCode != "request_send_timeout" || probe.TimeoutSource != "send_guard" { |
| 188 | t.Fatalf("lost guarded send failure evidence: %+v", probe) |
| 189 | } |
| 190 | } else { |
| 191 | if RequestAttemptCount(ctx) != 1 || requests.Load() != 3 { |
| 192 | t.Fatalf("fresh-connection failure was resent: server=%d count=%d", requests.Load(), RequestAttemptCount(ctx)) |
| 193 | } |
| 194 | // A dropped HTTP/1.1 connection is the same recoverable reset the |
| 195 | // stream owners already handle, not a protocol failure. |
| 196 | if recovery := ClassifyRecovery(err); !IsConnReset(err) || recovery.Phase == "protocol" || !recovery.Retryable { |
| 197 | t.Fatalf("connection failure reclassified: phase=%q retryable=%t err=%v", recovery.Phase, recovery.Retryable, err) |
| 198 | } |
| 199 | } |
| 200 | before := requests.Load() |
| 201 | // The failed H1 probe disables compatibility until the original expiry. |
| 202 | _, err = compatibilityPost(t.Context(), client, server.URL) |
| 203 | if HTTP2TransportCode(err) != "INTERNAL_ERROR" || requests.Load() != before+1 { |
| 204 | t.Fatalf("failed compatibility looped: requests=%d err=%v", requests.Load(), err) |
| 205 | } |
| 206 | }) |
| 207 | } |
| 208 | } |
| 209 |