-
Notifications
You must be signed in to change notification settings - Fork 0
/
locker.go
69 lines (60 loc) · 1.58 KB
/
locker.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
// Package locker provides functions for distributed locking.
package locker
import (
"context"
"crypto/rand"
"encoding/base64"
"sync"
"time"
"github.com/go-redis/redis/v8"
)
// RedisClient is redis scripter interface.
type RedisClient interface {
Eval(ctx context.Context, script string, keys []string, args ...interface{}) *redis.Cmd
EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *redis.Cmd
ScriptExists(ctx context.Context, hashes ...string) *redis.BoolSliceCmd
ScriptLoad(ctx context.Context, script string) *redis.StringCmd
}
// Locker defines parameters for creating new lock.
type Locker struct {
client RedisClient
buf []byte
mu sync.Mutex
}
// NewLocker creates new locker.
func NewLocker(client RedisClient) *Locker {
return &Locker{
client: client,
buf: make([]byte, 16),
}
}
// Lock creates and applies new lock.
func (locker *Locker) Lock(ctx context.Context, key string, ttl time.Duration) (LockResult, error) {
r := LockResult{}
value, err := locker.randomString()
if err != nil {
return r, err
}
r.Lock = Lock{
locker: locker,
key: key,
value: value,
}
r.Result, err = r.Lock.Lock(ctx, ttl)
return r, err
}
// randomString creates random string to use as lock key value
func (locker *Locker) randomString() (string, error) {
locker.mu.Lock()
defer locker.mu.Unlock()
_, err := rand.Reader.Read(locker.buf)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(locker.buf), nil
}
// LockResult contains new lock and result of applying a lock.
type LockResult struct {
Lock
Result
}