-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdistributed_lock.go
More file actions
377 lines (324 loc) · 9.99 KB
/
distributed_lock.go
File metadata and controls
377 lines (324 loc) · 9.99 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package scale
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"fmt"
"hash/fnv"
"log"
"sync"
"time"
"github.com/redis/go-redis/v9"
)
// DistributedLock provides distributed locking for state machine transitions
// and other coordination needs across multiple Workflow instances.
type DistributedLock interface {
// Acquire obtains a lock for the given key. Returns a release function.
// Blocks until the lock is acquired or context is cancelled.
Acquire(ctx context.Context, key string, ttl time.Duration) (release func(), err error)
// TryAcquire attempts to acquire a lock without blocking.
// Returns false if the lock is already held.
TryAcquire(ctx context.Context, key string, ttl time.Duration) (release func(), acquired bool, err error)
}
// --- InMemoryLock ---
// InMemoryLock implements DistributedLock for testing and single-server deployments.
// Uses sync.Mutex per key with a map.
type InMemoryLock struct {
mu sync.Mutex
locks map[string]*lockEntry
}
type lockEntry struct {
mu sync.Mutex
waiters chan struct{} // signals when the lock is released
held bool
}
// NewInMemoryLock creates a new in-memory distributed lock.
func NewInMemoryLock() *InMemoryLock {
return &InMemoryLock{
locks: make(map[string]*lockEntry),
}
}
// getOrCreateEntry returns the lock entry for the given key, creating one if necessary.
func (l *InMemoryLock) getOrCreateEntry(key string) *lockEntry {
l.mu.Lock()
defer l.mu.Unlock()
entry, ok := l.locks[key]
if !ok {
entry = &lockEntry{
waiters: make(chan struct{}, 1),
}
l.locks[key] = entry
}
return entry
}
// Acquire obtains a lock for the given key, blocking until acquired or context cancelled.
func (l *InMemoryLock) Acquire(ctx context.Context, key string, ttl time.Duration) (func(), error) {
entry := l.getOrCreateEntry(key)
for {
entry.mu.Lock()
if !entry.held {
entry.held = true
entry.mu.Unlock()
var releaseOnce sync.Once
release := func() {
releaseOnce.Do(func() {
entry.mu.Lock()
entry.held = false
entry.mu.Unlock()
// Signal one waiter
select {
case entry.waiters <- struct{}{}:
default:
}
})
}
// If ttl > 0, schedule automatic release
if ttl > 0 {
go func() {
timer := time.NewTimer(ttl)
defer timer.Stop()
select {
case <-timer.C:
release()
case <-ctx.Done():
}
}()
}
return release, nil
}
entry.mu.Unlock()
// Wait for release signal or context cancellation
select {
case <-entry.waiters:
// Lock was released, try again
continue
case <-ctx.Done():
return nil, fmt.Errorf("acquire lock for %s: %w", key, ctx.Err())
}
}
}
// TryAcquire attempts to acquire a lock without blocking.
// Returns false if the lock is already held.
func (l *InMemoryLock) TryAcquire(ctx context.Context, key string, ttl time.Duration) (func(), bool, error) {
entry := l.getOrCreateEntry(key)
entry.mu.Lock()
if entry.held {
entry.mu.Unlock()
return nil, false, nil
}
entry.held = true
entry.mu.Unlock()
var releaseOnce sync.Once
release := func() {
releaseOnce.Do(func() {
entry.mu.Lock()
entry.held = false
entry.mu.Unlock()
// Signal one waiter
select {
case entry.waiters <- struct{}{}:
default:
}
})
}
// If ttl > 0, schedule automatic release
if ttl > 0 {
go func() {
timer := time.NewTimer(ttl)
defer timer.Stop()
select {
case <-timer.C:
release()
case <-ctx.Done():
}
}()
}
return release, true, nil
}
// --- PGAdvisoryLock ---
// PGAdvisoryLock implements DistributedLock using PostgreSQL advisory locks
// (pg_advisory_lock / pg_advisory_unlock). The key string is hashed to int64
// for use as the lock ID.
type PGAdvisoryLock struct {
db *sql.DB
}
// NewPGAdvisoryLock creates a new PostgreSQL advisory lock implementation.
func NewPGAdvisoryLock(db *sql.DB) *PGAdvisoryLock {
return &PGAdvisoryLock{db: db}
}
// Acquire obtains a PostgreSQL advisory lock for the given key.
// Blocks until the lock is acquired or context is cancelled.
// Note: ttl is not natively supported by pg_advisory_lock; the lock is held
// until explicitly released or the session ends.
func (l *PGAdvisoryLock) Acquire(ctx context.Context, key string, ttl time.Duration) (func(), error) {
lockID := hashToInt64(key)
// Use a dedicated connection to ensure the advisory lock is tied to it.
conn, err := l.db.Conn(ctx)
if err != nil {
return nil, fmt.Errorf("acquire lock connection for %s: %w", key, err)
}
_, err = conn.ExecContext(ctx, "SELECT pg_advisory_lock($1)", lockID)
if err != nil {
conn.Close()
return nil, fmt.Errorf("acquire lock for %s: %w", key, err)
}
var releaseOnce sync.Once
release := func() {
releaseOnce.Do(func() {
// Use a background context for unlock since the original ctx may be cancelled
_, _ = conn.ExecContext(context.Background(), "SELECT pg_advisory_unlock($1)", lockID)
conn.Close()
})
}
return release, nil
}
// TryAcquire attempts to acquire a PostgreSQL advisory lock without blocking.
// Returns false if the lock is already held.
func (l *PGAdvisoryLock) TryAcquire(ctx context.Context, key string, ttl time.Duration) (func(), bool, error) {
lockID := hashToInt64(key)
conn, err := l.db.Conn(ctx)
if err != nil {
return nil, false, fmt.Errorf("try acquire lock connection for %s: %w", key, err)
}
var acquired bool
err = conn.QueryRowContext(ctx, "SELECT pg_try_advisory_lock($1)", lockID).Scan(&acquired)
if err != nil {
conn.Close()
return nil, false, fmt.Errorf("try acquire lock for %s: %w", key, err)
}
if !acquired {
conn.Close()
return nil, false, nil
}
var releaseOnce sync.Once
release := func() {
releaseOnce.Do(func() {
_, _ = conn.ExecContext(context.Background(), "SELECT pg_advisory_unlock($1)", lockID)
conn.Close()
})
}
return release, true, nil
}
// hashToInt64 converts a string key to an int64 using FNV-1a hash.
// The same key always produces the same hash value.
func hashToInt64(key string) int64 {
h := fnv.New64a()
_, _ = h.Write([]byte(key))
v := h.Sum64() & 0x7FFFFFFFFFFFFFFF // Clear sign bit; always <= math.MaxInt64.
return int64(v) //nolint:gosec // masked to non-negative range
}
// --- RedisLock ---
// redisReleaseScript atomically releases a Redis lock only if the caller
// holds it (i.e., the stored value matches the token).
var redisReleaseScript = redis.NewScript(`
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
`)
// RedisLock implements DistributedLock using Redis SET NX with TTL.
// Uses a unique token per acquisition to ensure only the holder can release.
type RedisLock struct {
addr string
password string
db int
client *redis.Client
initOnce sync.Once
}
// NewRedisLock creates a new Redis distributed lock using the given address.
// The Redis client is created lazily on first use.
func NewRedisLock(addr string) *RedisLock {
return NewRedisLockWithOptions(addr, "", 0)
}
// NewRedisLockWithOptions creates a new Redis distributed lock with full
// connection options. The Redis client is created lazily on first use.
func NewRedisLockWithOptions(addr, password string, db int) *RedisLock {
return &RedisLock{addr: addr, password: password, db: db}
}
// connect initialises the Redis client exactly once.
func (l *RedisLock) connect() {
l.initOnce.Do(func() {
l.client = redis.NewClient(&redis.Options{
Addr: l.addr,
Password: l.password,
DB: l.db,
})
})
}
// Close releases the underlying Redis client connection.
func (l *RedisLock) Close() error {
l.connect()
return l.client.Close()
}
// randomToken generates a cryptographically random hex string used as the
// lock token, ensuring only the holder can release.
func randomToken() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("generate lock token: %w", err)
}
return hex.EncodeToString(b), nil
}
// buildRelease returns a release function that atomically deletes the lock
// only when the stored token matches, making it safe to call multiple times.
func (l *RedisLock) buildRelease(key, token string) func() {
var once sync.Once
return func() {
once.Do(func() {
ctx := context.Background()
if err := redisReleaseScript.Run(ctx, l.client, []string{key}, token).Err(); err != nil {
log.Printf("distributed lock: failed to release Redis lock for key %s: %v", key, err)
}
})
}
}
// Acquire obtains a Redis lock for the given key using SET NX PX.
// Retries with exponential backoff until the lock is acquired or ctx is
// cancelled. Returns a release function that atomically deletes the lock.
func (l *RedisLock) Acquire(ctx context.Context, key string, ttl time.Duration) (func(), error) {
l.connect()
token, err := randomToken()
if err != nil {
return nil, err
}
backoff := 16 * time.Millisecond
const maxBackoff = 512 * time.Millisecond
for {
cmd := l.client.SetArgs(ctx, key, token, redis.SetArgs{Mode: "NX", TTL: ttl})
if err := cmd.Err(); err != nil && err != redis.Nil {
return nil, fmt.Errorf("acquire redis lock for %s: %w", key, err)
}
if cmd.Val() == "OK" {
return l.buildRelease(key, token), nil
}
select {
case <-ctx.Done():
return nil, fmt.Errorf("acquire redis lock for %s: %w", key, ctx.Err())
case <-time.After(backoff):
}
backoff *= 2
if backoff > maxBackoff {
backoff = maxBackoff
}
}
}
// TryAcquire attempts to acquire a Redis lock for the given key without
// blocking. Returns (release, true, nil) if acquired, (nil, false, nil) if
// the lock is already held.
func (l *RedisLock) TryAcquire(ctx context.Context, key string, ttl time.Duration) (func(), bool, error) {
l.connect()
token, err := randomToken()
if err != nil {
return nil, false, err
}
cmd := l.client.SetArgs(ctx, key, token, redis.SetArgs{Mode: "NX", TTL: ttl})
if err := cmd.Err(); err != nil && err != redis.Nil {
return nil, false, fmt.Errorf("try acquire redis lock for %s: %w", key, err)
}
if cmd.Val() != "OK" {
return nil, false, nil
}
return l.buildRelease(key, token), true, nil
}