oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package hostedctl
2
3import "sync"
4
5// attemptLocks serialises the controller's operations on one attempt
6// (ruling R18). One controller owns a database (R11), so an in-memory lock
7// is enough.
8type attemptLocks struct {
9 mu sync.Mutex
10 m map[string]*attemptLock
11 // waiting, when set, is called with the attempt ID each time a caller
12 // finds the lock held or awaited and is about to wait. Tests use it to
13 // see contention without sleeping; production leaves it nil.
14 waiting func(id string)
15}
16
17type attemptLock struct {
18 mu sync.Mutex
19 users int // holders and waiters; the entry goes when it reaches zero
20}
21
22// lockAttempt takes attempt id's lock and returns the function that
23// releases it. Every operation on one attempt runs under it, held across
24// its provider calls: Launch's and Replay's dispatch, Stop, Refresh's
25// per-job reconcile and re-base, and the pause, resume and reaper actions.
26//
27// Never call it inside a store transaction, and never hold two attempts'
28// locks at once: a transaction may be waiting for the lock's holder, which
29// needs the store to finish. An entry lives only while someone holds or
30// waits for it, so unknown attempt IDs leave nothing behind.
31func (c *Controller) lockAttempt(id string) func() {
32 l := &c.attempts
33 l.mu.Lock()
34 if l.m == nil {
35 l.m = map[string]*attemptLock{}
36 }
37 e := l.m[id]
38 if e == nil {
39 e = &attemptLock{}
40 l.m[id] = e
41 }
42 e.users++
43 contended, hook := e.users > 1, l.waiting
44 l.mu.Unlock()
45
46 if contended && hook != nil {
47 hook(id)
48 }
49 e.mu.Lock()
50 var once sync.Once
51 return func() {
52 once.Do(func() {
53 e.mu.Unlock()
54 l.mu.Lock()
55 if e.users--; e.users == 0 {
56 delete(l.m, id)
57 }
58 l.mu.Unlock()
59 })
60 }
61}
62