-
-
Notifications
You must be signed in to change notification settings - Fork 192
/
memcache.go
198 lines (162 loc) · 4.73 KB
/
memcache.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
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
package store
import (
"context"
"errors"
"fmt"
"strings"
"time"
"golang.org/x/sync/errgroup"
"github.com/bradfitz/gomemcache/memcache"
)
// MemcacheClientInterface represents a bradfitz/gomemcache client
type MemcacheClientInterface interface {
Get(key string) (item *memcache.Item, err error)
Set(item *memcache.Item) error
Delete(item string) error
FlushAll() error
CompareAndSwap(item *memcache.Item) error
Add(item *memcache.Item) error
}
const (
// MemcacheType represents the storage type as a string value
MemcacheType = "memcache"
// MemcacheTagPattern represents the tag pattern to be used as a key in specified storage
MemcacheTagPattern = "gocache_tag_%s"
TagKeyExpiry = 720 * time.Hour
)
// MemcacheStore is a store for Memcache
type MemcacheStore struct {
client MemcacheClientInterface
options *Options
}
// NewMemcache creates a new store to Memcache instance(s)
func NewMemcache(client MemcacheClientInterface, options ...Option) *MemcacheStore {
return &MemcacheStore{
client: client,
options: applyOptions(options...),
}
}
// Get returns data stored from a given key
func (s *MemcacheStore) Get(_ context.Context, key any) (any, error) {
item, err := s.client.Get(key.(string))
if err != nil {
return nil, err
}
if item == nil {
return nil, NotFoundWithCause(errors.New("unable to retrieve data from memcache"))
}
return item.Value, err
}
// GetWithTTL returns data stored from a given key and its corresponding TTL
func (s *MemcacheStore) GetWithTTL(_ context.Context, key any) (any, time.Duration, error) {
item, err := s.client.Get(key.(string))
if err != nil {
return nil, 0, err
}
if item == nil {
return nil, 0, NotFoundWithCause(errors.New("unable to retrieve data from memcache"))
}
return item.Value, time.Duration(item.Expiration) * time.Second, err
}
// Set defines data in Memcache for given key identifier
func (s *MemcacheStore) Set(ctx context.Context, key any, value any, options ...Option) error {
opts := applyOptionsWithDefault(s.options, options...)
item := &memcache.Item{
Key: key.(string),
Value: value.([]byte),
Expiration: int32(opts.expiration.Seconds()),
}
err := s.client.Set(item)
if err != nil {
return err
}
if tags := opts.tags; len(tags) > 0 {
s.setTags(ctx, key, tags)
}
return nil
}
func (s *MemcacheStore) setTags(ctx context.Context, key any, tags []string) {
group, ctx := errgroup.WithContext(ctx)
for _, tag := range tags {
currentTag := tag
group.Go(func() error {
tagKey := fmt.Sprintf(MemcacheTagPattern, currentTag)
var err error
for i := 0; i < 3; i++ {
if err = s.addKeyToTagValue(tagKey, key); err == nil {
return nil
}
// loop to retry any failure (including race conditions)
}
return err
})
}
group.Wait()
}
func (s *MemcacheStore) addKeyToTagValue(tagKey string, key any) error {
var (
cacheKeys = []string{}
result *memcache.Item
err error
)
result, err = s.client.Get(tagKey)
if err == nil {
cacheKeys = strings.Split(string(result.Value), ",")
} else if !errors.Is(err, memcache.ErrCacheMiss) {
return err
}
for _, cacheKey := range cacheKeys {
// if key already exists, nothing to do
if cacheKey == key.(string) {
return nil
}
}
cacheKeys = append(cacheKeys, key.(string))
newVal := []byte(strings.Join(cacheKeys, ","))
if result == nil {
// if key didnt exist, use Add to create only if still not there
return s.client.Add(&memcache.Item{
Key: tagKey,
Value: newVal,
Expiration: int32(TagKeyExpiry.Seconds()),
})
}
// update existing value
// using CompareAndSwap to ensure not to run over writes between Get and here
result.Value = newVal
result.Expiration = int32(TagKeyExpiry.Seconds())
return s.client.CompareAndSwap(result)
}
// Delete removes data from Memcache for given key identifier
func (s *MemcacheStore) Delete(_ context.Context, key any) error {
return s.client.Delete(key.(string))
}
// Invalidate invalidates some cache data in Memcache for given options
func (s *MemcacheStore) Invalidate(ctx context.Context, options ...InvalidateOption) error {
opts := applyInvalidateOptions(options...)
if tags := opts.tags; len(tags) > 0 {
for _, tag := range tags {
tagKey := fmt.Sprintf(MemcacheTagPattern, tag)
result, err := s.Get(ctx, tagKey)
if err != nil {
return nil
}
cacheKeys := []string{}
if bytes, ok := result.([]byte); ok {
cacheKeys = strings.Split(string(bytes), ",")
}
for _, cacheKey := range cacheKeys {
s.Delete(ctx, cacheKey)
}
}
}
return nil
}
// Clear resets all data in the store
func (s *MemcacheStore) Clear(_ context.Context) error {
return s.client.FlushAll()
}
// GetType returns the store type
func (s *MemcacheStore) GetType() string {
return MemcacheType
}