Skip to content

Commit e4144d9

Browse files
author
Tyler Reid
committed
Wrap the defer in a function to make it defer after the return rather than after the if block. Add a unit test to validate we're tracking time correctly.
Signed-off-by: Tyler Reid <[email protected]>
1 parent 32033a8 commit e4144d9

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

pkg/ruler/compat.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ func MetricsQueryFunc(qf rules.QueryFunc, queries, failedQueries prometheus.Coun
151151
// If we've been passed a counter vec we want to record the wall time spent executing this request.
152152
if queryTime != nil {
153153
startTime = time.Now()
154-
defer queryTime.WithLabelValues(userID).Add(float64(time.Since(startTime)))
154+
defer func() { queryTime.WithLabelValues(userID).Add(float64(time.Since(startTime))) }()
155155
}
156156

157157
result, err := qf(ctx, qs, t)

pkg/ruler/compat_test.go

+19-2
Original file line numberDiff line numberDiff line change
@@ -231,8 +231,7 @@ func TestMetricsQueryFuncErrors(t *testing.T) {
231231
mockFunc := func(ctx context.Context, q string, t time.Time) (promql.Vector, error) {
232232
return promql.Vector{}, tc.returnedError
233233
}
234-
235-
qf := MetricsQueryFunc(mockFunc, queries, failures, queryTime, "user")
234+
qf := MetricsQueryFunc(mockFunc, queries, failures, queryTime, "userID")
236235

237236
_, err := qf(context.Background(), "test", time.Now())
238237
require.Equal(t, tc.returnedError, err)
@@ -242,3 +241,21 @@ func TestMetricsQueryFuncErrors(t *testing.T) {
242241
})
243242
}
244243
}
244+
245+
func TestMetricsQueryFuncMetrics(t *testing.T) {
246+
queries := prometheus.NewCounter(prometheus.CounterOpts{})
247+
failures := prometheus.NewCounter(prometheus.CounterOpts{})
248+
queryTime := prometheus.NewCounterVec(prometheus.CounterOpts{}, []string{"user"})
249+
250+
mockFunc := func(ctx context.Context, q string, t time.Time) (promql.Vector, error) {
251+
time.Sleep(1 * time.Millisecond)
252+
return promql.Vector{}, nil
253+
}
254+
qf := MetricsQueryFunc(mockFunc, queries, failures, queryTime, "userID")
255+
256+
_, _ = qf(context.Background(), "test", time.Now())
257+
258+
require.Equal(t, 1, int(testutil.ToFloat64(queries)))
259+
require.Equal(t, 0, int(testutil.ToFloat64(failures)))
260+
require.LessOrEqual(t, float64(1*time.Millisecond), testutil.ToFloat64(queryTime.WithLabelValues("userID")))
261+
}

0 commit comments

Comments
 (0)