Skip to content

Commit

Permalink
let people configure cacheSize if they want
Browse files Browse the repository at this point in the history
  • Loading branch information
crockeo committed Jun 21, 2023
1 parent 0b47ff3 commit 0fdc92c
Showing 1 changed file with 25 additions and 5 deletions.
30 changes: 25 additions & 5 deletions stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ type Store interface {
Scope
}

// StoreOption configures a Store when constructed with NewStoreWithOptions.
type StoreOption func(*statStore)

// A Scope namespaces Statistics.
//
// store := stats.NewDefaultStore()
Expand Down Expand Up @@ -216,16 +219,32 @@ type StatGenerator interface {
// NewStore returns an Empty store that flushes to Sink passed as an argument.
// Note: the export argument is unused.
func NewStore(sink Sink, _ bool) Store {
return NewStoreWithOptions(sink)
}

// NewStoreWithOptions returns an Empty store that flushes to Sink passed as an argument.
func NewStoreWithOptions(sink Sink, options ...StoreOption) Store {
s := &statStore{sink: sink}
for _, option := range options {
option(s)
}

// lru.NewWithEvict can only return a non-nil error when cacheSize < 0.
cacheSize := 65536
s.counters, _ = lru.NewWithEvict(cacheSize, s.flushCounter)
s.timers, _ = lru.New[string, *timer](cacheSize)
s.counters, _ = lru.NewWithEvict(s.cacheSize, s.flushCounter)
s.timers, _ = lru.New[string, *timer](s.cacheSize)

return s
}

// WithCacheSize sets the maximum number of counters and timers gostats will cache.
// By default this value is 65,536 and it should be kept higher
// than the expected maximum number of counters or timers.
func WithCacheSize(cacheSize int) StoreOption {
return func(store *statStore) {
store.cacheSize = cacheSize
}
}

// NewDefaultStore returns a Store with a TCP statsd sink, and a running flush timer.
func NewDefaultStore() Store {
var newStore Store
Expand Down Expand Up @@ -345,8 +364,9 @@ func (ts *timespan) CompleteWithDuration(value time.Duration) {
}

type statStore struct {
counters *lru.Cache[string, *counter]
timers *lru.Cache[string, *timer]
cacheSize int
counters *lru.Cache[string, *counter]
timers *lru.Cache[string, *timer]
// Gauges must not be expunged because they are client-side stateful.
// We use a sync.Map instead of a cache to ensure they are kept indefinitely.
gauges sync.Map
Expand Down

0 comments on commit 0fdc92c

Please sign in to comment.