-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnamespace.go
379 lines (296 loc) · 8.54 KB
/
namespace.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
package cache
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/steamsets/go-cache/pkg/telemetry"
"github.com/steamsets/go-cache/pkg/types"
)
type Namespace[T any] struct {
fresh time.Duration
stale time.Duration
telemetry bool
ns types.TNamespace
store tieredCache[T]
revalidating *sync.Map
}
type NamespaceConfig struct {
Stores []Store
Telemetry bool
Fresh time.Duration
Stale time.Duration
}
func NewNamespace[T any](ns types.TNamespace, ctx context.Context, cfg NamespaceConfig) Namespace[T] {
return Namespace[T]{
ns: ns,
fresh: cfg.Fresh,
stale: cfg.Stale,
store: newTieredCache[T](ns, cfg.Stores, cfg.Fresh, cfg.Stale, cfg.Telemetry),
revalidating: &sync.Map{},
}
}
func (n Namespace[T]) Get(ctx context.Context, key string) (value *T, found bool, err error) {
ctx, span := telemetry.NewSpan(ctx, "namespace.get")
defer span.End()
telemetry.WithAttributes(span,
telemetry.AttributeKV{Key: "key", Value: key},
telemetry.AttributeKV{Key: "namespace", Value: string(n.ns)},
)
val, found, err := n.store.Get(ctx, n.ns, key)
if err != nil {
return nil, false, err
}
if val == nil || val.Value == nil {
return nil, false, nil
}
v := getT[T](val.Value)
if time.Now().After(val.StaleUntil) {
n.store.Remove(ctx, n.ns, []string{key})
return nil, false, nil
}
return v, found, nil
}
func (n Namespace[T]) Set(ctx context.Context, key string, value T, opts *types.SetOptions) error {
ctx, span := telemetry.NewSpan(ctx, "namespace.set")
defer span.End()
telemetry.WithAttributes(span,
telemetry.AttributeKV{Key: "key", Value: key},
telemetry.AttributeKV{Key: "namespace", Value: string(n.ns)},
)
if key == "" {
return errors.New("key is empty")
}
return n.store.Set(ctx, n.ns, key, &value, opts)
}
type GetMany[T any] struct {
Key string
Value *T
Found bool
}
func (n Namespace[T]) GetMany(ctx context.Context, keys []string) ([]GetMany[T], error) {
ctx, span := telemetry.NewSpan(ctx, "namespace.get-many")
defer span.End()
telemetry.WithAttributes(span,
telemetry.AttributeKV{Key: "keys", Value: keys},
telemetry.AttributeKV{Key: "namespace", Value: string(n.ns)},
)
if len(keys) == 0 {
return nil, errors.New("no keys provided")
}
values, err := n.store.GetMany(ctx, n.ns, keys)
if err != nil {
return nil, err
}
ret := make([]GetMany[T], 0)
toRemove := make([]string, 0)
for _, val := range values {
if val.Value == nil {
ret = append(ret, GetMany[T]{
Key: val.Key,
Value: nil,
Found: val.Found,
})
continue
}
if time.Now().After(val.StaleUntil) {
toRemove = append(toRemove, val.Key)
}
v := getT[T](val.Value)
ret = append(ret, GetMany[T]{
Key: val.Key,
Value: v,
Found: val.Found,
})
}
if len(toRemove) > 0 {
if err := n.store.Remove(ctx, n.ns, toRemove); err != nil {
return nil, err
}
}
return ret, nil
}
type SetMany[T any] struct {
Value T
Key string
Opts *types.SetOptions
}
func (n Namespace[T]) SetMany(ctx context.Context, values []SetMany[*T], opts *types.SetOptions) error {
ctx, span := telemetry.NewSpan(ctx, "namespace.set-many")
defer span.End()
if len(values) == 0 {
return errors.New("no values provided")
}
return n.store.SetMany(ctx, n.ns, values, opts)
}
func (n Namespace[T]) Remove(ctx context.Context, keys []string) error {
ctx, span := telemetry.NewSpan(ctx, "namespace.remove")
defer span.End()
if len(keys) == 0 {
return nil
}
return n.store.Remove(ctx, n.ns, keys)
}
func (n Namespace[T]) Swr(ctx context.Context, key string, refreshFromOrigin func(string) (*T, error)) (*T, error) {
ctx, span := telemetry.NewSpan(ctx, "namespace.swr")
defer span.End()
if key == "" {
return nil, errors.New("key is empty")
}
value, found, err := n.store.Get(ctx, n.ns, key)
if err != nil {
return nil, err
}
now := time.Now()
if found {
if now.After(value.FreshUntil) {
newValue, error := n.deduplicateLoadFromOrigin(ctx, n.ns, key, refreshFromOrigin)
if error != nil {
return nil, error
}
if err := n.store.Set(ctx, n.ns, key, newValue, nil); err != nil {
return nil, err
}
}
v := getT[T](value.Value)
return v, nil
}
newValue, error := n.deduplicateLoadFromOrigin(ctx, n.ns, key, refreshFromOrigin)
if error != nil {
return nil, error
}
if err := n.store.Set(ctx, n.ns, key, newValue, nil); err != nil {
return nil, err
}
return newValue, nil
}
func getT[T any](val interface{}) *T {
if v1, ok := val.(T); ok {
return &v1
}
if v2, ok := val.(*T); ok {
return v2
}
return nil
}
func (n Namespace[T]) SwrMany(ctx context.Context, keys []string, refreshFromOrigin func([]string) ([]GetMany[T], error)) ([]GetMany[T], error) {
ctx, span := telemetry.NewSpan(ctx, "namespace.swr-many")
defer span.End()
if len(keys) == 0 {
return nil, errors.New("no keys provided")
}
values, err := n.store.GetMany(ctx, n.ns, keys)
if err != nil {
return nil, err
}
returnMap := make(map[string]GetMany[T])
keysToFetchFromOrigin := make([]string, 0)
for _, val := range values {
if !val.Found {
keysToFetchFromOrigin = append(keysToFetchFromOrigin, val.Key)
continue
}
if time.Now().After(val.StaleUntil) {
keysToFetchFromOrigin = append(keysToFetchFromOrigin, val.Key)
// We want to get the new value from the origin but will remove
// the result from the origin and just keep this value in the response
}
v := getT[T](val.Value)
returnMap[val.Key] = GetMany[T]{
Key: val.Key,
Value: v,
Found: val.Found,
}
}
// if we have keys to get, we need to get them
if len(keysToFetchFromOrigin) > 0 {
values, err := n.deduplicateLoadFromOriginMany(ctx, n.ns, keysToFetchFromOrigin, refreshFromOrigin)
if err != nil {
return nil, err
}
for _, v := range values {
if _, ok := returnMap[v.Key]; !ok {
returnMap[v.Key] = v
}
}
valuesToSet := make([]SetMany[*T], 0)
for _, v := range returnMap {
valuesToSet = append(valuesToSet, SetMany[*T]{
Value: v.Value,
Key: v.Key,
Opts: nil,
})
}
if err := n.store.SetMany(ctx, n.ns, valuesToSet, nil); err != nil {
return nil, err
}
}
for _, key := range keys {
if _, ok := returnMap[key]; !ok {
returnMap[key] = GetMany[T]{
Key: key,
Value: nil,
Found: false,
}
}
}
returnValues := make([]GetMany[T], 0)
for _, v := range returnMap {
returnValues = append(returnValues, v)
}
return returnValues, nil
}
type deduplicateEntry[T any] struct {
value *T
err error
}
type deduplicateManyEntry[T any] struct {
value []GetMany[T]
err error
}
func (n Namespace[T]) deduplicateLoadFromOrigin(ctx context.Context, ns types.TNamespace, key string, refreshFromOrigin func(string) (*T, error)) (*T, error) {
ctx, span := telemetry.NewSpan(ctx, "namespace.deduplicate-load-from-origin")
defer span.End()
revalidateKey := fmt.Sprintf("%s::%s", ns, key)
// if we are currently revalidating this key, wait for the result (hopefully)
if val, ok := n.revalidating.Load(revalidateKey); ok {
future := val.(chan deduplicateEntry[T])
result := <-future
return result.value, result.err
}
future := make(chan deduplicateEntry[T], 1)
n.revalidating.Store(revalidateKey, future)
defer n.revalidating.Delete(revalidateKey)
_, span2 := telemetry.NewSpan(ctx, "namespace.refreshFromOrigin")
value, err := refreshFromOrigin(key)
span2.End()
// Send the result through the channel
future <- deduplicateEntry[T]{value, err}
return value, err
}
func (n Namespace[T]) deduplicateLoadFromOriginMany(ctx context.Context, ns types.TNamespace, keys []string, refreshFromOrigin func([]string) ([]GetMany[T], error)) ([]GetMany[T], error) {
ctx, span := telemetry.NewSpan(ctx, "namespace.deduplicate-load-from-origin-many")
defer span.End()
revalidateKey := fmt.Sprintf("%s::%s", ns, strings.Join(keys, ","))
// if we are currently revalidating this key, wait for the result (hopefully)
if val, ok := n.revalidating.Load(revalidateKey); ok {
future := val.(chan deduplicateManyEntry[T])
result := <-future
return result.value, result.err
}
future := make(chan deduplicateManyEntry[T], 1)
n.revalidating.Store(revalidateKey, future)
defer n.revalidating.Delete(revalidateKey)
_, span2 := telemetry.NewSpan(ctx, "namespace.refreshFromOrigin")
telemetry.WithAttributes(span2,
telemetry.AttributeKV{Key: "keys", Value: keys},
telemetry.AttributeKV{Key: "namespace", Value: string(n.ns)},
)
values, err := refreshFromOrigin(keys)
span2.End()
// Send the result through the channel
future <- deduplicateManyEntry[T]{values, err}
return values, err
}