From adc742b4779669ade2277e347fcf5128363935f5 Mon Sep 17 00:00:00 2001 From: Yuri Shkuro Date: Fri, 3 Mar 2017 15:23:36 -0500 Subject: [PATCH] Fix typo and optimize cache overflow --- rpcmetrics/endpoints.go | 15 ++++++++++++--- rpcmetrics/endpoints_test.go | 7 +++++++ rpcmetrics/observer.go | 2 +- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/rpcmetrics/endpoints.go b/rpcmetrics/endpoints.go index b35b46d8..79ec1c8e 100644 --- a/rpcmetrics/endpoints.go +++ b/rpcmetrics/endpoints.go @@ -44,14 +44,23 @@ func newNormalizedEndpoints(maxSize int, normalizer NameNormalizer) *normalizedE // names it returns "" for all other names beyond those already cached. func (n *normalizedEndpoints) normalize(name string) string { n.mux.RLock() - norm := n.names[name] + norm, ok := n.names[name] + l := len(n.names) n.mux.RUnlock() - if norm != "" { + if ok { return norm } - norm = n.normalizer.Normalize(name) + if l >= n.maxSize { + return "" + } + return n.normalizeWithLock(name) +} + +func (n *normalizedEndpoints) normalizeWithLock(name string) string { + norm := n.normalizer.Normalize(name) n.mux.Lock() defer n.mux.Unlock() + // cache may have grown while we were not holding the lock if len(n.names) >= n.maxSize { return "" } diff --git a/rpcmetrics/endpoints_test.go b/rpcmetrics/endpoints_test.go index 6593bee7..39219e5e 100644 --- a/rpcmetrics/endpoints_test.go +++ b/rpcmetrics/endpoints_test.go @@ -39,4 +39,11 @@ func TestNormalizedEndpoints(t *testing.T) { assert.Equal(t, "ab-cd", n.normalize("ab^cd"), "cache hit") assertLen(1) assert.Equal(t, "", n.normalize("xys"), "cache overflow") + assertLen(1) +} + +func TestNormalizedEndpointsDoubleLocking(t *testing.T) { + n := newNormalizedEndpoints(1, DefaultNameNormalizer) + assert.Equal(t, "ab-cd", n.normalize("ab^cd"), "fill out the cache") + assert.Equal(t, "", n.normalizeWithLock("xys"), "cache overflow") } diff --git a/rpcmetrics/observer.go b/rpcmetrics/observer.go index 8db210d7..4cf5912d 100644 --- a/rpcmetrics/observer.go +++ b/rpcmetrics/observer.go @@ -39,7 +39,7 @@ type Observer struct { metricsByEndpoint *MetricsByEndpoint } -// NewObserver creates a new observer that can emit RPC metricso. +// NewObserver creates a new observer that can emit RPC metrics. func NewObserver(metricsFactory metrics.Factory, normalizer NameNormalizer) *Observer { return &Observer{ metricsByEndpoint: newMetricsByEndpoint(