forked from bsm/redislock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redislock.go
288 lines (237 loc) · 6.88 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
282
283
284
285
286
287
288
package redislock
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"io"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/redis/go-redis/v9"
)
var (
luaRefresh = redis.NewScript(`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("pexpire", KEYS[1], ARGV[2]) else return 0 end`)
luaRelease = redis.NewScript(`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`)
luaPTTL = redis.NewScript(`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")
)
// RedisClient is a minimal client interface.
type RedisClient interface {
redis.Scripter
SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.BoolCmd
}
// Client wraps a redis client.
type Client struct {
client RedisClient
tmp []byte
tmpMu sync.Mutex
}
// New creates a new Client instance with a custom namespace.
func New(client RedisClient) *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(ctx context.Context, 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()
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 ticker *time.Ticker
for {
ok, err := c.obtain(ctx, 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 ticker == nil {
ticker = time.NewTicker(backoff)
defer ticker.Stop()
} else {
ticker.Reset(backoff)
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ticker.C:
}
}
}
func (c *Client) obtain(ctx context.Context, key, value string, ttl time.Duration) (bool, error) {
return c.client.SetNX(ctx, key, value, ttl).Result()
}
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
key string
value string
}
// Obtain is a short-cut for New(...).Obtain(...).
func Obtain(ctx context.Context, client RedisClient, key string, ttl time.Duration, opt *Options) (*Lock, error) {
return New(client).Obtain(ctx, 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(ctx context.Context) (time.Duration, error) {
res, err := luaPTTL.Run(ctx, l.client, []string{l.key}, l.value).Result()
if err == redis.Nil {
return 0, nil
} else if err != nil {
return 0, err
}
if num := res.(int64); num > 0 {
return time.Duration(num) * time.Millisecond, nil
}
return 0, nil
}
// Refresh extends the lock with a new TTL.
// May return ErrNotObtained if refresh is unsuccessful.
func (l *Lock) Refresh(ctx context.Context, ttl time.Duration, opt *Options) error {
ttlVal := strconv.FormatInt(int64(ttl/time.Millisecond), 10)
status, err := luaRefresh.Run(ctx, l.client, []string{l.key}, l.value, ttlVal).Result()
if err != nil {
return err
} else if status == int64(1) {
return nil
}
return ErrNotObtained
}
// Release manually releases the lock.
// May return ErrLockNotHeld.
func (l *Lock) Release(ctx context.Context) error {
if l == nil {
return ErrLockNotHeld
}
res, err := luaRelease.Run(ctx, l.client, []string{l.key}, l.value).Result()
if err == redis.Nil {
return ErrLockNotHeld
} else if err != nil {
return err
}
if i, ok := res.(int64); !ok || i != 1 {
return ErrLockNotHeld
}
return nil
}
// --------------------------------------------------------------------
// Options describe the options for the lock
type Options struct {
// RetryStrategy allows to customise the lock retry strategy.
// Default: do not retry
RetryStrategy RetryStrategy
// Metadata string is appended to the lock token.
Metadata string
}
func (o *Options) getMetadata() string {
if o != nil {
return o.Metadata
}
return ""
}
func (o *Options) getRetryStrategy() RetryStrategy {
if o != nil && o.RetryStrategy != nil {
return o.RetryStrategy
}
return NoRetry()
}
// --------------------------------------------------------------------
// RetryStrategy allows to customise 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
}
}