Skip to content

fix: potential wrong total time in trace info when the request is invalid (#1016) #1017

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -1251,13 +1251,16 @@ func (r *Request) TraceInfo() TraceInfo {
RequestAttempt: r.Attempt,
}

// Calculate the total time accordingly,
// when connection is reused
if ct.gotConnInfo.Reused {
ti.TotalTime = ct.endTime.Sub(ct.getConn)
} else {
ti.TotalTime = ct.endTime.Sub(ct.dnsStart)
// Calculate the total time accordingly when connection is reused,
// and DNS start and get conn time may be zero if the request is invalid.
// See issue #1016.
requestStartTime := r.Time
if ct.gotConnInfo.Reused && !ct.getConn.IsZero() {
requestStartTime = ct.getConn
} else if !ct.dnsStart.IsZero() {
requestStartTime = ct.dnsStart
}
ti.TotalTime = ct.endTime.Sub(requestStartTime)

// Only calculate on successful connections
if !ct.connectDone.IsZero() {
Expand Down
12 changes: 12 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1830,6 +1830,18 @@ func TestTraceInfo(t *testing.T) {

})

t.Run("enable trace on invalid request, issue #1016", func(t *testing.T) {
resp, err := client.R().EnableTrace().Get("unknown://url.com")
assertNotNil(t, err)
tr := resp.Request.TraceInfo()
assertEqual(t, true, tr.DNSLookup == 0)
assertEqual(t, true, tr.ConnTime == 0)
assertEqual(t, true, tr.TLSHandshake == 0)
assertEqual(t, true, tr.ServerTime == 0)
assertEqual(t, true, tr.ResponseTime == 0)
assertEqual(t, true, tr.TotalTime > 0 && tr.TotalTime < time.Second)
})

t.Run("enable trace and debug on request", func(t *testing.T) {
c, logBuf := dcldb()
c.SetBaseURL(ts.URL)
Expand Down