-
Notifications
You must be signed in to change notification settings - Fork 23
/
cache.go
500 lines (461 loc) · 15.1 KB
/
cache.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package flowcontrol
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/buraksezer/olric"
olricconfig "github.com/buraksezer/olric/config"
flowcontrolv1 "github.com/fluxninja/aperture/api/v2/gen/proto/go/aperture/flowcontrol/check/v1"
distcache "github.com/fluxninja/aperture/v2/pkg/dist-cache"
"github.com/fluxninja/aperture/v2/pkg/log"
"github.com/fluxninja/aperture/v2/pkg/metrics"
panichandler "github.com/fluxninja/aperture/v2/pkg/panic-handler"
"github.com/fluxninja/aperture/v2/pkg/policies/flowcontrol/iface"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/fx"
)
var (
// ErrCacheKeyEmpty is the error returned when the cache key is empty.
ErrCacheKeyEmpty = errors.New("cache key cannot be empty")
// ErrCacheControlPointEmpty is the error returned when the cache control point is empty.
ErrCacheControlPointEmpty = errors.New("cache control_point cannot be empty")
// ErrCacheNotReady is the error returned when the cache is not ready to be used.
ErrCacheNotReady = errors.New("cache is not ready")
// ErrCacheKeyNotFound is the error returned when the key is not found in the cache. This is copied from the internal olric package.
ErrCacheKeyNotFound = errors.New("key not found")
)
// Cache for saving responses at flow end.
type Cache struct {
dmapCache olric.DMap
cacheLookupHitsTotal *prometheus.CounterVec
cacheMissesTotal *prometheus.CounterVec
cacheOperationResultsTotal *prometheus.CounterVec
}
// Cache implements iface.Cache.
var _ iface.Cache = (*Cache)(nil)
// NewCache creates a new cache.
func NewCache(dc *distcache.DistCache, lc fx.Lifecycle, pr *prometheus.Registry) (iface.Cache, error) {
labels := []string{
metrics.CacheTypeLabel,
metrics.ControlPointLabel,
}
cacheLookupHitsTotal := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: metrics.CacheLookupHitsTotalMetricName,
Help: "Cumulative number of cache lookup hits.",
}, labels)
cacheLookupMissesTotal := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: metrics.CacheLookupMissesTotalMetricName,
Help: "Cumulative number of cache lookup misses.",
}, labels)
labels = append(labels, []string{metrics.CacheOperationTypeLabel, metrics.CacheOperationStatusLabel}...)
cacheOperationResultsTotal := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: metrics.CacheOperationResultsTotalMetricName,
Help: "Cumulative number of operation statuses.",
}, labels)
cache := &Cache{
cacheLookupHitsTotal: cacheLookupHitsTotal,
cacheMissesTotal: cacheLookupMissesTotal,
cacheOperationResultsTotal: cacheOperationResultsTotal,
}
lc.Append(fx.Hook{
OnStart: func(_ context.Context) error {
for _, m := range []prometheus.Collector{
cacheLookupHitsTotal,
cacheLookupMissesTotal,
cacheOperationResultsTotal,
} {
err := pr.Register(m)
if err != nil {
if _, ok := err.(prometheus.AlreadyRegisteredError); !ok {
return fmt.Errorf("unable to register cache metrics: %v", err)
}
}
}
dmapCache, err := dc.NewDMap("control_point_cache", olricconfig.DMap{})
if err != nil {
return err
}
cache.dmapCache = dmapCache
return nil
},
})
return cache, nil
}
// get returns the value for the given key.
func (c *Cache) get(ctx context.Context, controlPoint string, cacheType iface.CacheType, key string) ([]byte, error) {
err := c.ready()
if err != nil {
return nil, err
}
if key == "" {
return nil, ErrCacheKeyEmpty
}
cacheKey, err := formatCacheKey(controlPoint, cacheType, key)
if err != nil {
return nil, err
}
getResponse, err := c.dmapCache.Get(ctx, cacheKey)
if err != nil {
return nil, err
}
cachedBytes, err := getResponse.Byte()
if err != nil {
return nil, err
}
return cachedBytes, nil
}
// upsert inserts or updates the value for the given key.
func (c *Cache) upsert(ctx context.Context, controlPoint string, cacheType iface.CacheType, key string, value []byte, ttl time.Duration) error {
err := c.ready()
if err != nil {
return err
}
if key == "" {
return ErrCacheKeyEmpty
}
cacheKey, err := formatCacheKey(controlPoint, cacheType, key)
if err != nil {
return err
}
return c.dmapCache.Put(ctx, cacheKey, value, olric.EX(ttl))
}
// delete deletes the value for the given key.
func (c *Cache) delete(ctx context.Context, controlPoint string, cacheType iface.CacheType, key string) error {
err := c.ready()
if err != nil {
return err
}
if key == "" {
return ErrCacheKeyEmpty
}
cacheKey, err := formatCacheKey(controlPoint, cacheType, key)
if err != nil {
return err
}
_, err = c.dmapCache.Delete(ctx, cacheKey)
return err
}
// ready returns nil if the cache is ready to be used.
func (c *Cache) ready() error {
if c.dmapCache == nil {
return ErrCacheNotReady
}
return nil
}
// Lookup looks up the cache for the given CacheLookupRequest.
func (c *Cache) Lookup(ctx context.Context, request *flowcontrolv1.CacheLookupRequest) *flowcontrolv1.CacheLookupResponse {
response, wgResult, wgGlobal := c.LookupWait(ctx, request)
wgResult.Wait()
wgGlobal.Wait()
c.reportLookupMetrics(request, response)
return response
}
// LookupWait looks up the cache for the given CacheLookupRequest. It does not wait for the response.
func (c *Cache) LookupWait(ctx context.Context, request *flowcontrolv1.CacheLookupRequest) (*flowcontrolv1.CacheLookupResponse, *sync.WaitGroup, *sync.WaitGroup) {
// define wait groups
var wgResult, wgGlobal sync.WaitGroup
response := &flowcontrolv1.CacheLookupResponse{
GlobalCacheResponses: make(map[string]*flowcontrolv1.KeyLookupResponse),
}
if request == nil {
return response, &wgResult, &wgGlobal
}
type Lookup struct {
lookupResponse *flowcontrolv1.KeyLookupResponse
key string
cacheType iface.CacheType
wg *sync.WaitGroup
}
execLookup := func(lookup *Lookup) func() {
return func() {
defer lookup.wg.Done()
lookupResponse := lookup.lookupResponse
cachedBytes, err := c.get(ctx, request.ControlPoint, lookup.cacheType, lookup.key)
if err == nil {
lookupResponse.Value = cachedBytes
lookupResponse.LookupStatus = flowcontrolv1.CacheLookupStatus_HIT
lookupResponse.OperationStatus = flowcontrolv1.CacheOperationStatus_SUCCESS
return
}
lookupResponse.LookupStatus = flowcontrolv1.CacheLookupStatus_MISS
if err.Error() == ErrCacheKeyNotFound.Error() {
lookupResponse.OperationStatus = flowcontrolv1.CacheOperationStatus_SUCCESS
} else {
lookupResponse.OperationStatus = flowcontrolv1.CacheOperationStatus_ERROR
lookupResponse.Error = err.Error()
}
}
}
var lookups []*Lookup
// define a lookup struct to hold the cache key and the cached value
if request.ResultCacheKey != "" {
response.ResultCacheResponse = &flowcontrolv1.KeyLookupResponse{}
lookups = append(lookups, &Lookup{
key: request.ResultCacheKey,
lookupResponse: response.ResultCacheResponse,
cacheType: iface.Result,
wg: &wgResult,
})
}
for _, globalCacheKey := range request.GlobalCacheKeys {
lookupResponse := &flowcontrolv1.KeyLookupResponse{}
response.GlobalCacheResponses[globalCacheKey] = lookupResponse
lookups = append(lookups, &Lookup{
key: globalCacheKey,
lookupResponse: lookupResponse,
cacheType: iface.Global,
wg: &wgGlobal,
})
}
for i, lookup := range lookups {
lookup.wg.Add(1)
if i == len(lookups)-1 {
execLookup(lookup)()
continue
}
panichandler.Go(execLookup(lookup))
}
return response, &wgResult, &wgGlobal
}
// Upsert upserts the cache for the given CacheUpsertRequest.
func (c *Cache) Upsert(ctx context.Context, req *flowcontrolv1.CacheUpsertRequest) *flowcontrolv1.CacheUpsertResponse {
response := &flowcontrolv1.CacheUpsertResponse{
GlobalCacheResponses: make(map[string]*flowcontrolv1.KeyUpsertResponse),
}
if req == nil {
return response
}
type UpsertRequest struct {
entry *flowcontrolv1.CacheEntry
upsertResponse *flowcontrolv1.KeyUpsertResponse
key string
cacheType iface.CacheType
}
wg := sync.WaitGroup{}
execCacheUpsert := func(upsertRequest *UpsertRequest) func() {
return func() {
defer wg.Done()
cacheType := upsertRequest.cacheType
key := upsertRequest.key
value := upsertRequest.entry.Value
ttl := upsertRequest.entry.Ttl.AsDuration()
// Default and Cap TTL to one week
if ttl == 0 || (ttl > time.Hour*24*7) {
ttl = time.Hour * 24 * 7
}
err := c.upsert(ctx, req.ControlPoint, cacheType, key, value, ttl)
if err != nil {
upsertRequest.upsertResponse.OperationStatus = flowcontrolv1.CacheOperationStatus_ERROR
upsertRequest.upsertResponse.Error = err.Error()
} else {
upsertRequest.upsertResponse.OperationStatus = flowcontrolv1.CacheOperationStatus_SUCCESS
}
}
}
var upsertRequests []*UpsertRequest
if req.ResultCacheEntry != nil && req.ResultCacheEntry.Key != "" {
wg.Add(1)
upsertResponse := &flowcontrolv1.KeyUpsertResponse{}
response.ResultCacheResponse = upsertResponse
upsertRequests = append(upsertRequests, &UpsertRequest{
key: req.ResultCacheEntry.Key,
cacheType: iface.Result,
entry: req.ResultCacheEntry,
upsertResponse: upsertResponse,
})
}
// iterate over the state cache entries map
for key, globalCacheEntry := range req.GlobalCacheEntries {
if key == "" {
continue
}
wg.Add(1)
upsertResponse := &flowcontrolv1.KeyUpsertResponse{}
response.GlobalCacheResponses[key] = upsertResponse
// set the state cache entry key
upsertRequests = append(upsertRequests, &UpsertRequest{
key: key,
cacheType: iface.Global,
entry: globalCacheEntry,
upsertResponse: upsertResponse,
})
}
for i, upsertRequest := range upsertRequests {
if i == len(upsertRequests)-1 {
execCacheUpsert(upsertRequest)()
continue
}
go execCacheUpsert(upsertRequest)()
}
wg.Wait()
return response
}
// Delete deletes the cache for the given CacheDeleteRequest.
func (c *Cache) Delete(ctx context.Context, req *flowcontrolv1.CacheDeleteRequest) *flowcontrolv1.CacheDeleteResponse {
response := &flowcontrolv1.CacheDeleteResponse{
GlobalCacheResponses: make(map[string]*flowcontrolv1.KeyDeleteResponse),
}
if req == nil {
return response
}
type DeleteRequest struct {
deleteResponse *flowcontrolv1.KeyDeleteResponse
key string
cacheType iface.CacheType
}
wg := sync.WaitGroup{}
execCacheDelete := func(deleteRequest *DeleteRequest) func() {
return func() {
defer wg.Done()
cacheType := deleteRequest.cacheType
key := deleteRequest.key
err := c.delete(ctx, req.ControlPoint, cacheType, key)
if err != nil {
deleteRequest.deleteResponse.OperationStatus = flowcontrolv1.CacheOperationStatus_ERROR
deleteRequest.deleteResponse.Error = err.Error()
} else {
deleteRequest.deleteResponse.OperationStatus = flowcontrolv1.CacheOperationStatus_SUCCESS
}
}
}
var deleteRequests []*DeleteRequest
if req.ResultCacheKey != "" {
wg.Add(1)
deleteResponse := &flowcontrolv1.KeyDeleteResponse{}
response.ResultCacheResponse = deleteResponse
deleteRequests = append(deleteRequests, &DeleteRequest{
cacheType: iface.Result,
key: req.ResultCacheKey,
deleteResponse: deleteResponse,
})
}
for _, globalCacheKey := range req.GlobalCacheKeys {
if globalCacheKey == "" {
continue
}
wg.Add(1)
deleteResponse := &flowcontrolv1.KeyDeleteResponse{}
response.GlobalCacheResponses[globalCacheKey] = deleteResponse
deleteRequests = append(deleteRequests, &DeleteRequest{
cacheType: iface.Global,
key: globalCacheKey,
deleteResponse: deleteResponse,
})
}
for i, deleteRequest := range deleteRequests {
if i == len(deleteRequests)-1 {
execCacheDelete(deleteRequest)()
continue
}
go execCacheDelete(deleteRequest)()
}
wg.Wait()
c.reportDeleteMetrics(req, response)
return response
}
func (c *Cache) reportLookupMetrics(
request *flowcontrolv1.CacheLookupRequest,
response *flowcontrolv1.CacheLookupResponse,
) {
if response.ResultCacheResponse != nil {
c.reportLookupMetricsForResponse(
metrics.CacheTypeResult,
request.ControlPoint,
response.ResultCacheResponse,
)
c.reportOperationMetricsForResponse(
metrics.CacheOperationTypeLookup,
metrics.CacheTypeResult,
request.ControlPoint,
response.ResultCacheResponse.OperationStatus,
)
}
for _, resp := range response.GlobalCacheResponses {
c.reportLookupMetricsForResponse(
metrics.CacheTypeGlobal,
request.ControlPoint,
resp,
)
c.reportOperationMetricsForResponse(
metrics.CacheOperationTypeLookup,
metrics.CacheTypeGlobal,
request.ControlPoint,
resp.OperationStatus,
)
}
}
func (c *Cache) reportDeleteMetrics(
request *flowcontrolv1.CacheDeleteRequest,
response *flowcontrolv1.CacheDeleteResponse,
) {
if response.ResultCacheResponse != nil {
c.reportOperationMetricsForResponse(
metrics.CacheOperationTypeDelete,
metrics.CacheTypeResult,
request.ControlPoint,
response.ResultCacheResponse.OperationStatus,
)
}
for _, resp := range response.GlobalCacheResponses {
c.reportOperationMetricsForResponse(
metrics.CacheOperationTypeDelete,
metrics.CacheTypeGlobal,
request.ControlPoint,
resp.OperationStatus,
)
}
}
func (c *Cache) reportLookupMetricsForResponse(cacheType, controlPoint string, response *flowcontrolv1.KeyLookupResponse) {
labels := prometheus.Labels(map[string]string{
metrics.CacheTypeLabel: cacheType,
metrics.ControlPointLabel: controlPoint,
})
switch response.LookupStatus {
case flowcontrolv1.CacheLookupStatus_HIT:
hitCounter, err := c.cacheLookupHitsTotal.GetMetricWith(labels)
if err != nil {
log.Debug().Msgf("Could not extract cache hit count counter metric: %v", err)
return
}
hitCounter.Inc()
case flowcontrolv1.CacheLookupStatus_MISS:
missCounter, err := c.cacheMissesTotal.GetMetricWith(labels)
if err != nil {
log.Debug().Msgf("Could not extract cache miss count counter metric: %v", err)
return
}
missCounter.Inc()
}
}
func (c *Cache) reportOperationMetricsForResponse(operationType, cacheType, controlPoint string, operationStatus flowcontrolv1.CacheOperationStatus) {
labels := prometheus.Labels(map[string]string{
metrics.CacheTypeLabel: cacheType,
metrics.ControlPointLabel: controlPoint,
metrics.CacheOperationTypeLabel: operationType,
})
switch operationStatus {
case flowcontrolv1.CacheOperationStatus_SUCCESS:
labels[metrics.CacheOperationStatusLabel] = metrics.CacheOperationStatusSuccess
case flowcontrolv1.CacheOperationStatus_ERROR:
labels[metrics.CacheOperationStatusLabel] = metrics.CacheOperationStatusError
}
statusCounter, err := c.cacheOperationResultsTotal.GetMetricWith(labels)
if err != nil {
log.Debug().Msgf("Could not extract cache operation status metric: %v", err)
return
}
statusCounter.Inc()
}
// formatCacheKey returns the cache key for the given control point and key.
func formatCacheKey(controlPoint string, cacheType iface.CacheType, key string) (string, error) {
if cacheType == iface.Result {
if controlPoint == "" {
return "", ErrCacheControlPointEmpty
}
return "@controlpoint:" + controlPoint + "/type:bytes" + "/key:" + key, nil
} else {
return "@global" + "/type:bytes" + "/key:" + key, nil
}
}