forked from bsm/redislock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redislock.go
281 lines (232 loc) · 6.8 KB
/
redislock.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
package redislock
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"io"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/mediocregopher/radix/v3"
)
var (
luaRefresh = radix.NewEvalScript(1, `if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("pexpire", KEYS[1], ARGV[2]) else return 0 end`)
luaRelease = radix.NewEvalScript(1, `if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`)
luaPTTL = radix.NewEvalScript(1, `if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("pttl", KEYS[1]) else return -3 end`)
)
var (
// ErrNotObtained is returned when a lock cannot be obtained.
ErrNotObtained = errors.New("redislock: not obtained")
// ErrLockNotHeld is returned when trying to release an inactive lock.
ErrLockNotHeld = errors.New("redislock: lock not held")
)
// Client wraps a redis client.
type Client struct {
client radix.Client
tmp []byte
tmpMu sync.Mutex
}
// New creates a new Client instance with a custom namespace.
func New(client radix.Client) *Client {
return &Client{client: client}
}
// Obtain tries to obtain a new lock using a key with the given TTL.
// May return ErrNotObtained if not successful.
func (c *Client) Obtain(key string, ttl time.Duration, opt *Options) (*Lock, error) {
// Create a random token
token, err := c.randomToken()
if err != nil {
return nil, err
}
value := token + opt.getMetadata()
ctx := opt.getContext()
retry := opt.getRetryStrategy()
// make sure we don't retry forever
if _, ok := ctx.Deadline(); !ok {
var cancel context.CancelFunc
ctx, cancel = context.WithDeadline(ctx, time.Now().Add(ttl))
defer cancel()
}
var timer *time.Timer
for {
ok, err := c.obtain(key, value, ttl)
if err != nil {
return nil, err
} else if ok {
return &Lock{client: c, key: key, value: value}, nil
}
backoff := retry.NextBackoff()
if backoff < 1 {
return nil, ErrNotObtained
}
if timer == nil {
timer = time.NewTimer(backoff)
defer timer.Stop()
} else {
timer.Reset(backoff)
}
select {
case <-ctx.Done():
return nil, ErrNotObtained
case <-timer.C:
}
}
}
func (c *Client) obtain(key, value string, ttl time.Duration) (bool, error) {
var result string
err := c.client.Do(radix.FlatCmd(&result, "SET", key, value, "PX", ttl.Milliseconds(), "NX"))
return result == "OK", err
}
func (c *Client) randomToken() (string, error) {
c.tmpMu.Lock()
defer c.tmpMu.Unlock()
if len(c.tmp) == 0 {
c.tmp = make([]byte, 16)
}
if _, err := io.ReadFull(rand.Reader, c.tmp); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(c.tmp), nil
}
// --------------------------------------------------------------------
// Lock represents an obtained, distributed lock.
type Lock struct {
client *Client
key string
value string
}
// Obtain is a short-cut for New(...).Obtain(...).
func Obtain(client radix.Client, key string, ttl time.Duration, opt *Options) (*Lock, error) {
return New(client).Obtain(key, ttl, opt)
}
// Key returns the redis key used by the lock.
func (l *Lock) Key() string {
return l.key
}
// Token returns the token value set by the lock.
func (l *Lock) Token() string {
return l.value[:22]
}
// Metadata returns the metadata of the lock.
func (l *Lock) Metadata() string {
return l.value[22:]
}
// TTL returns the remaining time-to-live. Returns 0 if the lock has expired.
func (l *Lock) TTL() (time.Duration, error) {
var num int64
err := l.client.client.Do(luaPTTL.Cmd(&num, l.key, l.value))
if err != nil || num < 0 {
return 0, err
}
return time.Duration(num) * time.Millisecond, nil
}
// Refresh extends the lock with a new TTL.
// May return ErrNotObtained if refresh is unsuccessful.
func (l *Lock) Refresh(ttl time.Duration, opt *Options) error {
var status bool
err := l.client.client.Do(luaRefresh.Cmd(&status, l.key, l.value, strconv.FormatInt(ttl.Milliseconds(), 10)))
if err != nil || status {
return err
}
return ErrNotObtained
}
// Release manually releases the lock.
// May return ErrLockNotHeld.
func (l *Lock) Release() error {
var num int
err := l.client.client.Do(luaRelease.Cmd(&num, l.key, l.value))
if err != nil || num == 1 {
return err
}
return ErrLockNotHeld
}
// --------------------------------------------------------------------
// Options describe the options for the lock
type Options struct {
// RetryStrategy allows to customize the lock retry strategy.
// Default: do not retry
RetryStrategy RetryStrategy
// Metadata string is appended to the lock token.
Metadata string
// Context provides an optional context for timeout and cancellation control.
// If requested, Obtain will by default retry until the TTL expires. This
// behavior can be tweaked with a custom context deadline.
Context context.Context
}
func (o *Options) getMetadata() string {
if o != nil {
return o.Metadata
}
return ""
}
func (o *Options) getContext() context.Context {
if o != nil && o.Context != nil {
return o.Context
}
return context.Background()
}
func (o *Options) getRetryStrategy() RetryStrategy {
if o != nil && o.RetryStrategy != nil {
return o.RetryStrategy
}
return NoRetry()
}
// --------------------------------------------------------------------
// RetryStrategy allows to customize the lock retry strategy.
type RetryStrategy interface {
// NextBackoff returns the next backoff duration.
NextBackoff() time.Duration
}
type linearBackoff time.Duration
// LinearBackoff allows retries regularly with customized intervals
func LinearBackoff(backoff time.Duration) RetryStrategy {
return linearBackoff(backoff)
}
// NoRetry acquire the lock only once.
func NoRetry() RetryStrategy {
return linearBackoff(0)
}
func (r linearBackoff) NextBackoff() time.Duration {
return time.Duration(r)
}
type limitedRetry struct {
s RetryStrategy
cnt int64
max int64
}
// LimitRetry limits the number of retries to max attempts.
func LimitRetry(s RetryStrategy, max int) RetryStrategy {
return &limitedRetry{s: s, max: int64(max)}
}
func (r *limitedRetry) NextBackoff() time.Duration {
if atomic.LoadInt64(&r.cnt) >= r.max {
return 0
}
atomic.AddInt64(&r.cnt, 1)
return r.s.NextBackoff()
}
type exponentialBackoff struct {
cnt uint64
min, max time.Duration
}
// ExponentialBackoff strategy is an optimization strategy with a retry time of 2**n milliseconds (n means number of times).
// You can set a minimum and maximum value, the recommended minimum value is not less than 16ms.
func ExponentialBackoff(min, max time.Duration) RetryStrategy {
return &exponentialBackoff{min: min, max: max}
}
func (r *exponentialBackoff) NextBackoff() time.Duration {
cnt := atomic.AddUint64(&r.cnt, 1)
ms := 2 << 25
if cnt < 25 {
ms = 2 << cnt
}
if d := time.Duration(ms) * time.Millisecond; d < r.min {
return r.min
} else if r.max != 0 && d > r.max {
return r.max
} else {
return d
}
}