Repository navigation
Expand file tree
/
Copy pathlock.go
More file actions
105 lines (89 loc) · 2.44 KB
/
Copy pathlock.go
File metadata and controls
105 lines (89 loc) · 2.44 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
package main
import (
"fmt"
"sync"
"time"
)
// TabLock represents an active lock held by an agent on a tab.
type TabLock struct {
Owner string `json:"owner"`
LockedAt time.Time `json:"lockedAt"`
ExpiresAt time.Time `json:"expiresAt"`
}
// lockManager handles tab locking with timeout-based deadlock prevention.
type lockManager struct {
locks map[string]*TabLock // tabID → lock
mu sync.Mutex
}
const (
defaultLockTimeout = 30 * time.Second
maxLockTimeout = 5 * time.Minute
)
func newLockManager() *lockManager {
return &lockManager{locks: make(map[string]*TabLock)}
}
// Lock acquires a lock on a tab for the given owner. Returns error if already
// locked by a different owner (and not expired).
func (lm *lockManager) Lock(tabID, owner string, timeout time.Duration) error {
if owner == "" {
return fmt.Errorf("owner required")
}
if timeout <= 0 {
timeout = defaultLockTimeout
}
if timeout > maxLockTimeout {
timeout = maxLockTimeout
}
lm.mu.Lock()
defer lm.mu.Unlock()
if existing, ok := lm.locks[tabID]; ok {
if time.Now().Before(existing.ExpiresAt) && existing.Owner != owner {
return fmt.Errorf("tab locked by %q until %s", existing.Owner, existing.ExpiresAt.Format(time.RFC3339))
}
}
lm.locks[tabID] = &TabLock{
Owner: owner,
LockedAt: time.Now(),
ExpiresAt: time.Now().Add(timeout),
}
return nil
}
// Unlock releases a lock. Only the owner (or anyone after expiry) can unlock.
func (lm *lockManager) Unlock(tabID, owner string) error {
lm.mu.Lock()
defer lm.mu.Unlock()
existing, ok := lm.locks[tabID]
if !ok {
return nil // not locked, idempotent
}
if existing.Owner != owner && time.Now().Before(existing.ExpiresAt) {
return fmt.Errorf("tab locked by %q, cannot unlock", existing.Owner)
}
delete(lm.locks, tabID)
return nil
}
// Get returns the lock info for a tab, or nil if unlocked/expired.
func (lm *lockManager) Get(tabID string) *TabLock {
lm.mu.Lock()
defer lm.mu.Unlock()
lock, ok := lm.locks[tabID]
if !ok {
return nil
}
if time.Now().After(lock.ExpiresAt) {
delete(lm.locks, tabID)
return nil
}
return lock
}
// CheckAccess returns an error if the tab is locked by someone other than owner.
func (lm *lockManager) CheckAccess(tabID, owner string) error {
lock := lm.Get(tabID)
if lock == nil {
return nil
}
if owner == "" || lock.Owner != owner {
return fmt.Errorf("tab locked by %q until %s", lock.Owner, lock.ExpiresAt.Format(time.RFC3339))
}
return nil
}