Skip to content

Commit

Permalink
metrics/RequestMeter: add label for X-From-Cache (sourcegraph#55774)
Browse files Browse the repository at this point in the history
  • Loading branch information
bobheadxi committed Aug 11, 2023
1 parent db39a90 commit 97813a5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
27 changes: 18 additions & 9 deletions internal/metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@ type RequestMeter struct {
}

const (
labelCategory = "category"
labelCode = "code"
labelHost = "host"
labelTask = "task"
labelCategory = "category"
labelCode = "code"
labelHost = "host"
labelTask = "task"
labelFromCache = "from_cache"
)

var taskKey struct{}
Expand All @@ -64,7 +65,7 @@ func NewRequestMeter(subsystem, help string) *RequestMeter {
Subsystem: subsystem,
Name: "requests_total",
Help: help,
}, []string{labelCategory, labelCode, labelHost, labelTask})
}, []string{labelCategory, labelCode, labelHost, labelTask, labelFromCache})
registerer.MustRegister(requestCounter)

// TODO(uwedeportivo):
Expand Down Expand Up @@ -136,12 +137,20 @@ func (t *requestCounterMiddleware) RoundTrip(r *http.Request) (resp *http.Respon
code = strconv.Itoa(resp.StatusCode)
}

// X-From-Cache=1 if the returned response is from the cache created by
// httpcli.NewCachedTransportOpt
var fromCache = "false"
if resp != nil && resp.Header.Get("X-From-Cache") != "" {
fromCache = "true"
}

d := time.Since(start)
t.meter.counter.With(map[string]string{
labelCategory: category,
labelCode: code,
labelHost: r.URL.Host,
labelTask: TaskFromContext(r.Context()),
labelCategory: category,
labelCode: code,
labelHost: r.URL.Host,
labelTask: TaskFromContext(r.Context()),
labelFromCache: fromCache,
}).Inc()

t.meter.duration.WithLabelValues(category, code, r.URL.Host).Observe(d.Seconds())
Expand Down
8 changes: 7 additions & 1 deletion internal/metrics/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,13 @@ func TestRequestMeterTransport(t *testing.T) {
t.Error(err)
}

c, err := rm.counter.GetMetricWith(map[string]string{labelCategory: "/apiCallA", labelCode: "200", labelHost: "foosystem.com", labelTask: "unknown"})
c, err := rm.counter.GetMetricWith(map[string]string{
labelCategory: "/apiCallA",
labelCode: "200",
labelHost: "foosystem.com",
labelTask: "unknown",
labelFromCache: "false",
})
if err != nil {
t.Error(err)
}
Expand Down

0 comments on commit 97813a5

Please sign in to comment.