-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathcachegeneric.go
281 lines (240 loc) · 7.68 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
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
package cache
import (
"bytes"
"context"
"errors"
"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 {
c := w.Cache.(*jetCache)
combKey := fmt.Sprintf("%s%s%v", key, c.separator, 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) {
c := w.Cache.(*jetCache)
var varT V
combKey := fmt.Sprintf("%s%s%v", key, c.separator, 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 is a wrapper around MGetWithErr that logs any errors and returns only the results.
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) {
var err error
if result, err = w.MGetWithErr(ctx, key, ids, fn); err != nil {
logger.Warn("MGet error(%v)", err)
}
return
}
// MGetWithErr efficiently retrieves multiple values associated with the given `key` and `ids`,
// returning both the results and any errors encountered during the process.
//
// It first attempts to retrieve values from the local cache (if enabled), then from the remote cache (if enabled).
// For any values not found in the caches, it calls the provided `fn` function to fetch them from the
// underlying data source. The fetched values are then stored in both the local and remote caches for
// future use.
//
// The results are returned as a map where the key is the `id` and the value is the corresponding data.
// Any errors encountered during the cache retrieval or data fetching process are returned as a non-nil error.
func (w *T[K, V]) MGetWithErr(ctx context.Context, key string, ids []K, fn func(context.Context, []K) (map[K]V, error)) (result map[K]V, errs error) {
c := w.Cache.(*jetCache)
miss := make(map[string]K, len(ids))
for _, missId := range ids {
missKey := fmt.Sprintf("%s%s%v", key, c.separator, missId)
miss[missKey] = missId
}
if c.local != nil {
result, errs = 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%s%v", key, c.separator, missIds)
v, err, _ := c.group.Do(combKey, func() (interface{}, error) {
var ret map[K]V
process := func(r map[K]V, e error) {
errs = errors.Join(errs, e)
ret = util.MergeMap(ret, r)
}
if c.local != nil {
process(w.mGetLocal(miss, false))
if len(miss) == 0 {
return ret, nil
}
}
if c.remote != nil {
process(w.mGetRemote(ctx, miss))
if len(miss) == 0 {
return ret, nil
}
}
if fn != nil {
process(w.mQueryAndSetCache(ctx, miss, fn))
}
return ret, nil
})
if err != nil {
errs = errors.Join(errs, err)
return
}
return util.MergeMap(result, v.(map[K]V)), errs
}
func (w *T[K, V]) mGetLocal(miss map[string]K, skipMissStats bool) (result map[K]V, errs error) {
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 {
errs = errors.Join(errs, fmt.Errorf("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
}
func (w *T[K, V]) mGetRemote(ctx context.Context, miss map[string]K) (result map[K]V, errs error) {
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 {
errs = errors.Join(errs, fmt.Errorf("mGetRemote#c.Remote.MGet error(%v)", err))
return
}
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 {
errs = errors.Join(errs, fmt.Errorf("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
}
func (w *T[K, V]) mQueryAndSetCache(ctx context.Context, miss map[string]K, fn func(context.Context, []K) (map[K]V, error)) (result map[K]V, errs error) {
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 {
errs = errors.Join(errs, fmt.Errorf("mQueryAndSetCache#fn(%v) error(%v)", missIds, err))
c.statsHandler.IncrQueryFail(err)
return
}
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
errs = errors.Join(errs, fmt.Errorf("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 {
errs = errors.Join(errs, fmt.Errorf("mQueryAndSetCache#c.Remote.MSet error(%v)", err))
}
}
if len(placeholderValues) > 0 {
if err = c.remote.MSet(ctx, placeholderValues, c.notFoundExpiry); err != nil {
errs = errors.Join(errs, fmt.Errorf("mQueryAndSetCache#c.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
}