-
Notifications
You must be signed in to change notification settings - Fork 165
Expand file tree
/
Copy pathredislock_test.go
More file actions
767 lines (644 loc) · 19.5 KB
/
Copy pathredislock_test.go
File metadata and controls
767 lines (644 loc) · 19.5 KB
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
package redislock_test
import (
"context"
"errors"
"fmt"
"math/rand"
"sync"
"sync/atomic"
"testing"
"time"
. "github.com/bsm/redislock"
"github.com/redis/go-redis/v9"
)
func TestClient(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
// obtain
client := New(rc)
lock, err := client.Obtain(t.Context(), lockKey, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
if exp, got := 22, len(lock.Token()); exp != got {
t.Fatalf("expected %v, got %v", exp, got)
}
// check TTL
assertTTL(t, lock, time.Hour)
// try to obtain again
_, err = client.Obtain(t.Context(), lockKey, time.Hour, nil)
if exp, got := ErrNotObtained, err; !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
// manually unlock
if err := lock.Release(t.Context()); err != nil {
t.Fatal(err)
}
// lock again
lock, err = client.Obtain(t.Context(), lockKey, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
}
func TestObtain(t *testing.T) {
lock := quickObtain(t, time.Hour)
if err := lock.Release(t.Context()); err != nil {
t.Fatal(err)
}
}
func TestObtain_metadata(t *testing.T) {
rc := redisConnect(t)
meta := "my-data"
lock, err := Obtain(t.Context(), rc, rc.lockKey(), time.Hour, &Options{Metadata: meta})
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
if exp, got := meta, lock.Metadata(); exp != got {
t.Fatalf("expected %v, got %v", exp, got)
}
}
func TestObtain_custom_token(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
// obtain lock
lock1, err := Obtain(t.Context(), rc, lockKey, time.Hour, &Options{Token: "foo", Metadata: "bar"})
if err != nil {
t.Fatal(err)
}
defer lock1.Release(t.Context())
if exp, got := "foo", lock1.Token(); exp != got {
t.Errorf("expected %v, got %v", exp, got)
}
if exp, got := "bar", lock1.Metadata(); exp != got {
t.Errorf("expected %v, got %v", exp, got)
}
// try to obtain again
_, err = Obtain(t.Context(), rc, lockKey, time.Hour, nil)
if exp, got := ErrNotObtained, err; !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
// allow to re-obtain lock if token is known
lock2, err := Obtain(t.Context(), rc, lockKey, time.Hour, &Options{Token: "foo", Metadata: "baz"})
if err != nil {
t.Fatal(err)
}
defer lock2.Release(t.Context())
if exp, got := "foo", lock2.Token(); exp != got {
t.Errorf("expected %v, got %v", exp, got)
}
if exp, got := "baz", lock2.Metadata(); exp != got {
t.Errorf("expected %v, got %v", exp, got)
}
}
func TestObtain_fence(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
fenceKey := lockKey + ":fence"
rc.keys = append(rc.keys, fenceKey)
// no token without a FenceKey
plain := quickObtain(t, time.Hour)
defer plain.Release(t.Context())
if got := plain.FenceToken(); got != 0 {
t.Fatalf("expected no fence token without Options.FenceKey, got %v", got)
}
if err := plain.Release(t.Context()); err != nil {
t.Fatal(err)
}
// first fenced obtain
lock1, err := Obtain(t.Context(), rc, lockKey, time.Hour, &Options{FenceKey: fenceKey})
if err != nil {
t.Fatal(err)
}
tok1 := lock1.FenceToken()
if exp, got := int64(1), tok1; exp != got {
t.Fatalf("expected first fence token %v, got %v", exp, got)
}
if err := lock1.Release(t.Context()); err != nil {
t.Fatal(err)
}
// next obtain must mint a greater token
lock2, err := Obtain(t.Context(), rc, lockKey, time.Hour, &Options{FenceKey: fenceKey})
if err != nil {
t.Fatal(err)
}
defer lock2.Release(t.Context())
if tok2 := lock2.FenceToken(); tok2 <= tok1 {
t.Fatalf("expected fence token > %v, got %v", tok1, tok2)
}
}
func TestObtain_fence_reentrant(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
fenceKey := lockKey + ":fence"
rc.keys = append(rc.keys, fenceKey)
// obtain with a known token
lock1, err := Obtain(t.Context(), rc, lockKey, time.Hour, &Options{Token: "foo", FenceKey: fenceKey})
if err != nil {
t.Fatal(err)
}
defer lock1.Release(t.Context())
tok1 := lock1.FenceToken()
// re-obtain (override) must not advance the token
lock2, err := Obtain(t.Context(), rc, lockKey, time.Hour, &Options{Token: "foo", FenceKey: fenceKey})
if err != nil {
t.Fatal(err)
}
defer lock2.Release(t.Context())
if exp, got := tok1, lock2.FenceToken(); exp != got {
t.Fatalf("re-entrant override must not mint a new token: expected %v, got %v", exp, got)
}
}
func TestObtain_retry_success(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
// obtain for 20ms
lock1 := quickObtain(t, 20*time.Millisecond)
defer lock1.Release(t.Context())
// lock again with linar retry - 3x for 20ms
lock2, err := Obtain(t.Context(), rc, lockKey, time.Hour, &Options{
RetryStrategy: LimitRetry(LinearBackoff(20*time.Millisecond), 3),
})
if err != nil {
t.Fatal(err)
}
defer lock2.Release(t.Context())
}
func TestObtain_retry_failure(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
// obtain for 50ms
lock1, err := Obtain(t.Context(), rc, lockKey, 50*time.Millisecond, nil)
if err != nil {
t.Fatal(err)
}
defer lock1.Release(t.Context())
// lock again with linar retry - 2x for 5ms
_, err = Obtain(t.Context(), rc, lockKey, time.Hour, &Options{
RetryStrategy: LimitRetry(LinearBackoff(5*time.Millisecond), 2),
})
if exp, got := ErrNotObtained, err; !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
}
func TestObtain_retry_context_deadline(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
lock1, err := Obtain(t.Context(), rc, lockKey, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock1.Release(t.Context())
ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
defer cancel()
_, err = Obtain(ctx, rc, lockKey, time.Hour, &Options{
RetryStrategy: LinearBackoff(5 * time.Millisecond),
})
if !errors.Is(err, ErrNotObtained) {
t.Fatalf("expected error to wrap ErrNotObtained, got %v", err)
}
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("expected error to wrap context.DeadlineExceeded, got %v", err)
}
}
func TestObtain_concurrent(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
numLocks := int32(0)
numThreads := 100
wg := new(sync.WaitGroup)
errs := make(chan error, numThreads)
for range numThreads {
wg.Go(func() {
wait := rand.Int63n(int64(10 * time.Millisecond))
time.Sleep(time.Duration(wait))
_, err := Obtain(t.Context(), rc, lockKey, time.Minute, nil)
if err == ErrNotObtained {
return
} else if err != nil {
errs <- err
} else {
atomic.AddInt32(&numLocks, 1)
}
})
}
wg.Wait()
close(errs)
for err := range errs {
t.Fatal(err)
}
if exp, got := 1, int(numLocks); exp != got {
t.Fatalf("expected %v, got %v", exp, got)
}
}
func TestLock_Refresh(t *testing.T) {
t.Run("success", func(t *testing.T) {
lock := quickObtain(t, time.Hour)
defer lock.Release(t.Context())
// check TTL
assertTTL(t, lock, time.Hour)
// update TTL
if err := lock.Refresh(t.Context(), time.Minute, nil); err != nil {
t.Fatal(err)
}
// check TTL again
assertTTL(t, lock, time.Minute)
})
t.Run("retry success", func(t *testing.T) {
lock := quickObtain(t, time.Hour)
defer lock.Release(t.Context())
// refresh with linear retry - 3x for 20ms
if err := lock.Refresh(t.Context(), time.Minute, &Options{
RetryStrategy: LimitRetry(LinearBackoff(20*time.Millisecond), 3),
}); err != nil {
t.Fatal(err)
}
assertTTL(t, lock, time.Minute)
})
t.Run("retry failure on lost lock returns immediately", func(t *testing.T) {
lock := quickObtain(t, 5*time.Millisecond)
defer lock.Release(t.Context())
// let the lock expire
time.Sleep(10 * time.Millisecond)
// refresh with linear retry - 2x for 100ms; should still return quickly
// because a lost lock is a terminal failure rather than a retryable one.
backoff := 100 * time.Millisecond
start := time.Now()
err := lock.Refresh(t.Context(), time.Hour, &Options{
RetryStrategy: LimitRetry(LinearBackoff(backoff), 2),
})
if exp, got := ErrNotObtained, err; !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
if elapsed := time.Since(start); elapsed >= backoff {
t.Fatalf("expected Refresh on a lost lock to return without retrying, took %v", elapsed)
}
})
t.Run("retry recovers from transient error", func(t *testing.T) {
rc := redisConnect(t)
flaky := &flakyScripter{Client: rc.Client}
client := New(flaky)
lock, err := client.Obtain(t.Context(), rc.lockKey(), time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
// fail the next 2 refresh attempts; the 3rd should succeed.
flaky.fails.Store(2)
if err := lock.Refresh(t.Context(), time.Minute, &Options{
RetryStrategy: LimitRetry(LinearBackoff(5*time.Millisecond), 5),
}); err != nil {
t.Fatalf("expected refresh to recover, got %v", err)
}
if remaining := flaky.fails.Load(); remaining != 0 {
t.Fatalf("expected all injected failures to be consumed, %d remaining", remaining)
}
assertTTL(t, lock, time.Minute)
})
t.Run("retry exhausted returns last error", func(t *testing.T) {
rc := redisConnect(t)
flaky := &flakyScripter{Client: rc.Client}
client := New(flaky)
lock, err := client.Obtain(t.Context(), rc.lockKey(), time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
// keep failing past the retry limit; we should see the injected error
// rather than ErrNotObtained.
flaky.fails.Store(10)
err = lock.Refresh(t.Context(), time.Minute, &Options{
RetryStrategy: LimitRetry(LinearBackoff(5*time.Millisecond), 2),
})
if !errors.Is(err, errFlaky) {
t.Fatalf("expected %v, got %v", errFlaky, err)
}
})
t.Run("expired", func(t *testing.T) {
lock := quickObtain(t, 5*time.Millisecond)
defer lock.Release(t.Context())
// try refreshing after expiry
time.Sleep(10 * time.Millisecond)
if exp, got := ErrNotObtained, lock.Refresh(t.Context(), time.Minute, nil); !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
})
t.Run("nil receiver", func(t *testing.T) {
var lock *Lock
if err := lock.Refresh(t.Context(), time.Minute, nil); !errors.Is(err, ErrNotObtained) {
t.Fatalf("expected %v, got %v", ErrNotObtained, err)
}
})
t.Run("value mismatch", func(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
lock, err := Obtain(t.Context(), rc, lockKey, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
// another process steals the slot
if err := rc.Set(t.Context(), lockKey, "intruder", time.Hour).Err(); err != nil {
t.Fatal(err)
}
if err := lock.Refresh(t.Context(), time.Minute, nil); !errors.Is(err, ErrNotObtained) {
t.Fatalf("expected %v, got %v", ErrNotObtained, err)
}
})
t.Run("deleted key", func(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
lock, err := Obtain(t.Context(), rc, lockKey, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
if err := rc.Del(t.Context(), lockKey).Err(); err != nil {
t.Fatal(err)
}
if err := lock.Refresh(t.Context(), time.Minute, nil); !errors.Is(err, ErrNotObtained) {
t.Fatalf("expected %v, got %v", ErrNotObtained, err)
}
})
t.Run("sequential refreshes", func(t *testing.T) {
lock := quickObtain(t, time.Hour)
defer lock.Release(t.Context())
if err := lock.Refresh(t.Context(), 30*time.Second, nil); err != nil {
t.Fatal(err)
}
assertTTL(t, lock, 30*time.Second)
if err := lock.Refresh(t.Context(), 2*time.Minute, nil); err != nil {
t.Fatal(err)
}
assertTTL(t, lock, 2*time.Minute)
})
t.Run("preserves token and metadata", func(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
lock, err := Obtain(t.Context(), rc, lockKey, time.Hour, &Options{Token: "tok", Metadata: "meta"})
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
if err := lock.Refresh(t.Context(), time.Minute, nil); err != nil {
t.Fatal(err)
}
v, err := rc.Get(t.Context(), lockKey).Result()
if err != nil {
t.Fatal(err)
}
if exp := "tok" + "meta"; v != exp {
t.Fatalf("expected %q, got %q", exp, v)
}
if exp, got := "tok", lock.Token(); exp != got {
t.Fatalf("expected token %q, got %q", exp, got)
}
if exp, got := "meta", lock.Metadata(); exp != got {
t.Fatalf("expected metadata %q, got %q", exp, got)
}
})
t.Run("multi-key missing", func(t *testing.T) {
rc := redisConnect(t)
keyA, keyB := rc.lockKey(), rc.lockKey()
lock, err := ObtainMulti(t.Context(), rc, []string{keyA, keyB}, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
if err := rc.Del(t.Context(), keyB).Err(); err != nil {
t.Fatal(err)
}
if err := lock.Refresh(t.Context(), time.Minute, nil); !errors.Is(err, ErrNotObtained) {
t.Fatalf("expected %v, got %v", ErrNotObtained, err)
}
})
t.Run("multi-key wrong value", func(t *testing.T) {
rc := redisConnect(t)
keyA, keyB := rc.lockKey(), rc.lockKey()
lock, err := ObtainMulti(t.Context(), rc, []string{keyA, keyB}, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
if err := rc.Set(t.Context(), keyA, "intruder", time.Hour).Err(); err != nil {
t.Fatal(err)
}
if err := lock.Refresh(t.Context(), time.Minute, nil); !errors.Is(err, ErrNotObtained) {
t.Fatalf("expected %v, got %v", ErrNotObtained, err)
}
})
t.Run("ctx cancelled during retry", func(t *testing.T) {
rc := redisConnect(t)
flaky := &flakyScripter{Client: rc.Client}
client := New(flaky)
lock, err := client.Obtain(t.Context(), rc.lockKey(), time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
// keep failing so Refresh stays in the retry loop until ctx is cancelled.
flaky.fails.Store(1000)
ctx, cancel := context.WithCancel(t.Context())
time.AfterFunc(10*time.Millisecond, cancel)
err = lock.Refresh(ctx, time.Minute, &Options{
RetryStrategy: LinearBackoff(5 * time.Millisecond),
})
if !errors.Is(err, context.Canceled) {
t.Fatalf("expected error to wrap context.Canceled, got %v", err)
}
if !errors.Is(err, errFlaky) {
t.Fatalf("expected error to wrap %v, got %v", errFlaky, err)
}
})
}
func TestLock_Release_expired(t *testing.T) {
lock := quickObtain(t, 5*time.Millisecond)
defer lock.Release(t.Context())
// try releasing
time.Sleep(10 * time.Millisecond)
if exp, got := ErrLockNotHeld, lock.Release(t.Context()); !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
}
func TestLock_Release_not_own(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
lock, err := Obtain(t.Context(), rc, lockKey, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(t.Context())
// manually transfer ownership
if err := rc.Set(t.Context(), lockKey, "ABCD", 0).Err(); err != nil {
t.Fatal(err)
}
cmd := rc.Get(t.Context(), lockKey)
v, err := cmd.Result()
if err != nil {
t.Fatal(err)
}
if v != "ABCD" {
t.Fatalf("expected %v, got %v", "ABCD", v)
}
// try releasing
if exp, got := ErrLockNotHeld, lock.Release(t.Context()); !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
}
func TestLock_Release_not_held(t *testing.T) {
rc := redisConnect(t)
lockKey := rc.lockKey()
lock1, err := Obtain(t.Context(), rc, lockKey, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock1.Release(t.Context())
lock2, err := Obtain(t.Context(), rc, lockKey, time.Minute, nil)
if exp, got := ErrNotObtained, err; !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
if exp, got := (*Lock)(nil), lock2; exp != got {
t.Fatalf("expected %v, got %v", exp, got)
}
if exp, got := ErrLockNotHeld, lock2.Release(t.Context()); !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
}
func TestLock_ObtainMulti(t *testing.T) {
rc := redisConnect(t)
lockKey1 := rc.lockKey("_MultiLock_1")
lockKey2 := rc.lockKey("_MultiLock_2")
lockKey3 := rc.lockKey("_MultiLock_3")
lockKey4 := rc.lockKey("_MultiLock_4")
// 1. Obtain lock 1 and 2
lock12, err := ObtainMulti(t.Context(), rc, []string{lockKey1, lockKey2}, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
// 2. Obtain lock 3 and 4
lock34, err := ObtainMulti(t.Context(), rc, []string{lockKey3, lockKey4}, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
// 3. Try to obtain lock 2 and 3
_, err = ObtainMulti(t.Context(), rc, []string{lockKey2, lockKey3}, time.Hour, nil)
// Expect it to fail since lock 2 and 3 are already locked.
if !errors.Is(err, ErrNotObtained) {
t.Fatalf("expected ErrNotObtained, got %s.", err)
}
// 4. Release lock 1 and 2
lock12.Release(t.Context())
// 5. Obtain lock 1
lock1, err := ObtainMulti(t.Context(), rc, []string{lockKey1}, time.Hour, nil)
// Expected to succeed since lock 1 was released (along with lock 2)
if err != nil {
t.Fatal(err)
}
defer lock1.Release(t.Context())
// 6. Try to obtain lock 2 and 3 (again)
_, err = ObtainMulti(t.Context(), rc, []string{lockKey2, lockKey3}, time.Hour, nil)
// Expect it to fail since lock 3 is still locked.
if !errors.Is(err, ErrNotObtained) {
t.Fatalf("expected ErrNotObtained, got %s.", err)
}
// 7. Release lock 3 and 4
lock34.Release(t.Context())
// 8. Try to obtain lock 2 and 3 (again)
lock23, err := ObtainMulti(t.Context(), rc, []string{lockKey2, lockKey3}, time.Hour, nil)
// Expect it to succeed since lock 2 and 3 are available.
if err != nil {
t.Fatal(err)
}
defer lock23.Release(t.Context())
}
// ----------------------------------------------------------------------------
var lockInc = new(atomic.Int64)
var redisOpts = &redis.Options{
Network: "tcp",
Addr: "127.0.0.1:6379",
DB: 9,
}
type testRedis struct {
*redis.Client
keys []string
}
func (rc *testRedis) lockKey(suffix ...string) string {
key := fmt.Sprintf("__bsm_redislock_%d__", lockInc.Add(1))
if len(suffix) > 0 {
key += suffix[0]
}
rc.keys = append(rc.keys, key)
return key
}
func redisConnect(t *testing.T) *testRedis {
t.Helper()
rc := &testRedis{Client: redis.NewClient(redisOpts)}
t.Cleanup(func() {
// t.Context() is canceled before Cleanup runs, so use a fresh context
ctx := context.Background()
if len(rc.keys) > 0 {
_ = rc.Del(ctx, rc.keys...).Err()
}
_ = rc.Close()
})
return rc
}
func quickObtain(t *testing.T, ttl time.Duration) *Lock {
t.Helper()
rc := redisConnect(t)
lock, err := Obtain(t.Context(), rc, rc.lockKey(), ttl, nil)
if err != nil {
t.Fatal(err)
}
return lock
}
func assertTTL(t *testing.T, lock *Lock, exp time.Duration) {
t.Helper()
ttl, err := lock.TTL(t.Context())
if err != nil {
t.Fatal(err)
}
delta := ttl - exp
if delta < 0 {
delta = -delta
}
if delta > time.Second {
t.Fatalf("expected ~%v, got %v", exp, ttl)
}
}
var errFlaky = errors.New("flaky scripter: injected failure")
// flakyScripter wraps a redis.Client and fails the next `fails` script
// invocations before delegating to the wrapped client.
type flakyScripter struct {
*redis.Client
fails atomic.Int32
}
func (f *flakyScripter) shouldFail() bool {
for {
n := f.fails.Load()
if n <= 0 {
return false
}
if f.fails.CompareAndSwap(n, n-1) {
return true
}
}
}
func (f *flakyScripter) Eval(ctx context.Context, script string, keys []string, args ...any) *redis.Cmd {
if f.shouldFail() {
cmd := redis.NewCmd(ctx)
cmd.SetErr(errFlaky)
return cmd
}
return f.Client.Eval(ctx, script, keys, args...)
}
func (f *flakyScripter) EvalSha(ctx context.Context, sha1 string, keys []string, args ...any) *redis.Cmd {
if f.shouldFail() {
cmd := redis.NewCmd(ctx)
cmd.SetErr(errFlaky)
return cmd
}
return f.Client.EvalSha(ctx, sha1, keys, args...)
}