request: provide observability over HTTP request latency (#848)

This commit is contained in:
Luis Rascão
2021-12-17 00:39:34 +00:00
committed by GitHub
parent 6232914112
commit 15fcfe60a9
4 changed files with 34 additions and 0 deletions

View File

@@ -20,3 +20,10 @@ func WithRetryPolicy(p RetryPolicy) RequesterOption {
r.retryPolicy = p
}
}
// WithReporter configures the reporter for a Requester.
func WithReporter(rep Reporter) RequesterOption {
return func(r *Requester) {
r.reporter = rep
}
}

View File

@@ -0,0 +1,17 @@
package request
import (
"time"
)
// Reporter interface groups observability functionality over
// HTTP request latency.
type Reporter interface {
Latency(name, method, path string, t time.Duration)
}
// SetupGlobalReporter sets a reporter interface to be used
// for all exchange requests
func SetupGlobalReporter(r Reporter) {
globalReporter = r
}

View File

@@ -39,6 +39,7 @@ func New(name string, httpRequester *http.Client, opts ...RequesterOption) *Requ
retryPolicy: DefaultRetryPolicy,
maxRetries: MaxRetryAttempts,
timedLock: timedmutex.NewTimedMutex(DefaultMutexLockTimeout),
reporter: globalReporter,
}
for _, o := range opts {
@@ -150,7 +151,14 @@ func (r *Requester) doRequest(ctx context.Context, endpoint EndpointLimit, newRe
}
}
start := time.Now()
resp, err := r.HTTPClient.Do(req)
if r.reporter != nil {
r.reporter.Latency(r.Name, p.Method, p.Path, time.Since(start))
}
if retry, checkErr := r.retryPolicy(resp, err); checkErr != nil {
return checkErr
} else if retry {

View File

@@ -23,12 +23,14 @@ const (
var (
MaxRequestJobs = DefaultMaxRequestJobs
MaxRetryAttempts = DefaultMaxRetryAttempts
globalReporter Reporter
)
// Requester struct for the request client
type Requester struct {
HTTPClient *http.Client
limiter Limiter
reporter Reporter
Name string
UserAgent string
maxRetries int