GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(rate): add in-memory sliding window counter store · majorcontext/keep@f154f8b

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • internal/rate
    • counter.go
    • counter_test.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎internal/rate/counter.go‎

Copy file name to clipboard
+88Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// Package rate provides an in-memory sliding window counter store
2+
// for Keep's rateCount() CEL function.
3+
package rate
4+
5+
import (
6+
"sync"
7+
"time"
8+
)
9+
10+
// Clock abstracts time for testing.
11+
type Clock interface {
12+
Now() time.Time
13+
}
14+
15+
// realClock uses time.Now.
16+
type realClock struct{}
17+
18+
func (realClock) Now() time.Time { return time.Now() }
19+
20+
// Store is a thread-safe sliding window counter store.
21+
type Store struct {
22+
mu sync.Mutex
23+
data map[string][]time.Time
24+
clock Clock
25+
}
26+
27+
// NewStore creates a new counter store using real time.
28+
func NewStore() *Store {
29+
return &Store{
30+
data: make(map[string][]time.Time),
31+
clock: realClock{},
32+
}
33+
}
34+
35+
// NewStoreWithClock creates a store with a custom clock for testing.
36+
func NewStoreWithClock(clock Clock) *Store {
37+
return &Store{
38+
data: make(map[string][]time.Time),
39+
clock: clock,
40+
}
41+
}
42+
43+
// Increment records a hit for the given key at the current time.
44+
func (s *Store) Increment(key string) {
45+
s.mu.Lock()
46+
defer s.mu.Unlock()
47+
s.data[key] = append(s.data[key], s.clock.Now())
48+
}
49+
50+
// Count returns the number of hits for key within the given window duration.
51+
func (s *Store) Count(key string, window time.Duration) int {
52+
s.mu.Lock()
53+
defer s.mu.Unlock()
54+
55+
cutoff := s.clock.Now().Add(-window)
56+
timestamps := s.data[key]
57+
58+
count := 0
59+
for _, ts := range timestamps {
60+
if !ts.Before(cutoff) {
61+
count++
62+
}
63+
}
64+
return count
65+
}
66+
67+
// GC removes entries older than maxAge from all keys.
68+
// Removes keys that become empty.
69+
func (s *Store) GC(maxAge time.Duration) {
70+
s.mu.Lock()
71+
defer s.mu.Unlock()
72+
73+
cutoff := s.clock.Now().Add(-maxAge)
74+
75+
for key, timestamps := range s.data {
76+
fresh := timestamps[:0]
77+
for _, ts := range timestamps {
78+
if ts.After(cutoff) {
79+
fresh = append(fresh, ts)
80+
}
81+
}
82+
if len(fresh) == 0 {
83+
delete(s.data, key)
84+
} else {
85+
s.data[key] = fresh
86+
}
87+
}
88+
}
Collapse file

‎internal/rate/counter_test.go‎

Copy file name to clipboard
+162Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
package rate
2+
3+
import (
4+
"sync"
5+
"testing"
6+
"time"
7+
)
8+
9+
// mockClock is a controllable clock for testing.
10+
type mockClock struct {
11+
mu sync.Mutex
12+
t time.Time
13+
}
14+
15+
func (c *mockClock) Now() time.Time {
16+
c.mu.Lock()
17+
defer c.mu.Unlock()
18+
return c.t
19+
}
20+
21+
func (c *mockClock) Advance(d time.Duration) {
22+
c.mu.Lock()
23+
defer c.mu.Unlock()
24+
c.t = c.t.Add(d)
25+
}
26+
27+
func newMockClock() *mockClock {
28+
return &mockClock{t: time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)}
29+
}
30+
31+
func TestCounter_Increment(t *testing.T) {
32+
clk := newMockClock()
33+
s := NewStoreWithClock(clk)
34+
35+
s.Increment("key1")
36+
37+
if got := s.Count("key1", time.Minute); got != 1 {
38+
t.Errorf("Count() = %d, want 1", got)
39+
}
40+
}
41+
42+
func TestCounter_MultipleIncrements(t *testing.T) {
43+
clk := newMockClock()
44+
s := NewStoreWithClock(clk)
45+
46+
for i := 0; i < 5; i++ {
47+
s.Increment("key1")
48+
}
49+
50+
if got := s.Count("key1", time.Minute); got != 5 {
51+
t.Errorf("Count() = %d, want 5", got)
52+
}
53+
}
54+
55+
func TestCounter_WindowExpiry(t *testing.T) {
56+
clk := newMockClock()
57+
s := NewStoreWithClock(clk)
58+
59+
s.Increment("key1")
60+
61+
// Advance past the window
62+
clk.Advance(2 * time.Minute)
63+
64+
if got := s.Count("key1", time.Minute); got != 0 {
65+
t.Errorf("Count() = %d, want 0 after window expiry", got)
66+
}
67+
}
68+
69+
func TestCounter_SlidingWindow(t *testing.T) {
70+
clk := newMockClock()
71+
s := NewStoreWithClock(clk)
72+
73+
// t=0: increment
74+
s.Increment("key1")
75+
76+
// t=30s: increment
77+
clk.Advance(30 * time.Second)
78+
s.Increment("key1")
79+
80+
// t=90s: increment; with 1m window, t=0 hit has expired
81+
clk.Advance(60 * time.Second)
82+
s.Increment("key1")
83+
84+
// At t=90s with 1m window: t=0 is expired, t=30s and t=90s are within window
85+
if got := s.Count("key1", time.Minute); got != 2 {
86+
t.Errorf("Count() = %d, want 2 (t=0 should be expired)", got)
87+
}
88+
}
89+
90+
func TestCounter_IndependentKeys(t *testing.T) {
91+
clk := newMockClock()
92+
s := NewStoreWithClock(clk)
93+
94+
s.Increment("keyA")
95+
s.Increment("keyA")
96+
s.Increment("keyA")
97+
98+
s.Increment("keyB")
99+
s.Increment("keyB")
100+
101+
if got := s.Count("keyA", time.Minute); got != 3 {
102+
t.Errorf("Count(keyA) = %d, want 3", got)
103+
}
104+
if got := s.Count("keyB", time.Minute); got != 2 {
105+
t.Errorf("Count(keyB) = %d, want 2", got)
106+
}
107+
}
108+
109+
func TestCounter_Concurrent(t *testing.T) {
110+
s := NewStore()
111+
112+
const goroutines = 100
113+
var wg sync.WaitGroup
114+
wg.Add(goroutines)
115+
116+
for i := 0; i < goroutines; i++ {
117+
go func() {
118+
defer wg.Done()
119+
s.Increment("shared-key")
120+
}()
121+
}
122+
123+
wg.Wait()
124+
125+
if got := s.Count("shared-key", time.Minute); got != goroutines {
126+
t.Errorf("Count() = %d, want %d after concurrent increments", got, goroutines)
127+
}
128+
}
129+
130+
func TestCounter_GC(t *testing.T) {
131+
clk := newMockClock()
132+
s := NewStoreWithClock(clk)
133+
134+
s.Increment("key1")
135+
s.Increment("key2")
136+
137+
// Advance time so entries are old
138+
clk.Advance(5 * time.Minute)
139+
140+
// Add a fresh entry for key2
141+
s.Increment("key2")
142+
143+
// GC entries older than 2 minutes
144+
s.GC(2 * time.Minute)
145+
146+
// key1 should be fully removed (all entries expired)
147+
s.mu.Lock()
148+
_, hasKey1 := s.data["key1"]
149+
_, hasKey2 := s.data["key2"]
150+
key2Len := len(s.data["key2"])
151+
s.mu.Unlock()
152+
153+
if hasKey1 {
154+
t.Error("GC should have removed key1 entirely")
155+
}
156+
if !hasKey2 {
157+
t.Error("GC should have kept key2 (has a fresh entry)")
158+
}
159+
if key2Len != 1 {
160+
t.Errorf("key2 should have 1 entry after GC, got %d", key2Len)
161+
}
162+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.