From 4d94d72fbaa48d4a3bdaa693aaaa723ae9ea4da6 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Fri, 30 Jun 2023 21:53:21 -0700 Subject: [PATCH] metrics: add LabelMap.GetIncrFunc Updates tailscale/corp#7354 Signed-off-by: Brad Fitzpatrick --- metrics/metrics.go | 8 ++++++++ metrics/metrics_test.go | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/metrics/metrics.go b/metrics/metrics.go index 5a323dc38..b7339d02b 100644 --- a/metrics/metrics.go +++ b/metrics/metrics.go @@ -45,6 +45,14 @@ func (m *LabelMap) Get(key string) *expvar.Int { return m.Map.Get(key).(*expvar.Int) } +// GetIncrFunc returns a function that increments the expvar.Int named by key. +// +// Most callers should not need this; it exists to satisfy an +// interface elsewhere. +func (m *LabelMap) GetIncrFunc(key string) func(delta int64) { + return m.Get(key).Add +} + // GetFloat returns a direct pointer to the expvar.Float for key, creating it // if necessary. func (m *LabelMap) GetFloat(key string) *expvar.Float { diff --git a/metrics/metrics_test.go b/metrics/metrics_test.go index 1a2cf8d14..e170c7895 100644 --- a/metrics/metrics_test.go +++ b/metrics/metrics_test.go @@ -11,6 +11,18 @@ import ( "tailscale.com/tstest" ) +func TestLabelMap(t *testing.T) { + var m LabelMap + m.GetIncrFunc("foo")(1) + m.GetIncrFunc("bar")(2) + if g, w := m.Get("foo").Value(), int64(1); g != w { + t.Errorf("foo = %v; want %v", g, w) + } + if g, w := m.Get("bar").Value(), int64(2); g != w { + t.Errorf("bar = %v; want %v", g, w) + } +} + func TestCurrentFileDescriptors(t *testing.T) { if runtime.GOOS != "linux" { t.Skipf("skipping on %v", runtime.GOOS)