ceremonyclient/go-libp2p/p2p/host/basic/internal/backoff/backoff.go
Cassandra Heart dbd95bd9e9
v2.1.0 (#439)
* v2.1.0 [omit consensus and adjacent] - this commit will be amended with the full release after the file copy is complete

* 2.1.0 main node rollup
2025-09-30 02:48:15 -05:00

53 lines
828 B
Go

package backoff
import (
"time"
)
var since = time.Since
const defaultDelay = 100 * time.Millisecond
const defaultMaxDelay = 1 * time.Minute
type ExpBackoff struct {
Delay time.Duration
MaxDelay time.Duration
failures int
lastRun time.Time
}
func (b *ExpBackoff) init() {
if b.Delay == 0 {
b.Delay = defaultDelay
}
if b.MaxDelay == 0 {
b.MaxDelay = defaultMaxDelay
}
}
func (b *ExpBackoff) calcDelay() time.Duration {
delay := b.Delay * time.Duration(1<<(b.failures-1))
delay = min(delay, b.MaxDelay)
return delay
}
func (b *ExpBackoff) Run(f func() error) (err error, ran bool) {
b.init()
if b.failures != 0 {
if since(b.lastRun) < b.calcDelay() {
return nil, false
}
}
b.lastRun = time.Now()
err = f()
if err == nil {
b.failures = 0
} else {
b.failures++
}
return err, true
}