github.com/koko1123/flow-go-1@v0.29.6/utils/liveness/check.go (about) 1 package liveness 2 3 import ( 4 "sync" 5 "time" 6 ) 7 8 // Check is a heartbeat style liveness reporter. 9 // 10 // It is not guaranteed to be safe to CheckIn across multiple goroutines. 11 // IsLive must be safe to be called concurrently with CheckIn. 12 type Check interface { 13 CheckIn() 14 IsLive(time.Duration) bool 15 } 16 17 // internalCheck implements a Check. 18 type internalCheck struct { 19 lock sync.RWMutex 20 lastCheckIn time.Time 21 defaultTolerance time.Duration 22 } 23 24 // CheckIn adds a heartbeat at the current time. 25 func (c *internalCheck) CheckIn() { 26 c.lock.Lock() 27 c.lastCheckIn = time.Now() 28 c.lock.Unlock() 29 } 30 31 // IsLive checks if we are still live against the given the tolerace between hearbeats. 32 // 33 // If tolerance is 0, the default tolerance is used. 34 func (c *internalCheck) IsLive(tolerance time.Duration) bool { 35 c.lock.RLock() 36 defer c.lock.RUnlock() 37 if tolerance == 0 { 38 tolerance = c.defaultTolerance 39 } 40 41 return c.lastCheckIn.Add(tolerance).After(time.Now()) 42 }