mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
62 lines
2.0 KiB
Go
62 lines
2.0 KiB
Go
package answer
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptrace"
|
|
"sync/atomic"
|
|
)
|
|
|
|
// DoHTTP records transport evidence for one HTTP call. An already admitted
|
|
// operation must pass PossiblyAdmitted even when this call only polls it.
|
|
func DoHTTP(client *http.Client, req *http.Request, phase Phase) (*http.Response, error) {
|
|
if err := req.Context().Err(); err != nil {
|
|
// Do not invoke even a custom transport after a preflight cancellation.
|
|
// An earlier admission still belongs to the operation, including polls.
|
|
return nil, RecordContext(req.Context(), phase, err)
|
|
}
|
|
// A concrete http.Transport may delegate through RegisterProtocol. Only
|
|
// our privately owned native path can supply positive trace provenance.
|
|
if client.Transport == nil {
|
|
copy := *client
|
|
copy.Transport = defaultHTTPTransport
|
|
client = ©
|
|
}
|
|
_, trustedTrace := client.Transport.(*nativeHTTPTransport)
|
|
// Lack of trace support is not proof of an unsent request. GotConn is
|
|
// conservative: from that point a request write may have started, even
|
|
// if a WroteHeaders callback never arrives after a partial write.
|
|
var traced, connected atomic.Bool
|
|
trace := &httptrace.ClientTrace{
|
|
GetConn: func(string) { traced.Store(true) },
|
|
GotConn: func(httptrace.GotConnInfo) { connected.Store(true) },
|
|
}
|
|
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
|
|
resp, err := client.Do(req)
|
|
observed := PossiblyAdmitted
|
|
if phase == Unsent && trustedTrace && traced.Load() && !connected.Load() {
|
|
observed = Unsent
|
|
}
|
|
if err != nil {
|
|
return resp, RecordContext(req.Context(), observed, err)
|
|
}
|
|
if resp.Body != nil {
|
|
resp.Body = &responseBody{ReadCloser: resp.Body, ctx: req.Context()}
|
|
}
|
|
return resp, nil
|
|
}
|
|
|
|
type responseBody struct {
|
|
io.ReadCloser
|
|
ctx context.Context
|
|
}
|
|
|
|
func (body *responseBody) Read(p []byte) (int, error) {
|
|
n, err := body.ReadCloser.Read(p)
|
|
if err != nil && err != io.EOF {
|
|
err = RecordContext(body.ctx, PossiblyAdmitted, err)
|
|
}
|
|
return n, err
|
|
}
|