File size: 1,338 Bytes
6a7089a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package bridge

import (
	"fmt"
	"sync"
	"time"
)

const DefaultLockTimeout = 10 * time.Minute

type lockEntry struct {
	owner   string
	expires time.Time
}

type LockManager struct {
	locks map[string]lockEntry
	mu    sync.Mutex
}

func NewLockManager() *LockManager {
	return &LockManager{
		locks: make(map[string]lockEntry),
	}
}

func (m *LockManager) TryLock(tabID, owner string, ttl time.Duration) error {
	m.mu.Lock()
	defer m.mu.Unlock()

	l, ok := m.locks[tabID]
	if ok && time.Now().Before(l.expires) && l.owner != owner {
		return fmt.Errorf("tab %s is locked by %s for another %v", tabID, l.owner, time.Until(l.expires).Round(time.Second))
	}

	m.locks[tabID] = lockEntry{
		owner:   owner,
		expires: time.Now().Add(ttl),
	}
	return nil
}

func (m *LockManager) Unlock(tabID, owner string) error {
	m.mu.Lock()
	defer m.mu.Unlock()

	l, ok := m.locks[tabID]
	if !ok || time.Now().After(l.expires) {
		delete(m.locks, tabID)
		return nil
	}

	if l.owner != owner {
		return fmt.Errorf("cannot unlock: tab %s is locked by %s", tabID, l.owner)
	}

	delete(m.locks, tabID)
	return nil
}

func (m *LockManager) Get(tabID string) *LockInfo {
	m.mu.Lock()
	defer m.mu.Unlock()

	l, ok := m.locks[tabID]
	if !ok || time.Now().After(l.expires) {
		return nil
	}

	return &LockInfo{
		Owner:     l.owner,
		ExpiresAt: l.expires,
	}
}