返回 DeepSeek-Reasonix
protocol_compatibility.go
根目录 / internal / provider / protocol_compatibility.go
1 package provider
2
3 import (
4 "context"
5 "crypto/sha256"
6 "crypto/tls"
7 "errors"
8 "io"
9 "net/http"
10 "net/url"
11 "sync"
12 "time"
13 )
14
15 const protocolCompatibilityTTL = 10 * time.Minute
16 const protocolCompatibilityLimit = 256
17
18 // A hint is process-local and survives provider reconstruction, but never
19 // persists URLs, proxy credentials or configuration. Fixed expiry prevents an
20 // unhealthy path from permanently disabling HTTP/2.
21 var protocolCompatibilityHints = &protocolHints{entries: make(map[[32]byte]*protocolHint)}
22
23 type protocolHint struct {
24 since uint64 // request sequence when the entry was recorded; only a later request confirms it
25 until time.Time
26 reason string
27 mode string // observed, pending, probing, active, disabled
28 }
29
30 type protocolHints struct {
31 mu sync.Mutex
32 seq uint64
33 entries map[[32]byte]*protocolHint
34 }
35
36 // begin numbers a request so that "started after this observation" is an
37 // ordering, not a clock reading: coarse clocks tie two requests in one tick.
38 func (s *protocolHints) begin() uint64 {
39 s.mu.Lock()
40 defer s.mu.Unlock()
41 s.seq++
42 return s.seq
43 }
44
45 func (s *protocolHints) selectHTTP1(key [32]byte, now time.Time) *protocolHint {
46 s.mu.Lock()
47 defer s.mu.Unlock()
48 h := s.entries[key]
49 if h == nil {
50 return nil
51 }
52 if !now.Before(h.until) {
53 delete(s.entries, key)
54 return nil
55 }
56 switch h.mode {
57 case "pending":
58 h.mode = "probing" // only one concurrent request tries an unproven path
59 case "active":
60 default:
61 return nil
62 }
63 return h
64 }
65
66 // failedHTTP2 records a trigger code from the request numbered started by begin.
67 // INTERNAL_ERROR is also a server's generic stream reset, so it only observes
68 // a route until a request started after that observation fails again.
69 func (s *protocolHints) failedHTTP2(key [32]byte, code string, started uint64, now time.Time) {
70 s.mu.Lock()
71 defer s.mu.Unlock()
72 for k, h := range s.entries {
73 if !now.Before(h.until) {
74 delete(s.entries, k)
75 }
76 }
77 if h := s.entries[key]; h != nil {
78 if h.mode == "observed" && (code != "INTERNAL_ERROR" || started > h.since) {
79 h.since, h.until, h.reason, h.mode = s.seq, now.Add(protocolCompatibilityTTL), code, "pending"
80 }
81 return // late failures cannot reset a newer decision or extend its TTL
82 }
83 if len(s.entries) >= protocolCompatibilityLimit {
84 return
85 }
86 mode := "pending"
87 if code == "INTERNAL_ERROR" {
88 mode = "observed"
89 }
90 s.entries[key] = &protocolHint{since: s.seq, until: now.Add(protocolCompatibilityTTL), reason: code, mode: mode}
91 }
92
93 func (s *protocolHints) settle(key [32]byte, h *protocolHint, mode string) {
94 s.mu.Lock()
95 defer s.mu.Unlock()
96 if s.entries[key] == h && h.mode != "disabled" && (mode != "pending" || h.mode == "probing") {
97 h.mode = mode
98 }
99 }
100
101 // WithProtocolCompatibility wraps only an ordinary provider transport. It does
102 // not wrap credential tunnels or custom RoundTrippers, whose dialing and ALPN
103 // contracts it cannot safely infer. Call before publishing the client.
104 // The wrapper calls its selected transport exactly once and returns its errors
105 // unchanged, so existing retry owners still judge them by their real cause. An
106 // HTTP/2 failure affects a later request, never replays the current one.
107 func WithProtocolCompatibility(client *http.Client, identity RequestIdentity) *http.Client {
108 base, ok := client.Transport.(*http.Transport)
109 if !ok || base.DialTLS != nil || base.DialTLSContext != nil { //nolint:staticcheck // Legacy TLS dialers also own ALPN; do not wrap them.
110 return client
111 }
112 h1 := base.Clone()
113 h1.ForceAttemptHTTP2 = false
114 h1.Protocols = new(http.Protocols)
115 h1.Protocols.SetHTTP1(true)
116 h1.TLSNextProto = make(map[string]func(string, *tls.Conn) http.RoundTripper)
117 if h1.TLSClientConfig != nil {
118 h1.TLSClientConfig.NextProtos = []string{"http/1.1"}
119 }
120 // Resolve once per request and pin the same proxy for selection and dialing.
121 // Do not mutate the base transport: it may already serve sibling streams.
122 normal := base.Clone()
123 normal.Proxy, h1.Proxy = selectedProtocolProxy, selectedProtocolProxy
124 copy := *client
125 copy.Transport = &protocolTransport{normal: normal, http1: h1, proxy: base.Proxy,
126 scope: identity.Provider + "\x00" + identity.Protocol, hints: protocolCompatibilityHints}
127 return &copy
128 }
129
130 type protocolProxyKey struct{}
131 type protocolProxy struct{ url *url.URL }
132
133 func selectedProtocolProxy(req *http.Request) (*url.URL, error) {
134 p, _ := req.Context().Value(protocolProxyKey{}).(protocolProxy)
135 return p.url, nil
136 }
137
138 type protocolTransport struct {
139 normal, http1 *http.Transport
140 proxy func(*http.Request) (*url.URL, error)
141 scope string
142 hints *protocolHints
143 }
144
145 func (t *protocolTransport) RoundTrip(req *http.Request) (*http.Response, error) {
146 var proxy *url.URL
147 var err error
148 if t.proxy != nil {
149 proxy, err = t.proxy(req)
150 if err != nil {
151 return nil, err
152 }
153 }
154 proxyPath := "direct"
155 if proxy != nil {
156 proxyPath = proxy.String()
157 }
158 key := sha256.Sum256([]byte(t.scope + "\x00" + req.URL.String() + "\x00" + proxyPath))
159 ctx := context.WithValue(req.Context(), protocolProxyKey{}, protocolProxy{proxy})
160 req = req.WithContext(ctx)
161 started := t.hints.begin()
162 var hint *protocolHint
163 if req.URL.Scheme == "https" && ctx.Err() == nil {
164 hint = t.hints.selectHTTP1(key, time.Now())
165 }
166 transport := t.normal
167 if hint != nil {
168 transport = t.http1
169 if observation, _ := ctx.Value(protocolObservationKey{}).(*requestObservationState); observation != nil {
170 observation.update("protocol_selected", func(v *RequestObservation) { v.ProtocolFallbackReason = hint.reason })
171 }
172 }
173 resp, err := transport.RoundTrip(req)
174 if err != nil {
175 t.failed(ctx, key, hint, started, err)
176 return resp, err
177 }
178 if hint != nil {
179 t.hints.settle(key, hint, "active")
180 }
181 resp.Body = &protocolResponseBody{ReadCloser: resp.Body, failed: func(err error) {
182 t.failed(ctx, key, hint, started, err)
183 }}
184 return resp, nil
185 }
186
187 func (t *protocolTransport) failed(ctx context.Context, key [32]byte, hint *protocolHint, started uint64, err error) {
188 if ctx.Err() != nil && !errors.As(context.Cause(ctx), new(*RequestSendTimeoutError)) {
189 if hint != nil {
190 t.hints.settle(key, hint, "pending")
191 }
192 return
193 }
194 if hint != nil {
195 t.hints.settle(key, hint, "disabled")
196 return
197 }
198 if code := compatibilityTrigger(err); code != "" {
199 t.hints.failedHTTP2(key, code, started, time.Now())
200 }
201 }
202
203 func (t *protocolTransport) CloseIdleConnections() {
204 t.normal.CloseIdleConnections()
205 t.http1.CloseIdleConnections()
206 }
207
208 // compatibilityTrigger returns the typed HTTP/2 code that marks a route as a
209 // compatibility candidate, or "" for every other failure.
210 func compatibilityTrigger(err error) string {
211 switch code := HTTP2TransportCode(err); code {
212 case "INTERNAL_ERROR", "PROTOCOL_ERROR", "HTTP_1_1_REQUIRED":
213 return code
214 }
215 return ""
216 }
217
218 // protocolFailureIsTerminal reports a peer reset that may follow processing, so
219 // no resend or stream retry owns it. Other HTTP/2 codes keep their handling.
220 func protocolFailureIsTerminal(err error) bool {
221 return compatibilityTrigger(err) != ""
222 }
223
224 type protocolResponseBody struct {
225 io.ReadCloser
226 failed func(error)
227 }
228
229 func (b *protocolResponseBody) Read(p []byte) (int, error) {
230 n, err := b.ReadCloser.Read(p)
231 if err == io.EOF {
232 return n, err // normal stream completion is not a transport failure
233 }
234 if err != nil {
235 b.failed(err)
236 }
237 return n, err
238 }
239
240 func (b *protocolResponseBody) Close() error {
241 err := b.ReadCloser.Close()
242 if err != nil {
243 b.failed(err)
244 }
245 return err
246 }
247
247 lines GO