Refactor for readability
This commit is contained in:
1 parent
ff9860023b
commit
17baba1490
11 files changed
+536
-405
No files matched your search
@@ -0,0 +1,57 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MaxHistoryPoints = 10000
|
||||
|
||||
type Sample struct {
|
||||
At time.Time
|
||||
Value int
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
mu sync.RWMutex
|
||||
value int
|
||||
updatedAt time.Time
|
||||
history []Sample
|
||||
}
|
||||
|
||||
func (s *Store) Get() int {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.value
|
||||
}
|
||||
|
||||
func (s *Store) Set(v int) {
|
||||
s.mu.Lock()
|
||||
s.value = v
|
||||
now := time.Now()
|
||||
s.updatedAt = now
|
||||
s.history = append(s.history, Sample{At: now, Value: v})
|
||||
s.trimHistoryLocked(now)
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Store) trimHistoryLocked(now time.Time) {
|
||||
cutoff := now.Add(-12 * time.Hour)
|
||||
keep := s.history[:0]
|
||||
for _, point := range s.history {
|
||||
if point.At.After(cutoff) {
|
||||
keep = append(keep, point)
|
||||
}
|
||||
}
|
||||
if len(keep) > MaxHistoryPoints {
|
||||
keep = keep[len(keep)-MaxHistoryPoints:]
|
||||
}
|
||||
s.history = keep
|
||||
}
|
||||
|
||||
func (s *Store) Snapshot() (int, time.Time, []Sample) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
history := append([]Sample(nil), s.history...)
|
||||
return s.value, s.updatedAt, history
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTrimHistoryToMaxPoints(t *testing.T) {
|
||||
s := &Store{}
|
||||
base := time.Date(2026, 4, 20, 0, 0, 0, 0, time.UTC)
|
||||
s.history = make([]Sample, 0, MaxHistoryPoints+25)
|
||||
for i := 0; i < MaxHistoryPoints+25; i++ {
|
||||
s.history = append(s.history, Sample{At: base.Add(time.Duration(i) * time.Second), Value: i})
|
||||
}
|
||||
|
||||
s.trimHistoryLocked(base.Add(time.Duration(MaxHistoryPoints+25) * time.Second))
|
||||
|
||||
if got := len(s.history); got != MaxHistoryPoints {
|
||||
t.Fatalf("history length = %d, want %d", got, MaxHistoryPoints)
|
||||
}
|
||||
if s.history[0].Value != 25 {
|
||||
t.Fatalf("oldest retained value = %d, want %d", s.history[0].Value, 25)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user