-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstrategy.go
45 lines (36 loc) · 1.19 KB
/
strategy.go
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
package cache
import (
"time"
)
type CachingStrategy[T any] interface {
CleanupTick() time.Duration
IsExpired(*CachedElement[T]) bool
IsCleanable(*CachedElement[T]) bool
NewCachedElement(*CachedElement[T], T, error) (*CachedElement[T], error)
ShouldPropagateError(error) bool
}
type DefaultCachingStrategy[T any] struct {
expiration time.Duration
cleanup time.Duration
}
func NewDefaultCachingStrategy[T any](expiration time.Duration, cleanup time.Duration) *DefaultCachingStrategy[T] {
return &DefaultCachingStrategy[T]{expiration: expiration, cleanup: cleanup}
}
func (cs *DefaultCachingStrategy[T]) CleanupTick() time.Duration {
return cs.cleanup
}
func (cs *DefaultCachingStrategy[T]) IsExpired(e *CachedElement[T]) bool {
if cs.expiration != 0 {
return time.Since(e.Timestamp) >= cs.expiration
}
return false
}
func (cs *DefaultCachingStrategy[T]) IsCleanable(e *CachedElement[T]) bool {
return cs.IsExpired(e)
}
func (cs *DefaultCachingStrategy[T]) NewCachedElement(old *CachedElement[T], v T, e error) (*CachedElement[T], error) {
return &CachedElement[T]{Value: v, Timestamp: time.Now()}, e
}
func (cs *DefaultCachingStrategy[T]) ShouldPropagateError(err error) bool {
return true
}