package hostedctl import "sync" // attemptLocks serialises the controller's operations on one attempt // (ruling R18). One controller owns a database (R11), so an in-memory lock // is enough. type attemptLocks struct { mu sync.Mutex m map[string]*attemptLock // waiting, when set, is called with the attempt ID each time a caller // finds the lock held or awaited and is about to wait. Tests use it to // see contention without sleeping; production leaves it nil. waiting func(id string) } type attemptLock struct { mu sync.Mutex users int // holders and waiters; the entry goes when it reaches zero } // lockAttempt takes attempt id's lock and returns the function that // releases it. Every operation on one attempt runs under it, held across // its provider calls: Launch's and Replay's dispatch, Stop, Refresh's // per-job reconcile and re-base, and the pause, resume and reaper actions. // // Never call it inside a store transaction, and never hold two attempts' // locks at once: a transaction may be waiting for the lock's holder, which // needs the store to finish. An entry lives only while someone holds or // waits for it, so unknown attempt IDs leave nothing behind. func (c *Controller) lockAttempt(id string) func() { l := &c.attempts l.mu.Lock() if l.m == nil { l.m = map[string]*attemptLock{} } e := l.m[id] if e == nil { e = &attemptLock{} l.m[id] = e } e.users++ contended, hook := e.users > 1, l.waiting l.mu.Unlock() if contended && hook != nil { hook(id) } e.mu.Lock() var once sync.Once return func() { once.Do(func() { e.mu.Unlock() l.mu.Lock() if e.users--; e.users == 0 { delete(l.m, id) } l.mu.Unlock() }) } }