This repository has been archived by the owner on Jul 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lookup_test.go
529 lines (444 loc) · 11.5 KB
/
lookup_test.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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
package ncache
import (
"context"
"errors"
"fmt"
"math/rand"
"reflect"
"runtime"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestLookupCache_GetSet(t *testing.T) {
for _, test := range []struct {
Name string
Opts *LookupOpts
InitialValue interface{}
InitialTTL time.Duration
InitialStalePeriod time.Duration
InitialWait time.Duration
LookupSleep time.Duration
LookupValue interface{}
LookupError string
LookupPanicValue interface{}
ExpectedValue interface{}
ExpectStale bool
ExpectedError string
ExpectLookup bool
}{
// TODO: test error when setting value in lookup (currently not exposed to users)
{
Name: "Fresh",
InitialValue: "hello",
InitialTTL: time.Second,
ExpectedValue: "hello",
},
{
Name: "Stale",
Opts: &LookupOpts{
RefreshMode: RefreshDefault,
},
InitialValue: "hello",
InitialTTL: 1 * time.Microsecond,
InitialStalePeriod: 5 * time.Second,
InitialWait: 1 * time.Millisecond,
ExpectedValue: "hello",
ExpectStale: true,
},
{
Name: "Stale + refresh expired (same as default)",
Opts: &LookupOpts{
RefreshMode: RefreshExpired,
},
InitialValue: "hello",
InitialTTL: 1 * time.Microsecond,
InitialStalePeriod: 5 * time.Second,
InitialWait: 5 * time.Millisecond,
ExpectedValue: "hello",
ExpectStale: true,
},
{
Name: "Stale + refresh",
Opts: &LookupOpts{
RefreshMode: RefreshStaleSync,
},
InitialValue: "hello",
InitialTTL: 1 * time.Microsecond,
InitialStalePeriod: 5 * time.Second,
InitialWait: 5 * time.Millisecond,
LookupValue: "world",
ExpectedValue: "world",
ExpectStale: false,
ExpectLookup: true,
},
{
Name: "Stale + refresh in background",
Opts: &LookupOpts{
RefreshMode: RefreshStale,
},
InitialValue: "hello",
InitialTTL: 1 * time.Microsecond,
InitialStalePeriod: 5 * time.Second,
InitialWait: 5 * time.Millisecond,
LookupValue: "world",
ExpectedValue: "hello",
ExpectStale: true,
ExpectLookup: true,
},
{
Name: "Expired",
InitialValue: "hello",
InitialTTL: 1 * time.Microsecond,
InitialWait: 1 * time.Millisecond,
LookupValue: "world",
ExpectedValue: "world",
ExpectLookup: true,
},
{
Name: "Lookup error",
InitialValue: "hello",
InitialTTL: 1 * time.Microsecond,
InitialWait: 1 * time.Millisecond,
LookupValue: "world",
LookupError: "damn",
ExpectedError: "damn",
ExpectLookup: true,
},
{
Name: "Lookup timeout",
Opts: &LookupOpts{
Timeout: 5 * time.Millisecond,
},
InitialValue: "hello",
InitialTTL: 1 * time.Microsecond,
InitialWait: 1 * time.Millisecond,
LookupValue: "world",
LookupError: "damn",
LookupSleep: 250 * time.Millisecond,
ExpectedError: context.DeadlineExceeded.Error(),
ExpectLookup: true,
},
{
Name: "Caller context canceled",
InitialValue: "hello",
InitialTTL: 1 * time.Microsecond,
InitialWait: 1 * time.Millisecond,
LookupValue: "world",
LookupError: "damn",
LookupSleep: 250 * time.Millisecond,
ExpectedError: context.DeadlineExceeded.Error(),
ExpectLookup: true,
},
{
Name: "Lookup panic",
InitialValue: "hello",
InitialTTL: 1 * time.Microsecond,
InitialWait: 1 * time.Millisecond,
LookupPanicValue: "some panic",
ExpectedError: "some panic",
ExpectLookup: true,
},
{
Name: "Lookup panic with error instance",
InitialValue: "hello",
InitialTTL: 1 * time.Microsecond,
InitialWait: 1 * time.Millisecond,
LookupPanicValue: errors.New("some panic with real error"),
ExpectedError: "some panic with real error",
ExpectLookup: true,
},
} {
test := test
t.Run(test.Name, func(t *testing.T) {
lookupCalled := make(chan struct{}, 1)
lookup := func(ctx context.Context, key string) (val interface{}, err error) {
lookupCalled <- struct{}{}
if key != test.Name {
// this runs on another goroutine so we are not allowed to use t here.
// instead just panic
panic(fmt.Sprintf("expected key=%q, got key=%q", test.Name, key))
}
if test.LookupSleep > 0 {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(test.LookupSleep):
}
}
if test.LookupPanicValue != nil {
panic(test.LookupPanicValue)
}
if test.LookupError != "" {
return nil, errors.New(test.LookupError)
}
return test.LookupValue, nil
}
c := NewLRU(4)
if err := c.Set(context.Background(), test.Name, test.InitialValue, test.InitialTTL, test.InitialStalePeriod); err != nil {
t.Fatalf("failed to set initial value for key %q: %s", test.Name, err)
}
time.Sleep(test.InitialWait)
lc := NewLookupCache(c, nil)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
gotValue, gotStale, gotErr := lc.GetSet(ctx, test.Name, lookup, test.Opts)
if test.ExpectedError == "" {
assertNoError(t, gotErr)
} else {
assertError(t, test.ExpectedError, gotErr)
}
assertStaleState(t, test.ExpectStale, gotStale)
assertValue(t, test.ExpectedValue, gotValue)
var receiveTimeout time.Duration
if test.Opts != nil && test.Opts.RefreshMode == RefreshStale {
// we need to wait when refreshing in background. we also add a few milliseconds to avoid timing issues.
receiveTimeout = test.LookupSleep + time.Second
}
if test.ExpectLookup {
assertReceive(t, lookupCalled, receiveTimeout)
} else {
assertNoReceive(t, lookupCalled, receiveTimeout)
}
})
}
}
func assertError(tb testing.TB, expected string, err error) {
tb.Helper()
if err == nil {
tb.Errorf("expected error %q, got no error", expected)
} else if err.Error() != expected {
tb.Errorf("expected error %q, got error %q", expected, err)
}
}
func assertNoError(tb testing.TB, err error) {
tb.Helper()
if err != nil {
tb.Errorf("expected no error, got error %q", err)
}
}
func assertNoReceive(tb testing.TB, c <-chan struct{}, timeout time.Duration) {
tb.Helper()
if timeout > 0 {
select {
case <-c:
tb.Error("unexpected value received on channel")
case <-time.After(timeout):
}
} else {
select {
case <-c:
tb.Error("unexpected value received on channel")
default:
}
}
}
func assertReceive(tb testing.TB, c <-chan struct{}, timeout time.Duration) {
tb.Helper()
if timeout > 0 {
select {
case <-c:
case <-time.After(timeout):
tb.Errorf("expected to receive value on channel but got nothing after %s", timeout)
}
} else {
select {
case <-c:
default:
tb.Error("expected to receive value on channel but got nothing")
}
}
}
func assertStaleState(tb testing.TB, expected, got bool) {
tb.Helper()
if expected && !got {
tb.Error("expected value to be stale, got non-stale value")
} else if !expected && got {
tb.Error("expected value to be non-stale, got stale value")
}
}
func assertValue(tb testing.TB, expected, got interface{}) {
tb.Helper()
switch {
case expected == nil && got != nil:
tb.Errorf("expected no value, got value %v", got)
case expected != nil && got == nil:
tb.Errorf("expected value %v, got no value", expected)
case !reflect.DeepEqual(expected, got):
tb.Errorf("expected value %v, got value %v", expected, got)
}
}
func TestLookupCache_GetSet_Dedupe(t *testing.T) {
lc := NewLookupCache(NewLRU(4), &LookupOpts{TTL: time.Second})
var lookupCalled uint64
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_, _, _ = lc.GetSet(context.Background(), "hello", func(context.Context, string) (interface{}, error) {
atomic.AddUint64(&lookupCalled, 1)
time.Sleep(75 * time.Microsecond)
return "world", nil
}, nil)
}()
}
wg.Wait()
if calls := atomic.LoadUint64(&lookupCalled); calls != 1 {
t.Errorf("expected exactly 1 lookup, got %d", calls)
}
}
func TestLookupCache_GetSet_Expired(t *testing.T) {
lc := NewLookupCache(NewLRU(4), &LookupOpts{TTL: time.Millisecond})
var lookupCalled uint64
var lookupErr error
lookup := func(context.Context, string) (interface{}, error) {
lookupCalled++
return "world" + strconv.FormatUint(lookupCalled, 10), lookupErr
}
val, stale, err := lc.GetSet(context.Background(), "hello", lookup, nil)
assertValue(t, "world1", val)
assertStaleState(t, false, stale)
assertNoError(t, err)
time.Sleep(time.Millisecond)
val, stale, err = lc.GetSet(context.Background(), "hello", lookup, nil)
assertValue(t, "world2", val)
assertStaleState(t, false, stale)
assertNoError(t, err)
time.Sleep(time.Millisecond)
lookupErr = errors.New("some error")
val, stale, err = lc.GetSet(context.Background(), "hello", lookup, nil)
assertValue(t, nil, val)
assertStaleState(t, false, stale)
assertError(t, lookupErr.Error(), err)
lookupErr = nil
val, stale, err = lc.GetSet(context.Background(), "hello", lookup, nil)
assertValue(t, "world4", val)
assertStaleState(t, false, stale)
assertNoError(t, err)
}
func BenchmarkLookupCache_GetSet(b *testing.B) {
b.Run("Dedup", func(b *testing.B) {
size := runtime.GOMAXPROCS(0)
if size > 1 {
size = size / 2
}
c := NewLRU(size)
lc := NewLookupCache(c, &LookupOpts{
TTL: 1 * time.Microsecond,
})
key := "key"
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_, _, _ = lc.GetSet(context.Background(), key, func(context.Context, string) (interface{}, error) {
return key, nil
}, nil)
}
})
})
b.Run("Existing", func(b *testing.B) {
size := runtime.GOMAXPROCS(0)
if size > 1 {
size = size / 2
}
c := NewLRU(size)
lc := NewLookupCache(c, nil)
b.RunParallel(func(pb *testing.PB) {
key := "key#" + strconv.Itoa(rand.Int())
if err := c.Set(context.Background(), key, key, 0, 0); err != nil {
b.Fatalf("failed to set key %q: %s", key, err)
}
for pb.Next() {
_, _, _ = lc.GetSet(context.Background(), key, func(context.Context, string) (interface{}, error) {
panic("should never be called")
}, nil)
}
})
})
}
func TestLookupOpts_Merge(t *testing.T) {
for _, test := range []struct {
Name string
A, B LookupOpts
E LookupOpts
}{
{
Name: "Both Empty",
A: LookupOpts{},
B: LookupOpts{},
E: LookupOpts{},
},
{
Name: "A empty",
A: LookupOpts{},
B: LookupOpts{
RefreshMode: RefreshStale,
StaleFor: 1,
Timeout: 2,
TTL: 3,
},
E: LookupOpts{
RefreshMode: RefreshStale,
StaleFor: 1,
Timeout: 2,
TTL: 3,
},
},
{
Name: "B empty",
A: LookupOpts{
RefreshMode: RefreshStaleSync,
StaleFor: 1,
Timeout: 2,
TTL: 3,
},
B: LookupOpts{},
E: LookupOpts{
RefreshMode: RefreshStaleSync,
StaleFor: 1,
Timeout: 2,
TTL: 3,
},
},
{
Name: "Partial override",
A: LookupOpts{
StaleFor: 10,
TTL: 3,
},
B: LookupOpts{
RefreshMode: RefreshExpired,
StaleFor: 1,
Timeout: 2,
},
E: LookupOpts{
RefreshMode: RefreshExpired,
StaleFor: 1,
Timeout: 2,
TTL: 3,
},
},
{
Name: "Ignore default refresh in B",
A: LookupOpts{
RefreshMode: RefreshExpired,
},
B: LookupOpts{
RefreshMode: RefreshDefault,
},
E: LookupOpts{
RefreshMode: RefreshExpired,
},
},
} {
test := test
t.Run(test.Name, func(t *testing.T) {
g := test.A.merge(test.B)
if !reflect.DeepEqual(g, test.E) {
t.Errorf("result mismatch\n\texpected: %#v\n\t got: %#v", test.E, g)
}
})
}
}