-
Notifications
You must be signed in to change notification settings - Fork 4
/
core.go
290 lines (262 loc) · 8.09 KB
/
core.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
package mnemosyne
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/go-redis/redis"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
// Mnemosyne is the parent object which holds all cache instances
type Mnemosyne struct {
childs map[string]*MnemosyneInstance
}
// MnemosyneInstance is an instance of a multi-layer cache
type MnemosyneInstance struct {
name string
cacheLayers []*cache
cacheWatcher ICounter
softTTL time.Duration
}
// ErrCacheMiss is the Error returned when a cache miss happens
type ErrCacheMiss struct {
message string
}
func (e *ErrCacheMiss) Error() string {
return e.message
}
// NewMnemosyne initializes the Mnemosyne object which holds all the cache instances
func NewMnemosyne(config *viper.Viper, commTimer ITimer, cacheHitCounter ICounter) *Mnemosyne {
if commTimer == nil {
commTimer = NewDummyTimer()
}
if cacheHitCounter == nil {
cacheHitCounter = NewDummyCounter()
}
cacheConfigs := config.GetStringMap("cache")
caches := make(map[string]*MnemosyneInstance, len(cacheConfigs))
for cacheName := range cacheConfigs {
caches[cacheName] = newMnemosyneInstance(cacheName, config, commTimer, cacheHitCounter)
}
return &Mnemosyne{
childs: caches,
}
}
// Select returns a cache instance selected by name
func (m *Mnemosyne) Select(cacheName string) *MnemosyneInstance {
return m.childs[cacheName]
}
func newMnemosyneInstance(name string, config *viper.Viper, commTimer ITimer, hitCounter ICounter) *MnemosyneInstance {
configKeyPrefix := fmt.Sprintf("cache.%s", name)
layerNames := config.GetStringSlice(configKeyPrefix + ".layers")
cacheLayers := make([]*cache, len(layerNames))
for i, layerName := range layerNames {
keyPrefix := configKeyPrefix + "." + layerName
layerType := config.GetString(keyPrefix + ".type")
if layerType == "memory" {
cacheLayers[i] = newCacheInMem(
layerName,
config.GetInt(keyPrefix+".max-memory"),
config.GetDuration(keyPrefix+".ttl"),
config.GetInt(keyPrefix+".amnesia"),
config.GetBool(keyPrefix+".compression"),
)
} else if layerType == "redis" {
cacheLayers[i] = newCacheRedis(
layerName,
config.GetString(keyPrefix+".address"),
config.GetInt(keyPrefix+".db"),
config.GetDuration(keyPrefix+".ttl"),
config.GetDuration(keyPrefix+".idle-timeout"),
config.GetInt(keyPrefix+".amnesia"),
config.GetBool(keyPrefix+".compression"),
commTimer,
)
} else if layerType == "gaurdian" {
cacheLayers[i] = newCacheClusterRedis(
layerName,
config.GetString(keyPrefix+".address"),
config.GetStringSlice(keyPrefix+".slaves"),
config.GetInt(keyPrefix+".db"),
config.GetDuration(keyPrefix+".ttl"),
config.GetDuration(keyPrefix+".idle-timeout"),
config.GetInt(keyPrefix+".amnesia"),
config.GetBool(keyPrefix+".compression"),
commTimer,
)
} else if layerType == "tiny" {
cacheLayers[i] = newCacheTiny(
layerName,
config.GetInt(keyPrefix+".amnesia"),
config.GetBool(keyPrefix+".compression"),
)
} else {
logrus.Errorf("Malformed Config: Unknown cache type %s", layerType)
return nil
}
}
return &MnemosyneInstance{
name: name,
cacheLayers: cacheLayers,
cacheWatcher: hitCounter,
softTTL: config.GetDuration(configKeyPrefix + ".soft-ttl"),
}
}
func (mn *MnemosyneInstance) get(ctx context.Context, key string) (*cachableRet, error) {
cacheErrors := make([]error, len(mn.cacheLayers))
var result *cachableRet
for i, layer := range mn.cacheLayers {
result, cacheErrors[i] = layer.withContext(ctx).get(key)
if cacheErrors[i] == nil {
go mn.cacheWatcher.Inc(mn.name, fmt.Sprintf("layer%d", i))
go mn.fillUpperLayers(key, result, i)
return result, nil
}
}
go mn.cacheWatcher.Inc(mn.name, "miss")
return nil, &ErrCacheMiss{message: "Miss"} // FIXME: better Error combination
}
// Get retrieves the value for key
func (mn *MnemosyneInstance) Get(ctx context.Context, key string, ref interface{}) error {
cachableObj, err := mn.get(ctx, key)
if err != nil {
return err
}
if cachableObj == nil || cachableObj.CachedObject == nil {
logrus.WithFields(logrus.Fields{
"key": key,
"value": cachableObj,
}).Errorf("nil object found in cache")
return errors.New("nil found")
}
err = json.Unmarshal(*cachableObj.CachedObject, ref)
if err != nil {
return err
}
return nil
}
// GetAndShouldUpdate retrieves the value for key and also shows whether the soft-TTL of that key has passed or not
func (mn *MnemosyneInstance) GetAndShouldUpdate(ctx context.Context, key string, ref interface{}) (bool, error) {
cachableObj, err := mn.get(ctx, key)
if err == redis.Nil {
return true, err
} else if err != nil {
return false, err
}
if cachableObj == nil || cachableObj.CachedObject == nil {
logrus.WithFields(logrus.Fields{
"key": key,
"value": cachableObj,
}).Errorf("nil object found in cache")
return false, errors.New("nil found")
}
err = json.Unmarshal(*cachableObj.CachedObject, ref)
if err != nil {
return false, err
}
dataAge := time.Now().Sub(cachableObj.Time)
go mn.monitorDataHotness(dataAge)
shouldUpdate := dataAge > mn.softTTL
return shouldUpdate, nil
}
// ShouldUpdate shows whether the soft-TTL of a key has passed or not
func (mn *MnemosyneInstance) ShouldUpdate(ctx context.Context, key string) (bool, error) {
cachableObj, err := mn.get(ctx, key)
if err == redis.Nil {
return true, err
} else if err != nil {
return false, err
}
if cachableObj == nil || cachableObj.CachedObject == nil {
logrus.WithFields(logrus.Fields{
"key": key,
"value": cachableObj,
}).Errorf("nil object found in cache")
return false, errors.New("nil found")
}
shouldUpdate := time.Now().Sub(cachableObj.Time) > mn.softTTL
return shouldUpdate, nil
}
// Set sets the value for a key in all layers of the cache instance
func (mn *MnemosyneInstance) Set(ctx context.Context, key string, value interface{}) error {
if value == nil {
return fmt.Errorf("cannot set nil value in cache")
}
toCache := cachable{
CachedObject: value,
Time: time.Now(),
}
cacheErrors := make([]error, len(mn.cacheLayers))
errorStrings := make([]string, len(mn.cacheLayers))
haveErorr := false
for i, layer := range mn.cacheLayers {
cacheErrors[i] = layer.withContext(ctx).set(key, toCache)
if cacheErrors[i] != nil {
errorStrings[i] = cacheErrors[i].Error()
haveErorr = true
}
}
if haveErorr {
return fmt.Errorf(strings.Join(errorStrings, ";"))
}
return nil
}
// TTL returns the TTL of the first accessible data instance as well as the layer it was found on
func (mn *MnemosyneInstance) TTL(key string) (int, time.Duration) {
for i, layer := range mn.cacheLayers {
dur := layer.getTTL(key)
if dur > 0 {
return i, dur
}
}
return -1, time.Second * 0
}
// Delete removes a key from all the layers (if exists)
func (mn *MnemosyneInstance) Delete(ctx context.Context, key string) error {
cacheErrors := make([]error, len(mn.cacheLayers))
errorStrings := make([]string, len(mn.cacheLayers))
haveErorr := false
for i, layer := range mn.cacheLayers {
cacheErrors[i] = layer.delete(ctx, key)
if cacheErrors[i] != nil {
errorStrings[i] = cacheErrors[i].Error()
haveErorr = true
}
}
if haveErorr {
return fmt.Errorf(strings.Join(errorStrings, ";"))
}
return nil
}
// Flush completly clears a single layer of the cache
func (mn *MnemosyneInstance) Flush(targetLayerName string) error {
for _, layer := range mn.cacheLayers {
if layer.layerName == targetLayerName {
return layer.clear()
}
}
return fmt.Errorf("Layer Named: %v Not Found", targetLayerName)
}
func (mn *MnemosyneInstance) fillUpperLayers(key string, value *cachableRet, layer int) {
for i := layer - 1; i >= 0; i-- {
if value == nil {
continue
}
err := mn.cacheLayers[i].set(key, *value)
if err != nil {
logrus.Errorf("failed to fill layer %d : %v", i, err)
}
}
}
func (mn *MnemosyneInstance) monitorDataHotness(age time.Duration) {
if age <= mn.softTTL {
mn.cacheWatcher.Inc(mn.name+"-hotness", "hot")
} else if age <= mn.softTTL*2 {
mn.cacheWatcher.Inc(mn.name+"-hotness", "warm")
} else {
mn.cacheWatcher.Inc(mn.name+"-hotness", "cold")
}
}