-
Notifications
You must be signed in to change notification settings - Fork 14
/
locker_client.go
107 lines (90 loc) · 3.32 KB
/
locker_client.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
package gomysqllock
import (
"context"
"database/sql"
"fmt"
"time"
)
// DefaultRefreshInterval is the periodic duration with which a connection is refreshed/pinged
const DefaultRefreshInterval = time.Second
type lockerOpt func(locker *MysqlLocker)
// MysqlLocker is the client which provide APIs to obtain lock
type MysqlLocker struct {
db *sql.DB
refreshInterval time.Duration
}
// NewMysqlLocker returns an instance of locker which can be used to obtain locks
func NewMysqlLocker(db *sql.DB, lockerOpts ...lockerOpt) *MysqlLocker {
locker := &MysqlLocker{
db: db,
refreshInterval: DefaultRefreshInterval,
}
for _, opt := range lockerOpts {
opt(locker)
}
return locker
}
// WithRefreshInterval sets the duration for refresh interval for each obtained lock
func WithRefreshInterval(d time.Duration) lockerOpt {
return func(l *MysqlLocker) { l.refreshInterval = d }
}
// Obtain tries to acquire lock (with no MySQL timeout) with background context. This call is expected to block is lock is already held
func (l MysqlLocker) Obtain(key string) (*Lock, error) {
return l.ObtainTimeoutContext(context.Background(), key, -1)
}
// ObtainTimeout tries to acquire lock with background context and a MySQL timeout. This call is expected to block is lock is already held
func (l MysqlLocker) ObtainTimeout(key string, timeout int) (*Lock, error) {
return l.ObtainTimeoutContext(context.Background(), key, timeout)
}
// ObtainContext tries to acquire lock and gives up when the given context is cancelled
func (l MysqlLocker) ObtainContext(ctx context.Context, key string) (*Lock, error) {
return l.ObtainTimeoutContext(ctx, key, -1)
}
// ObtainTimeoutContext tries to acquire lock and gives up when the given context is cancelled
func (l MysqlLocker) ObtainTimeoutContext(ctx context.Context, key string, timeout int) (*Lock, error) {
cancellableContext, cancelFunc := context.WithCancel(context.Background())
dbConn, err := l.db.Conn(ctx)
if err != nil {
cancelFunc()
return nil, fmt.Errorf("failed to get a db connection: %w", err)
}
row := dbConn.QueryRowContext(ctx, "SELECT GET_LOCK(?, ?)", key, timeout)
var res sql.NullInt32
err = row.Scan(&res)
if err != nil {
//Close database connection whenever failed to acquire lock
defer dbConn.Close()
// mysql error does not tell if it was due to context closing, checking it manually
select {
case <-ctx.Done():
cancelFunc()
return nil, ErrGetLockContextCancelled
default:
break
}
cancelFunc()
return nil, fmt.Errorf("could not read mysql response: %w", err)
} else if !res.Valid {
//Close database connection whenever failed to acquire lock
defer dbConn.Close()
// Internal MySQL error occurred, such as out-of-memory, thread killed or others (the doc is not clear)
// Note: some MySQL/MariaDB versions (like MariaDB 10.1) does not support -1 as timeout parameters
cancelFunc()
return nil, ErrMySQLInternalError
} else if res.Int32 == 0 {
//Close database connection whenever failed to acquire lock
defer dbConn.Close()
// MySQL Timeout
cancelFunc()
return nil, ErrMySQLTimeout
}
lock := &Lock{
key: key,
conn: dbConn,
unlocker: make(chan struct{}, 1),
lostLockContext: cancellableContext,
cancelFunc: cancelFunc,
}
go lock.refresher(l.refreshInterval, cancelFunc)
return lock, nil
}