This repository has been archived by the owner on Jun 24, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
lock_test.go
294 lines (236 loc) · 7.77 KB
/
lock_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
package lock
import (
"fmt"
"math/rand"
"os"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/go-redis/redis"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
const testRedisKey = "__bsm_redis_lock_unit_test__"
var _ = Describe("Locker", func() {
var (
subject *Locker
)
hostname, _ := os.Hostname()
tokenPfx := fmt.Sprintf("%s-%d-", hostname, os.Getpid())
var newLock = func() *Locker {
return New(redisClient, testRedisKey, &Options{
RetryCount: 4,
RetryDelay: 25 * time.Millisecond,
LockTimeout: time.Second,
TokenPrefix: tokenPfx,
})
}
var getTTL = func() (time.Duration, error) {
return redisClient.PTTL(testRedisKey).Result()
}
BeforeEach(func() {
subject = newLock()
Expect(subject.IsLocked()).To(BeFalse())
})
AfterEach(func() {
Expect(redisClient.Del(testRedisKey).Err()).NotTo(HaveOccurred())
})
It("should normalize options", func() {
locker := New(redisClient, testRedisKey, &Options{
LockTimeout: -1,
RetryCount: -1,
RetryDelay: -1,
})
Expect(locker.opts).To(Equal(Options{
LockTimeout: 5 * time.Second,
RetryCount: 0,
RetryDelay: 100 * time.Millisecond,
}))
})
It("should fail obtain with error", func() {
locker := newLock()
locker.Lock()
defer locker.Unlock()
_, err := Obtain(redisClient, testRedisKey, nil)
Expect(err).To(Equal(ErrLockNotObtained))
})
It("should obtain through short-cut", func() {
Expect(Obtain(redisClient, testRedisKey, nil)).To(BeAssignableToTypeOf(subject))
})
It("should obtain fresh locks", func() {
Expect(subject.Lock()).To(BeTrue())
Expect(subject.IsLocked()).To(BeTrue())
Expect(redisClient.Get(testRedisKey).Result()).To(HaveLen(24 + len(subject.opts.TokenPrefix)))
Expect(getTTL()).To(BeNumerically("~", time.Second, 10*time.Millisecond))
})
It("should retry if enabled", func() {
Expect(redisClient.Set(testRedisKey, "ABCD", 0).Err()).NotTo(HaveOccurred())
Expect(redisClient.PExpire(testRedisKey, 30*time.Millisecond).Err()).NotTo(HaveOccurred())
Expect(subject.Lock()).To(BeTrue())
Expect(subject.IsLocked()).To(BeTrue())
Expect(redisClient.Get(testRedisKey).Result()).To(Equal(subject.token))
Expect(subject.opts.TokenPrefix).To(Equal(subject.token[:len(subject.token)-24]))
Expect(getTTL()).To(BeNumerically("~", time.Second, 10*time.Millisecond))
})
It("should not retry if not enabled", func() {
Expect(redisClient.Set(testRedisKey, "ABCD", 0).Err()).NotTo(HaveOccurred())
Expect(redisClient.PExpire(testRedisKey, 150*time.Millisecond).Err()).NotTo(HaveOccurred())
subject.opts.RetryCount = 0
Expect(subject.Lock()).To(BeFalse())
Expect(subject.IsLocked()).To(BeFalse())
Expect(getTTL()).To(BeNumerically("~", 150*time.Millisecond, 10*time.Millisecond))
})
It("should give up when retry count reached", func() {
Expect(redisClient.Set(testRedisKey, "ABCD", 0).Err()).NotTo(HaveOccurred())
Expect(redisClient.PExpire(testRedisKey, 150*time.Millisecond).Err()).NotTo(HaveOccurred())
Expect(subject.Lock()).To(BeFalse())
Expect(subject.IsLocked()).To(BeFalse())
Expect(subject.token).To(Equal(""))
Expect(redisClient.Get(testRedisKey).Result()).To(Equal("ABCD"))
Expect(getTTL()).To(BeNumerically("~", 45*time.Millisecond, 20*time.Millisecond))
})
It("should release own locks", func() {
Expect(subject.Lock()).To(BeTrue())
Expect(subject.IsLocked()).To(BeTrue())
Expect(subject.Unlock()).NotTo(HaveOccurred())
Expect(subject.token).To(Equal(""))
Expect(subject.IsLocked()).To(BeFalse())
Expect(redisClient.Get(testRedisKey).Err()).To(Equal(redis.Nil))
})
It("should failure on release expired lock", func() {
Expect(subject.Lock()).To(BeTrue())
Expect(subject.IsLocked()).To(BeTrue())
time.Sleep(subject.opts.LockTimeout * 2)
err := subject.Unlock()
Expect(err).To(Equal(ErrLockUnlockFailed))
})
It("should not release someone else's locks", func() {
Expect(redisClient.Set(testRedisKey, "ABCD", 0).Err()).NotTo(HaveOccurred())
Expect(subject.IsLocked()).To(BeFalse())
err := subject.Unlock()
Expect(err).To(Equal(ErrLockUnlockFailed))
Expect(subject.token).To(Equal(""))
Expect(subject.IsLocked()).To(BeFalse())
Expect(redisClient.Get(testRedisKey).Val()).To(Equal("ABCD"))
})
It("should refresh locks", func() {
Expect(subject.Lock()).To(BeTrue())
Expect(subject.IsLocked()).To(BeTrue())
time.Sleep(50 * time.Millisecond)
Expect(getTTL()).To(BeNumerically("~", 950*time.Millisecond, 10*time.Millisecond))
Expect(subject.Lock()).To(BeTrue())
Expect(subject.IsLocked()).To(BeTrue())
Expect(getTTL()).To(BeNumerically("~", time.Second, 10*time.Millisecond))
})
It("should re-create expired locks on refresh", func() {
Expect(subject.Lock()).To(BeTrue())
Expect(subject.IsLocked()).To(BeTrue())
token := subject.token
Expect(redisClient.Del(testRedisKey).Err()).NotTo(HaveOccurred())
Expect(subject.Lock()).To(BeTrue())
Expect(subject.IsLocked()).To(BeTrue())
Expect(subject.token).NotTo(Equal(token))
Expect(getTTL()).To(BeNumerically("~", time.Second, 10*time.Millisecond))
})
It("should not re-capture expired locks acquiredby someone else", func() {
Expect(subject.Lock()).To(BeTrue())
Expect(subject.IsLocked()).To(BeTrue())
Expect(redisClient.Set(testRedisKey, "ABCD", 0).Err()).NotTo(HaveOccurred())
Expect(subject.Lock()).To(BeFalse())
Expect(subject.IsLocked()).To(BeFalse())
})
It("should prevent multiple locks (fuzzing)", func() {
res := int32(0)
wg := new(sync.WaitGroup)
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer GinkgoRecover()
defer wg.Done()
locker := newLock()
wait := rand.Int63n(int64(50 * time.Millisecond))
time.Sleep(time.Duration(wait))
ok, err := locker.Lock()
if err != nil {
atomic.AddInt32(&res, 100)
return
} else if !ok {
return
}
atomic.AddInt32(&res, 1)
}()
}
wg.Wait()
Expect(res).To(Equal(int32(1)))
})
It("should error when lock time exceeded while running handler", func() {
err := Run(redisClient, testRedisKey, &Options{LockTimeout: time.Millisecond}, func() {
time.Sleep(time.Millisecond * 5)
})
Expect(err).To(Equal(ErrLockDurationExceeded))
})
It("should retry and wait for locks if requested", func() {
var (
wg sync.WaitGroup
res int32
)
wg.Add(1)
go func() {
defer wg.Done()
defer GinkgoRecover()
err := Run(redisClient, testRedisKey, &Options{RetryCount: 10, RetryDelay: 10 * time.Millisecond}, func() {
atomic.AddInt32(&res, 1)
})
Expect(err).NotTo(HaveOccurred())
}()
err := Run(redisClient, testRedisKey, nil, func() {
atomic.AddInt32(&res, 1)
time.Sleep(20 * time.Millisecond)
})
wg.Wait()
Expect(err).NotTo(HaveOccurred())
Expect(res).To(Equal(int32(2)))
})
It("should give up retrying after timeout", func() {
var (
wg sync.WaitGroup
res int32
)
wg.Add(1)
go func() {
defer wg.Done()
defer GinkgoRecover()
err := Run(redisClient, testRedisKey, &Options{RetryCount: 1, RetryDelay: 10 * time.Millisecond}, func() {
atomic.AddInt32(&res, 1)
})
Expect(err).To(Equal(ErrLockNotObtained))
}()
err := Run(redisClient, testRedisKey, nil, func() {
atomic.AddInt32(&res, 1)
time.Sleep(100 * time.Millisecond)
})
wg.Wait()
Expect(err).NotTo(HaveOccurred())
Expect(res).To(Equal(int32(1)))
})
})
// --------------------------------------------------------------------
func TestSuite(t *testing.T) {
RegisterFailHandler(Fail)
AfterEach(func() {
Expect(redisClient.Del(testRedisKey).Err()).NotTo(HaveOccurred())
})
RunSpecs(t, "redis-lock")
}
var redisClient *redis.Client
var _ = BeforeSuite(func() {
redisClient = redis.NewClient(&redis.Options{
Network: "tcp",
Addr: "127.0.0.1:6379", DB: 9,
})
Expect(redisClient.Ping().Err()).NotTo(HaveOccurred())
})
var _ = AfterSuite(func() {
Expect(redisClient.Close()).To(Succeed())
})