-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
287 lines (238 loc) · 7.93 KB
/
Copy patherrors.go
File metadata and controls
287 lines (238 loc) · 7.93 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
package recorder
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net"
"strings"
"syscall"
)
// Error phases. The phase names the step of the HTTP exchange in which the
// failure was observed.
const (
PhaseRequestSetup = "request_setup"
PhaseDNS = "dns"
PhaseConnect = "connect"
PhaseProxy = "proxy"
PhaseTLS = "tls"
PhaseWriteRequest = "write_request"
PhaseWriteRequestBody = "write_request_body"
PhaseWaitResponse = "wait_response"
PhaseReadResponseHeaders = "read_response_headers"
PhaseReadResponseBody = "read_response_body"
PhaseRedirect = "redirect"
PhaseContext = "context"
PhaseUnknown = "unknown"
)
// ErrorInfo is the structured _recorder.error value describing a transport or
// body-stream failure.
type ErrorInfo struct {
// Phase is one of the Phase* constants.
Phase string `json:"phase"`
// Type is the innermost observed Go error type.
Type string `json:"type"`
// Message is the configured redacted top-level error text.
Message string `json:"message"`
// Timeout and Temporary preserve matching error interface facts.
Timeout bool `json:"timeout"`
Temporary bool `json:"temporary"`
// ContextCanceled and ContextDeadlineExceeded describe the request context,
// not merely an error that happens to match a context sentinel.
ContextCanceled bool `json:"contextCanceled"`
ContextDeadlineExceeded bool `json:"contextDeadlineExceeded"`
// Cause is the configured redacted context cause, when present.
Cause string `json:"cause,omitempty"`
// UnwrapChain lists bounded Go error type names from outermost to innermost.
UnwrapChain []string `json:"unwrapChain,omitempty"`
}
const maxUnwrapDepth = 32
// unwrapChain walks the error chain (following the first branch of joined
// errors), depth-capped so hostile Unwrap implementations cannot loop us.
func unwrapChain(err error) []error {
var chain []error
for e := err; e != nil && len(chain) < maxUnwrapDepth; {
chain = append(chain, e)
switch u := e.(type) {
case interface{ Unwrap() error }:
e = u.Unwrap()
case interface{ Unwrap() []error }:
if us := u.Unwrap(); len(us) > 0 {
e = us[0]
} else {
e = nil
}
default:
e = nil
}
}
return chain
}
// newErrorInfo builds the structured error record. ctxErr is the request
// context's Err() at failure time (nil when the context was still live);
// cause is the corresponding context.Cause. The ContextCanceled /
// ContextDeadlineExceeded flags require the request context to have actually
// fired: net/http timeout errors (e.g. ResponseHeaderTimeout's
// *http.timeoutError) deliberately match context errors via errors.Is, and
// must not masquerade as a caller-initiated cancellation.
func newErrorInfo(err error, phase string, red *redactor, ctxErr, cause error) *ErrorInfo {
if err == nil {
return nil
}
chain := unwrapChain(err)
info := &ErrorInfo{
Phase: phase,
Message: red.redactError(err.Error()),
ContextCanceled: ctxErr != nil && errors.Is(err, context.Canceled),
ContextDeadlineExceeded: ctxErr != nil && errors.Is(err, context.DeadlineExceeded),
}
info.UnwrapChain = make([]string, len(chain))
for i, e := range chain {
info.UnwrapChain[i] = fmt.Sprintf("%T", e)
}
info.Type = info.UnwrapChain[len(info.UnwrapChain)-1]
for _, e := range chain {
if t, ok := e.(interface{ Timeout() bool }); ok && t.Timeout() {
info.Timeout = true
}
if t, ok := e.(interface{ Temporary() bool }); ok && t.Temporary() {
info.Temporary = true
}
}
if info.ContextDeadlineExceeded {
info.Timeout = true
}
if cause != nil {
info.Cause = red.redactError(cause.Error())
}
return info
}
// classifyPhase determines the failure phase for an error returned by the
// underlying RoundTripper. Typed matching (errors.As / errors.Is) comes
// first; the httptrace progress recorded in v is the fallback. String
// matching is a last resort only, for errors that expose no type at all
// (the redirect-loop error assembled by http.Client). ctxDone reports
// whether the request's own context had fired when the error was observed.
func classifyPhase(err error, v traceView, hasProxy, respReceived, ctxDone bool, reqBodyReadErr error) string {
if err == nil {
return ""
}
// A read failure recorded on the caller-supplied request body means the
// transport aborted while streaming the body upward.
if reqBodyReadErr != nil && !respReceived {
return PhaseWriteRequestBody
}
var dnsErr *net.DNSError
if errors.As(err, &dnsErr) {
return PhaseDNS
}
if isTLSError(err) {
return PhaseTLS
}
var opErr *net.OpError
if errors.As(err, &opErr) {
switch opErr.Op {
case "dial":
if hasProxy {
return PhaseProxy
}
return PhaseConnect
case "write":
if !v.wroteHeaders.IsZero() {
return PhaseWriteRequestBody
}
return PhaseWriteRequest
case "read":
return readPhase(v, respReceived)
}
}
if errors.Is(err, syscall.ECONNREFUSED) {
if hasProxy {
return PhaseProxy
}
return PhaseConnect
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
// Prefer the network step that was in flight when the context fired;
// otherwise attribute the failure to the context itself — but only
// when the request's own context really fired. Transport-internal
// timeouts (net/http's ResponseHeaderTimeout error) merely match
// context errors via errors.Is and belong to the phase the exchange
// actually stood in.
switch p := phaseFromTrace(v, respReceived); p {
case PhaseDNS, PhaseConnect, PhaseTLS:
return p
}
if ctxDone {
return PhaseContext
}
return phaseFromTrace(v, respReceived)
}
// Last resort string match: http.Client's redirect-loop error carries no
// typed error to match on.
if msg := err.Error(); strings.Contains(msg, "stopped after") && strings.Contains(msg, "redirect") {
return PhaseRedirect
}
return phaseFromTrace(v, respReceived)
}
func readPhase(v traceView, respReceived bool) string {
if respReceived {
return PhaseReadResponseBody
}
if !v.firstByte.IsZero() {
return PhaseReadResponseHeaders
}
return PhaseWaitResponse
}
// phaseFromTrace derives the failure phase from how far the exchange
// progressed according to httptrace events.
func phaseFromTrace(v traceView, respReceived bool) string {
switch {
case respReceived:
return PhaseReadResponseBody
case !v.firstByte.IsZero():
return PhaseReadResponseHeaders
case !v.wroteRequest.IsZero() || !v.wroteHeaders.IsZero():
return PhaseWaitResponse
case !v.tlsStart.IsZero() && v.tlsDone.IsZero():
return PhaseTLS
case !v.connectStart.IsZero() && v.connectDone.IsZero():
return PhaseConnect
case !v.dnsStart.IsZero() && v.dnsDone.IsZero():
return PhaseDNS
case !v.gotConn.IsZero():
return PhaseWriteRequest
case v.getConn.IsZero() && v.dnsStart.IsZero() && v.connectStart.IsZero():
return PhaseRequestSetup
default:
return PhaseUnknown
}
}
// isTLSError reports whether the chain contains a TLS or certificate
// verification error. Typed checks first; the package prefix of unexported
// types (tls alerts, net/http's tlsHandshakeTimeoutError) is the fallback.
func isTLSError(err error) bool {
var (
hostnameErr x509.HostnameError
caErr x509.UnknownAuthorityError
invalidErr x509.CertificateInvalidError
rootsErr x509.SystemRootsError
recordErr tls.RecordHeaderError
verifyErr *tls.CertificateVerificationError
)
if errors.As(err, &hostnameErr) || errors.As(err, &caErr) ||
errors.As(err, &invalidErr) || errors.As(err, &rootsErr) ||
errors.As(err, &recordErr) || errors.As(err, &verifyErr) {
return true
}
for _, e := range unwrapChain(err) {
tn := fmt.Sprintf("%T", e)
if strings.HasPrefix(tn, "tls.") || strings.HasPrefix(tn, "*tls.") ||
strings.HasPrefix(tn, "x509.") || strings.HasPrefix(tn, "*x509.") ||
strings.Contains(tn, "tlsHandshakeTimeout") {
return true
}
}
return false
}