-
Notifications
You must be signed in to change notification settings - Fork 0
/
anycache.go
394 lines (319 loc) · 9.57 KB
/
anycache.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
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// Package anycache provide laze caching with posibility to use diffent cache storages
package anycache
import (
"context"
"encoding/json"
"errors"
"math/rand"
"time"
"github.com/ksysoev/anycache/storage"
)
const (
HundredPercent = 100
)
// CacheStorage
type CacheStorage interface {
Get(context.Context, string) (string, error)
Set(context.Context, string, string, storage.CacheStorageItemOptions) error
TTL(context.Context, string) (bool, time.Duration, error)
Del(context.Context, string) (bool, error)
GetWithTTL(context.Context, string) (string, time.Duration, error)
Close() error
}
// Cache
type Cache struct {
Storage CacheStorage
ctx context.Context
cancelCtx context.CancelFunc
requests chan *CacheReuest
responses chan CacheResponse
cancel chan *CacheReuest
maxShiftTTL uint8 // max shift of TTL in persent
}
type CacheReuest struct {
generator CacheGenerator
ctx context.Context
response chan CacheResponse
key string
TTL time.Duration
WarmUpTTL time.Duration
}
type CacheResponse struct {
err error
key string
value string
warmingUp bool
}
type CacheQueue struct {
cancelCtx context.CancelFunc
currentValue string
requests []*CacheReuest
WarmingUp bool
}
type CacheGenerator func(ctx context.Context) (string, error)
type CacheOptions func(*Cache)
type CacheItemOptions func(*CacheReuest)
// NewCache creates a new Cache instance with the provided CacheStorage and CacheOptions.
// WithTTLRandomization sets max shift of TTL in persent
// It returns the created Cache instance.
func NewCache(store CacheStorage, opts ...CacheOptions) Cache {
ctx, cancelCtx := context.WithCancel(context.Background())
c := Cache{
Storage: store,
ctx: ctx,
cancelCtx: cancelCtx,
requests: make(chan *CacheReuest),
responses: make(chan CacheResponse),
cancel: make(chan *CacheReuest),
}
for _, opt := range opts {
opt(&c)
}
go c.requestHandler()
return c
}
// WithTTLRandomization sets max shift of TTL in persent
func WithTTLRandomization(maxShiftPercent uint8) func(*Cache) {
return func(c *Cache) {
c.maxShiftTTL = maxShiftPercent
}
}
// WithTTL sets TTL for cache item
func WithTTL(ttl time.Duration) CacheItemOptions {
return func(req *CacheReuest) {
req.TTL = ttl
}
}
// WithWarmUpTTL sets TTL threshold for cache item to be warmed up
func WithWarmUpTTL(ttl time.Duration) CacheItemOptions {
return func(req *CacheReuest) {
req.WarmUpTTL = ttl
}
}
func WithCtx(ctx context.Context) CacheItemOptions {
return func(req *CacheReuest) {
req.ctx = ctx
}
}
// Cache caches the result of the generator function for the given key.
// If the key already exists in the cache, the cached value is returned.
// Otherwise, the generator function is called to generate a new value,
// which is then cached and returned.
// The function takes an optional list of CacheItemOptions to customize the caching behavior.
// WithTTL sets TTL for cache item
// WithWarmUpTTL sets TTL threshold for cache item to be warmed up
func (c *Cache) Cache(key string, generator CacheGenerator, opts ...CacheItemOptions) (string, error) {
response := make(chan CacheResponse)
req := CacheReuest{
key: key,
generator: generator,
response: response,
ctx: context.Background(),
}
for _, opt := range opts {
opt(&req)
}
c.requests <- &req
select {
case <-req.ctx.Done():
c.cancel <- &req
return "", req.ctx.Err()
case resp := <-response:
return resp.value, resp.err
}
}
// CacheStruct caches the result of a function that returns a struct.
// The key is used to identify the cached value.
// The generator function is called to generate the value if it is not already cached.
// The result parameter is a pointer to the struct that will be populated with the cached value.
// The opts parameter is optional and can be used to set additional cache item options.
// WithTTL sets TTL for cache item
// WithWarmUpTTL sets TTL threshold for cache item to be warmed up
// Returns an error if there was a problem caching or unmarshalling the value.
func (c *Cache) CacheStruct(key string, generator func(context.Context) (any, error), result any, opts ...CacheItemOptions) error {
generatorWrapper := func(ctx context.Context) (string, error) {
val, err := generator(ctx)
if err != nil {
return "", err
}
jsonVal, err := json.Marshal(val)
if err != nil {
return "", err
}
return string(jsonVal), nil
}
val, err := c.Cache(key, generatorWrapper, opts...)
if err != nil {
return err
}
err = json.Unmarshal([]byte(val), result)
return err
}
func (c *Cache) requestHandler() {
requestStorage := map[string]CacheQueue{}
for {
select {
case req := <-c.requests:
reqQ, ok := requestStorage[req.key]
if ok {
if reqQ.WarmingUp {
req.response <- CacheResponse{
key: req.key,
value: reqQ.currentValue,
err: nil,
}
continue
}
reqQ.requests = append(reqQ.requests, req)
requestStorage[req.key] = reqQ
continue
}
ctx, cancel := context.WithCancel(context.Background())
requestStorage[req.key] = CacheQueue{
requests: []*CacheReuest{req},
cancelCtx: cancel,
}
reqCopy := *req
reqCopy.ctx = ctx
go c.processRequest(&reqCopy)
case resp := <-c.responses:
reqQ, ok := requestStorage[resp.key]
if !ok {
continue
}
if resp.warmingUp {
reqQ.currentValue = resp.value
reqQ.WarmingUp = true
processNow := reqQ.requests[1:]
reqQ.requests = reqQ.requests[:1]
requestStorage[resp.key] = reqQ
for _, req := range processNow {
req.response <- resp
close(req.response)
}
continue
}
for _, req := range reqQ.requests {
req.response <- resp
}
delete(requestStorage, resp.key)
case req := <-c.cancel:
reqQ, ok := requestStorage[req.key]
if !ok {
continue
}
close(req.response)
if len(reqQ.requests) == 1 {
reqQ.cancelCtx()
delete(requestStorage, req.key)
continue
}
for i, r := range reqQ.requests {
if r == req {
reqQ.requests = append(reqQ.requests[:i], reqQ.requests[i+1:]...)
requestStorage[req.key] = reqQ
break
}
}
case <-c.ctx.Done():
for _, reqQ := range requestStorage {
reqQ.cancelCtx()
for _, req := range reqQ.requests {
req.response <- CacheResponse{
key: req.key,
value: "",
err: c.ctx.Err(),
}
close(req.response)
}
}
return
}
}
}
// processRequest processes a cache request with the given key, generator function, and options.
// If the cache storage has a value for the key, it returns the value and any error encountered.
// If the cache storage does not have a value for the key, it generates a value using the provided generator function,
// sets it in the cache storage with the given key and options, and returns the generated value and any error encountered.
// If the cache item options include a warm-up TTL, it checks if the current TTL of the key is less than or equal to the warm-up TTL.
// If the current TTL is less than or equal to the warm-up TTL, it sets the value in the cache storage again with the same key and options,
// and returns the new value and any error encountered.
func (c *Cache) processRequest(req *CacheReuest) {
var (
value string
err error
needWarmUp bool
)
if req.WarmUpTTL.Nanoseconds() > 0 {
var ttl time.Duration
value, ttl, err = c.Storage.GetWithTTL(req.ctx, req.key)
readyForWarmUp := ttl.Nanoseconds() != 0 && ttl.Nanoseconds() <= req.WarmUpTTL.Nanoseconds()
if err == nil && readyForWarmUp {
needWarmUp = true
}
} else {
value, err = c.Storage.Get(req.ctx, req.key)
}
if err != nil && errors.Is(err, storage.KeyNotExistError{}) {
value, err = c.generateAndSet(req)
}
cacheResp := CacheResponse{
key: req.key,
value: value,
err: err,
warmingUp: needWarmUp,
}
select {
case c.responses <- cacheResp:
case <-req.ctx.Done():
return
}
if needWarmUp {
newVal, err := c.generateAndSet(req)
cacheResp := CacheResponse{
key: req.key,
value: newVal,
err: err,
warmingUp: false,
}
select {
case c.responses <- cacheResp:
case <-req.ctx.Done():
return
}
}
}
// generateAndSet generates a value using the provided generator function,
// sets it in the cache storage with the given key and options,
// and returns the generated value and any error encountered.
func (c *Cache) generateAndSet(req *CacheReuest) (string, error) {
value, err := req.generator(req.ctx)
if err != nil {
return value, err
}
ttl := randomizeTTL(c.maxShiftTTL, req.TTL)
err = c.Storage.Set(req.ctx, req.key, value, storage.CacheStorageItemOptions{TTL: ttl})
if err != nil {
return value, err
}
return value, nil
}
// randomizeTTL randomizes the TTL (time-to-live) duration by a percentage defined by persentOfRandomTTL constant.
// It takes a time.Duration as input and returns a time.Duration as output.
// If the input duration is zero, it returns the same duration.
func randomizeTTL(maxShiftTTL uint8, ttl time.Duration) time.Duration {
if maxShiftTTL == 0 || ttl.Nanoseconds() == 0 {
return ttl
}
MaxShift := ttl.Nanoseconds() * int64(maxShiftTTL) / HundredPercent
//nolint:gosec // we don't need cryptographically secure random number generator here
randomizedShift := int64(float64(MaxShift) * (float64(rand.Intn(HundredPercent)) - HundredPercent/2) / HundredPercent)
randomizedTTL := ttl.Nanoseconds() + randomizedShift
return time.Duration(randomizedTTL)
}
// Close closes the Cache instance.
// It returns an error if any occurred.
func (c *Cache) Close() error {
c.cancelCtx()
return c.Storage.Close()
}