-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
103 lines (89 loc) · 2.4 KB
/
cache.go
File metadata and controls
103 lines (89 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package featureflag
import (
"sync"
"time"
)
// cacheEntry holds a cached flag value together with its expiration timestamp.
type cacheEntry struct {
value FlagValue
expiresAt time.Time
}
// FlagCache is a thread-safe in-memory TTL cache for evaluated flag values.
// A TTL of zero disables caching (every Get returns a miss).
type FlagCache struct {
mu sync.RWMutex
entries map[string]cacheEntry // key = flagKey + "|" + userKey
ttl time.Duration
now func() time.Time // injectable clock for testing
}
// NewFlagCache creates a cache with the given TTL. Pass 0 to disable caching.
func NewFlagCache(ttl time.Duration) *FlagCache {
return &FlagCache{
entries: make(map[string]cacheEntry),
ttl: ttl,
now: time.Now,
}
}
// cacheKey builds a composite lookup key.
func cacheKey(flagKey, userKey string) string {
return flagKey + "|" + userKey
}
// Get returns the cached value and true if a non-expired entry exists.
func (c *FlagCache) Get(flagKey, userKey string) (FlagValue, bool) {
if c.ttl == 0 {
return FlagValue{}, false
}
c.mu.RLock()
entry, ok := c.entries[cacheKey(flagKey, userKey)]
c.mu.RUnlock()
if !ok {
return FlagValue{}, false
}
if c.now().After(entry.expiresAt) {
// Expired — lazily remove on next Set; the caller will fetch fresh.
return FlagValue{}, false
}
return entry.value, true
}
// Set stores a flag value in the cache. No-op when TTL is zero.
func (c *FlagCache) Set(flagKey, userKey string, val FlagValue) {
if c.ttl == 0 {
return
}
c.mu.Lock()
c.entries[cacheKey(flagKey, userKey)] = cacheEntry{
value: val,
expiresAt: c.now().Add(c.ttl),
}
c.mu.Unlock()
}
// Invalidate removes a single entry from the cache.
func (c *FlagCache) Invalidate(flagKey, userKey string) {
c.mu.Lock()
delete(c.entries, cacheKey(flagKey, userKey))
c.mu.Unlock()
}
// InvalidateFlag removes all entries for the given flag key.
func (c *FlagCache) InvalidateFlag(flagKey string) {
prefix := flagKey + "|"
c.mu.Lock()
for k := range c.entries {
if len(k) >= len(prefix) && k[:len(prefix)] == prefix {
delete(c.entries, k)
}
}
c.mu.Unlock()
}
// Flush removes all entries.
func (c *FlagCache) Flush() {
c.mu.Lock()
c.entries = make(map[string]cacheEntry)
c.mu.Unlock()
}
// Len returns the number of entries (including expired ones not yet evicted).
func (c *FlagCache) Len() int {
c.mu.RLock()
n := len(c.entries)
c.mu.RUnlock()
return n
}