-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathredislock_test.go
438 lines (365 loc) · 10.2 KB
/
redislock_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
package redislock_test
import (
"context"
"errors"
"fmt"
"math/rand"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
. "github.com/bsm/redislock"
"github.com/redis/go-redis/v9"
)
var redisOpts = &redis.Options{
Network: "tcp",
Addr: "127.0.0.1:6379",
DB: 9,
}
func TestClient(t *testing.T) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
// init client
client := New(rc)
// obtain
lock, err := client.Obtain(ctx, lockKey, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(ctx)
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(ctx, 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(ctx); err != nil {
t.Fatal(err)
}
// lock again
lock, err = client.Obtain(ctx, lockKey, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
defer lock.Release(ctx)
}
func TestObtain(t *testing.T) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
lock := quickObtain(t, rc, lockKey, time.Hour)
if err := lock.Release(ctx); err != nil {
t.Fatal(err)
}
}
func TestObtain_metadata(t *testing.T) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
meta := "my-data"
lock, err := Obtain(ctx, rc, lockKey, time.Hour, &Options{Metadata: meta})
if err != nil {
t.Fatal(err)
}
defer lock.Release(ctx)
if exp, got := meta, lock.Metadata(); exp != got {
t.Fatalf("expected %v, got %v", exp, got)
}
}
func TestObtain_custom_token(t *testing.T) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
// obtain lock
lock1, err := Obtain(ctx, rc, lockKey, time.Hour, &Options{Token: "foo", Metadata: "bar"})
if err != nil {
t.Fatal(err)
}
defer lock1.Release(ctx)
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(ctx, 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(ctx, rc, lockKey, time.Hour, &Options{Token: "foo", Metadata: "baz"})
if err != nil {
t.Fatal(err)
}
defer lock2.Release(ctx)
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_retry_success(t *testing.T) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
// obtain for 20ms
lock1 := quickObtain(t, rc, lockKey, 20*time.Millisecond)
defer lock1.Release(ctx)
// lock again with linar retry - 3x for 20ms
lock2, err := Obtain(ctx, rc, lockKey, time.Hour, &Options{
RetryStrategy: LimitRetry(LinearBackoff(20*time.Millisecond), 3),
})
if err != nil {
t.Fatal(err)
}
defer lock2.Release(ctx)
}
func TestObtain_retry_failure(t *testing.T) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
// obtain for 50ms
lock1 := quickObtain(t, rc, lockKey, 50*time.Millisecond)
defer lock1.Release(ctx)
// lock again with linar retry - 2x for 5ms
_, err := Obtain(ctx, 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_concurrent(t *testing.T) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
numLocks := int32(0)
numThreads := 100
wg := new(sync.WaitGroup)
errs := make(chan error, numThreads)
for i := 0; i < numThreads; i++ {
wg.Add(1)
go func() {
defer wg.Done()
wait := rand.Int63n(int64(10 * time.Millisecond))
time.Sleep(time.Duration(wait))
_, err := Obtain(ctx, 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) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
lock := quickObtain(t, rc, lockKey, time.Hour)
defer lock.Release(ctx)
// check TTL
assertTTL(t, lock, time.Hour)
// update TTL
if err := lock.Refresh(ctx, time.Minute, nil); err != nil {
t.Fatal(err)
}
// check TTL again
assertTTL(t, lock, time.Minute)
}
func TestLock_Refresh_expired(t *testing.T) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
lock := quickObtain(t, rc, lockKey, 5*time.Millisecond)
defer lock.Release(ctx)
// try releasing
time.Sleep(10 * time.Millisecond)
if exp, got := ErrNotObtained, lock.Refresh(ctx, time.Minute, nil); !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
}
func TestLock_Release_expired(t *testing.T) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
lock := quickObtain(t, rc, lockKey, 5*time.Millisecond)
defer lock.Release(ctx)
// try releasing
time.Sleep(10 * time.Millisecond)
if exp, got := ErrLockNotHeld, lock.Release(ctx); !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
}
func TestLock_Release_not_own(t *testing.T) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
lock := quickObtain(t, rc, lockKey, time.Hour)
defer lock.Release(ctx)
// manually transfer ownership
if err := rc.Set(ctx, lockKey, "ABCD", 0).Err(); err != nil {
t.Fatal(err)
}
cmd := rc.Get(ctx, 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(ctx); !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
}
func TestLock_Release_not_held(t *testing.T) {
lockKey := getLockKey()
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKey)
lock1 := quickObtain(t, rc, lockKey, time.Hour)
defer lock1.Release(ctx)
lock2, err := Obtain(context.Background(), 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(ctx); !errors.Is(got, exp) {
t.Fatalf("expected %v, got %v", exp, got)
}
}
func TestLock_ObtainMulti(t *testing.T) {
lockKeys := []string{
getLockKey() + "_MultiLock_1",
getLockKey() + "_MultiLock_2",
getLockKey() + "_MultiLock_3",
getLockKey() + "_MultiLock_4",
}
ctx := context.Background()
rc := redis.NewClient(redisOpts)
defer teardown(t, rc, lockKeys...)
lockKey1 := lockKeys[0]
lockKey2 := lockKeys[1]
lockKey3 := lockKeys[2]
lockKey4 := lockKeys[3]
// 1. Obtain lock 1 and 2
lock12, err := ObtainMulti(ctx, rc, []string{lockKey1, lockKey2}, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
// 2. Obtain lock 3 and 4
lock34, err := ObtainMulti(ctx, rc, []string{lockKey3, lockKey4}, time.Hour, nil)
if err != nil {
t.Fatal(err)
}
// 3. Try to obtain lock 2 and 3
_, err = ObtainMulti(ctx, 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(ctx)
// 5. Obtain lock 1
lock1, err := ObtainMulti(ctx, 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(ctx)
// 6. Try to obtain lock 2 and 3 (again)
_, err = ObtainMulti(ctx, 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(ctx)
// 8. Try to obtain lock 2 and 3 (again)
lock23, err := ObtainMulti(ctx, 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(ctx)
}
func getLockKey() string {
return fmt.Sprintf("__bsm_redislock_%s_%d__", getCallingFunctionName(1), time.Now().UnixNano())
}
func quickObtain(t *testing.T, rc *redis.Client, lockKey string, ttl time.Duration) *Lock {
t.Helper()
lock, err := Obtain(context.Background(), 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(context.Background())
if err != nil {
t.Fatal(err)
}
delta := ttl - exp
if delta < 0 {
delta = 1 - delta
}
if delta > time.Second {
t.Fatalf("expected ~%v, got %v", exp, ttl)
}
}
func teardown(t *testing.T, rc *redis.Client, lockKeys ...string) {
t.Helper()
for _, lockKey := range lockKeys {
if err := rc.Del(context.Background(), lockKey).Err(); err != nil {
t.Fatal(err)
}
}
if err := rc.Close(); err != nil {
t.Fatal(err)
}
}
func getCallingFunctionName(skipFrameCount int) string {
fpc, _, _, _ := runtime.Caller(1 + skipFrameCount)
funcName := "unknown"
fun := runtime.FuncForPC(fpc)
if fun != nil {
_, funcName = filepath.Split(fun.Name())
}
return funcName
}