-
Notifications
You must be signed in to change notification settings - Fork 22
/
cachegeneric.go
254 lines (219 loc) · 6.43 KB
/
cachegeneric.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
package cache
import (
"bytes"
"context"
"fmt"
"sort"
"golang.org/x/exp/constraints"
"github.com/mgtv-tech/jetcache-go/logger"
"github.com/mgtv-tech/jetcache-go/util"
)
// T wrap Cache to support golang's generics
type T[K constraints.Ordered, V any] struct {
Cache
}
// NewT new a T
func NewT[K constraints.Ordered, V any](cache Cache) *T[K, V] {
return &T[K, V]{cache}
}
// Set sets the value `v` associated with the given `key` and `id` in the cache.
// The expiration time of the cached value is determined by the cache configuration.
func (w *T[K, V]) Set(ctx context.Context, key string, id K, v V) error {
combKey := fmt.Sprintf("%s:%v", key, id)
return w.Cache.Set(ctx, combKey, Value(v))
}
// Get retrieves the value associated with the given `key` and `id`.
//
// It first attempts to fetch the value from the cache. If a cache miss occurs, it calls the provided
// `fn` function to fetch the value and stores it in the cache with an expiration time
// determined by the cache configuration.
//
// A `Once` mechanism is employed to ensure only one fetch is performed for a given `key` and `id`
// combination, even under concurrent access.
func (w *T[K, V]) Get(ctx context.Context, key string, id K, fn func(context.Context, K) (V, error)) (V, error) {
var varT V
combKey := fmt.Sprintf("%s:%v", key, id)
err := w.Once(ctx, combKey, Value(&varT), Do(func(ctx context.Context) (any, error) {
return fn(ctx, id)
}))
return varT, err
}
// MGet efficiently retrieves multiple values associated with the given `key` and `ids`.
//
// It attempts to fetch all values from the cache. For missing values, it calls the provided
// `fn` function to fetch the remaining values and updates the cache with an expiration time
// determined by the cache configuration.
//
// The results are returned as a map where the key is the `id` and the value is the corresponding data.
func (w *T[K, V]) MGet(ctx context.Context, key string, ids []K, fn func(context.Context, []K) (map[K]V, error)) (result map[K]V) {
c := w.Cache.(*jetCache)
miss := make(map[string]K, len(ids))
for _, missId := range ids {
missKey := fmt.Sprintf("%s:%v", key, missId)
miss[missKey] = missId
}
if c.local != nil {
result = w.mGetLocal(miss, true)
if len(miss) == 0 {
return
}
}
if c.remote == nil && fn == nil {
return
}
missIds := make([]K, 0, len(miss))
for _, missId := range miss {
missIds = append(missIds, missId)
}
sort.Slice(missIds, func(i, j int) bool {
return missIds[i] < missIds[j]
})
combKey := fmt.Sprintf("%s:%v", key, missIds)
v, err, _ := c.group.Do(combKey, func() (interface{}, error) {
var ret map[K]V
if c.local != nil {
ret = w.mGetLocal(miss, false)
if len(miss) == 0 {
return ret, nil
}
}
if c.remote != nil {
ret = util.MergeMap(ret, w.mGetRemote(ctx, miss))
if len(miss) == 0 {
return ret, nil
}
}
if fn != nil {
ret = util.MergeMap(ret, w.mQueryAndSetCache(ctx, miss, fn))
}
return ret, nil
})
if err != nil {
return result
}
return util.MergeMap(result, v.(map[K]V))
}
func (w *T[K, V]) mGetLocal(miss map[string]K, skipMissStats bool) map[K]V {
c := w.Cache.(*jetCache)
result := make(map[K]V, len(miss))
for missKey, missId := range miss {
if b, ok := c.local.Get(missKey); ok {
delete(miss, missKey)
c.statsHandler.IncrHit()
c.statsHandler.IncrLocalHit()
if bytes.Compare(b, notFoundPlaceholder) == 0 {
continue
}
var varT V
if err := c.Unmarshal(b, &varT); err != nil {
logger.Warn("mGetLocal#c.Unmarshal(%s) error(%v)", missKey, err)
} else {
result[missId] = varT
}
} else if !skipMissStats {
c.statsHandler.IncrLocalMiss()
if c.remote == nil {
c.statsHandler.IncrMiss()
}
}
}
return result
}
func (w *T[K, V]) mGetRemote(ctx context.Context, miss map[string]K) map[K]V {
c := w.Cache.(*jetCache)
missKeys := make([]string, 0, len(miss))
for missKey := range miss {
missKeys = append(missKeys, missKey)
}
cacheValues, err := c.remote.MGet(ctx, missKeys...)
if err != nil {
logger.Warn("mGetRemote#c.Remote.MGet error(%v)", err)
return nil
}
result := make(map[K]V, len(cacheValues))
for missKey, missId := range miss {
if val, ok := cacheValues[missKey]; ok {
delete(miss, missKey)
c.statsHandler.IncrHit()
c.statsHandler.IncrRemoteHit()
b := util.Bytes(val.(string))
if bytes.Compare(b, notFoundPlaceholder) == 0 {
continue
}
var varT V
if err = c.Unmarshal(b, &varT); err != nil {
logger.Warn("mGetRemote#c.Unmarshal(%s) error(%v)", missKey, err)
} else {
result[missId] = varT
if c.local != nil {
c.local.Set(missKey, b)
}
}
} else {
c.statsHandler.IncrMiss()
c.statsHandler.IncrRemoteMiss()
}
}
return result
}
func (w *T[K, V]) mQueryAndSetCache(ctx context.Context, miss map[string]K, fn func(context.Context, []K) (map[K]V, error)) map[K]V {
c := w.Cache.(*jetCache)
missIds := make([]K, 0, len(miss))
for _, missId := range miss {
missIds = append(missIds, missId)
}
c.statsHandler.IncrQuery()
fnValues, err := fn(ctx, missIds)
if err != nil {
c.statsHandler.IncrQueryFail(err)
return nil
}
result := make(map[K]V, len(fnValues))
cacheValues := make(map[string]any, len(miss))
placeholderValues := make(map[string]any, len(miss))
for missKey, missId := range miss {
if val, ok := fnValues[missId]; ok {
result[missId] = val
if b, err := c.Marshal(val); err != nil {
placeholderValues[missKey] = notFoundPlaceholder
logger.Warn("mQueryAndSetCache#c.Marshal error(%v)", err)
} else {
cacheValues[missKey] = b
}
} else {
placeholderValues[missKey] = notFoundPlaceholder
}
}
if c.local != nil {
if len(cacheValues) > 0 {
for key, value := range cacheValues {
c.local.Set(key, value.([]byte))
}
}
if len(placeholderValues) > 0 {
for key, value := range placeholderValues {
c.local.Set(key, value.([]byte))
}
}
}
if c.remote != nil {
if len(cacheValues) > 0 {
if err = c.remote.MSet(ctx, cacheValues, c.remoteExpiry); err != nil {
logger.Warn("mQueryAndSetCache#remote.MSet error(%v)", err)
}
}
if len(placeholderValues) > 0 {
if err = c.remote.MSet(ctx, placeholderValues, c.notFoundExpiry); err != nil {
logger.Warn("mQueryAndSetCache#remote.MSet error(%v)", err)
}
}
if c.isSyncLocal() {
cacheKeys := make([]string, 0, len(miss))
for missKey := range miss {
cacheKeys = append(cacheKeys, missKey)
}
c.send(EventTypeSetByMGet, cacheKeys...)
}
}
return result
}