forked from argoproj/argo-cd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwolevelclient.go
68 lines (58 loc) · 2.05 KB
/
twolevelclient.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
package cache
import (
"context"
"time"
log "github.com/sirupsen/logrus"
)
// NewTwoLevelClient creates cache client that proxies requests to given external cache and tries to minimize
// number of requests to external client by storing cache entries in local in-memory cache.
func NewTwoLevelClient(client CacheClient, inMemoryExpiration time.Duration) *twoLevelClient {
return &twoLevelClient{inMemoryCache: NewInMemoryCache(inMemoryExpiration), externalCache: client}
}
type twoLevelClient struct {
inMemoryCache *InMemoryCache
externalCache CacheClient
}
// Set stores the given value in both in-memory and external cache.
// Skip storing the value in external cache if the same value already exists in memory to avoid requesting external cache.
func (c *twoLevelClient) Set(item *Item) error {
has, err := c.inMemoryCache.HasSame(item.Key, item.Object)
if has {
return nil
}
if err != nil {
log.Warnf("Failed to check key '%s' in in-memory cache: %v", item.Key, err)
}
err = c.inMemoryCache.Set(item)
if err != nil {
log.Warnf("Failed to save key '%s' in in-memory cache: %v", item.Key, err)
}
return c.externalCache.Set(item)
}
// Get returns cache value from in-memory cache if it present. Otherwise loads it from external cache and persists
// in memory to avoid future requests to external cache.
func (c *twoLevelClient) Get(key string, obj interface{}) error {
err := c.inMemoryCache.Get(key, obj)
if err == nil {
return nil
}
err = c.externalCache.Get(key, obj)
if err == nil {
_ = c.inMemoryCache.Set(&Item{Key: key, Object: obj})
}
return err
}
// Delete deletes cache for given key in both in-memory and external cache.
func (c *twoLevelClient) Delete(key string) error {
err := c.inMemoryCache.Delete(key)
if err != nil {
return err
}
return c.externalCache.Delete(key)
}
func (c *twoLevelClient) OnUpdated(ctx context.Context, key string, callback func() error) error {
return c.externalCache.OnUpdated(ctx, key, callback)
}
func (c *twoLevelClient) NotifyUpdated(key string) error {
return c.externalCache.NotifyUpdated(key)
}