-
Notifications
You must be signed in to change notification settings - Fork 5
/
cachegeneric.go
224 lines (192 loc) · 5.21 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
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}
}
// MGet efficiently fetches multiple values associated with a specific key prefix and a list of IDs in a single call.
// It prioritizes retrieving data from the cache and falls back to a user-provided function (`fn`) if values are missing.
// Asynchronous refresh is not supported.
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 := util.JoinAny(":", 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]
})
v, err, _ := c.group.Do(fmt.Sprintf("%s:%v", key, missIds), 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
}