-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic.go
107 lines (81 loc) · 1.84 KB
/
basic.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
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
package memory
import (
"context"
"errors"
"sync"
"time"
"github.com/juliaqiuxy/wfcache"
)
const NoTTL time.Duration = -1
type BasicStorage struct {
pairs map[string]*wfcache.CacheItem
ttl time.Duration
mutex sync.RWMutex
}
func Create(ttl time.Duration) wfcache.StorageMaker {
return func() (wfcache.Storage, error) {
if ttl == 0 {
return nil, errors.New("basic: storage requires a ttl")
}
s := &BasicStorage{
pairs: make(map[string]*wfcache.CacheItem),
ttl: ttl,
}
return s, nil
}
}
func (s *BasicStorage) TimeToLive() time.Duration {
return s.ttl
}
func (s *BasicStorage) Get(ctx context.Context, key string) *wfcache.CacheItem {
s.mutex.RLock()
defer s.mutex.RUnlock()
m, found := s.pairs[key]
if found {
if s.ttl == NoTTL || time.Now().UTC().Before(time.Unix(m.ExpiresAt, 0)) {
return m
} else {
s.Del(ctx, key)
}
}
return nil
}
func (s *BasicStorage) BatchGet(ctx context.Context, keys []string) (results []*wfcache.CacheItem) {
s.mutex.RLock()
defer s.mutex.RUnlock()
for _, key := range keys {
m := s.Get(ctx, key)
if m != nil {
results = append(results, m)
}
}
return results
}
func (s *BasicStorage) Set(ctx context.Context, key string, data []byte) error {
s.mutex.Lock()
defer s.mutex.Unlock()
s.pairs[key] = &wfcache.CacheItem{
Key: key,
Value: data,
ExpiresAt: time.Now().UTC().Add(s.ttl).Unix(),
}
return nil
}
func (s *BasicStorage) BatchSet(ctx context.Context, pairs map[string][]byte) error {
s.mutex.Lock()
defer s.mutex.Unlock()
for key, data := range pairs {
s.pairs[key] = &wfcache.CacheItem{
Key: key,
Value: data,
ExpiresAt: time.Now().UTC().Add(s.ttl).Unix(),
}
}
return nil
}
func (s *BasicStorage) Del(ctx context.Context, key string) error {
s.mutex.Lock()
defer s.mutex.Unlock()
delete(s.pairs, key)
return nil
}