-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
315 lines (253 loc) · 7.21 KB
/
Copy pathcache.go
File metadata and controls
315 lines (253 loc) · 7.21 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Package simplecache provides a small, generic, in-memory TTL cache.
package simplecache
import (
"errors"
"sync"
"time"
)
var (
// ErrInvalidTTL is returned when a cache is created with a non-positive TTL.
ErrInvalidTTL = errors.New("simplecache: ttl must be greater than zero")
// ErrNilCloneFunc is returned when a cache is created without a clone function.
ErrNilCloneFunc = errors.New("simplecache: clone function must not be nil")
// ErrNilLoadFunc is returned when GetOrSet is called without a load function.
ErrNilLoadFunc = errors.New("simplecache: load function must not be nil")
// ErrInvalidCleanupInterval is returned when background cleanup is started
// with a non-positive interval.
ErrInvalidCleanupInterval = errors.New("simplecache: cleanup interval must be greater than zero")
// ErrCleanupAlreadyRunning is returned when background cleanup is already running.
ErrCleanupAlreadyRunning = errors.New("simplecache: cleanup is already running")
)
// CloneFunc returns an independent copy of a cached value.
//
// The cache calls this function on Set and Get. For immutable values, use
// Identity. For mutable values, provide a clone function that copies every
// mutable field that must be protected from caller mutation. Clone functions
// must not mutate their input and must be safe to call concurrently.
type CloneFunc[V any] func(V) V
type entry[V any] struct {
id uint64
value V
expiresAt time.Time
}
// Cache is a concurrency-safe in-memory TTL cache.
//
// Values are copied on Set and Get using the configured CloneFunc. This avoids
// callers mutating the cached value through slices, maps, pointers, or structs
// containing mutable fields, as long as the CloneFunc performs the needed copy.
type Cache[K comparable, V any] struct {
mu sync.RWMutex
items map[K]entry[V]
ttl time.Duration
clone CloneFunc[V]
nextID uint64
cleanupMu sync.Mutex
cleanupStop chan struct{}
cleanupDone chan struct{}
}
// New creates a cache whose entries expire after ttl.
func New[K comparable, V any](ttl time.Duration, clone CloneFunc[V]) (*Cache[K, V], error) {
if ttl <= 0 {
return nil, ErrInvalidTTL
}
if clone == nil {
return nil, ErrNilCloneFunc
}
return &Cache[K, V]{
items: make(map[K]entry[V]),
ttl: ttl,
clone: clone,
}, nil
}
// NewAuto creates a cache whose entries expire after ttl and whose values are
// copied with DeepClone.
//
// NewAuto is convenient for common nested values, but reflection-based cloning
// cannot safely copy every Go value. For production-critical values,
// resource-owning values, or values with invariants, prefer New with a custom
// CloneFunc.
func NewAuto[K comparable, V any](ttl time.Duration) (*Cache[K, V], error) {
return New[K, V](ttl, DeepClone[V])
}
// MustNew creates a cache and panics if the configuration is invalid.
func MustNew[K comparable, V any](ttl time.Duration, clone CloneFunc[V]) *Cache[K, V] {
cache, err := New[K, V](ttl, clone)
if err != nil {
panic(err)
}
return cache
}
// MustNewAuto creates a cache with DeepClone and panics if ttl is invalid.
func MustNewAuto[K comparable, V any](ttl time.Duration) *Cache[K, V] {
cache, err := NewAuto[K, V](ttl)
if err != nil {
panic(err)
}
return cache
}
// Set stores value under key until the cache TTL expires.
func (c *Cache[K, V]) Set(key K, value V) {
_ = c.SetWithTTL(key, value, c.ttl)
}
// SetWithTTL stores value under key until ttl expires.
func (c *Cache[K, V]) SetWithTTL(key K, value V, ttl time.Duration) error {
if ttl <= 0 {
return ErrInvalidTTL
}
cloned := c.clone(value)
c.mu.Lock()
defer c.mu.Unlock()
c.nextID++
c.items[key] = entry[V]{
id: c.nextID,
value: cloned,
expiresAt: time.Now().Add(ttl),
}
return nil
}
// Get returns a cloned cached value if key exists and has not expired.
func (c *Cache[K, V]) Get(key K) (V, bool) {
var zero V
c.mu.RLock()
item, ok := c.items[key]
c.mu.RUnlock()
if !ok {
return zero, false
}
now := time.Now()
if !now.Before(item.expiresAt) {
c.mu.Lock()
current, exists := c.items[key]
if exists && current.id == item.id {
delete(c.items, key)
}
c.mu.Unlock()
return zero, false
}
return c.clone(item.value), true
}
// GetOrSet returns the cached value for key if it exists and has not expired.
//
// If key is missing or expired, fn is called outside the cache lock. The value
// returned by fn is stored with the cache's default TTL and returned with cached
// set to false. If fn returns an error, the value is not stored.
func (c *Cache[K, V]) GetOrSet(key K, fn func() (V, error)) (value V, cached bool, err error) {
if value, ok := c.Get(key); ok {
return value, true, nil
}
if fn == nil {
var zero V
return zero, false, ErrNilLoadFunc
}
value, err = fn()
if err != nil {
var zero V
return zero, false, err
}
c.Set(key, value)
return c.clone(value), false, nil
}
// Has reports whether key exists and has not expired.
func (c *Cache[K, V]) Has(key K) bool {
c.mu.RLock()
item, ok := c.items[key]
c.mu.RUnlock()
if !ok {
return false
}
if !time.Now().Before(item.expiresAt) {
c.mu.Lock()
current, exists := c.items[key]
if exists && current.id == item.id {
delete(c.items, key)
}
c.mu.Unlock()
return false
}
return true
}
// Delete removes key from the cache.
func (c *Cache[K, V]) Delete(key K) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.items, key)
}
// Clear removes all entries from the cache.
func (c *Cache[K, V]) Clear() {
c.mu.Lock()
defer c.mu.Unlock()
c.items = make(map[K]entry[V])
}
// DeleteExpired removes all expired entries and returns the number removed.
func (c *Cache[K, V]) DeleteExpired() int {
now := time.Now()
removed := 0
c.mu.Lock()
defer c.mu.Unlock()
for key, item := range c.items {
if !now.Before(item.expiresAt) {
delete(c.items, key)
removed++
}
}
return removed
}
// Len returns the number of stored entries, including entries that may have
// expired but have not been accessed or removed by DeleteExpired yet.
func (c *Cache[K, V]) Len() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.items)
}
// LenFresh removes expired entries and returns the number of unexpired entries.
func (c *Cache[K, V]) LenFresh() int {
c.DeleteExpired()
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.items)
}
// StartCleanup starts a background goroutine that periodically removes expired
// entries. The cache does not start background cleanup automatically.
func (c *Cache[K, V]) StartCleanup(interval time.Duration) error {
if interval <= 0 {
return ErrInvalidCleanupInterval
}
c.cleanupMu.Lock()
defer c.cleanupMu.Unlock()
if c.cleanupStop != nil {
return ErrCleanupAlreadyRunning
}
stop := make(chan struct{})
done := make(chan struct{})
c.cleanupStop = stop
c.cleanupDone = done
go func() {
defer close(done)
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
c.DeleteExpired()
case <-stop:
return
}
}
}()
return nil
}
// StopCleanup stops background cleanup if it is running.
func (c *Cache[K, V]) StopCleanup() {
c.cleanupMu.Lock()
stop := c.cleanupStop
done := c.cleanupDone
if stop == nil {
c.cleanupMu.Unlock()
return
}
c.cleanupStop = nil
c.cleanupDone = nil
close(stop)
c.cleanupMu.Unlock()
<-done
}