49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
// Copyright © 2023 Thorsten Schubert <tschubert@bafh.org>
|
|
|
|
package retry
|
|
|
|
import "time"
|
|
|
|
type FibonacciBackoff struct {
|
|
initialDelay time.Duration
|
|
prevDelay time.Duration
|
|
nextDelay time.Duration
|
|
maxRetries uint
|
|
currentRetries uint
|
|
}
|
|
|
|
func NewFibonacciBackoff(initialDelay time.Duration, maxRetries uint) *FibonacciBackoff {
|
|
return &FibonacciBackoff{
|
|
initialDelay: initialDelay,
|
|
prevDelay: 0,
|
|
nextDelay: initialDelay,
|
|
maxRetries: maxRetries,
|
|
}
|
|
}
|
|
|
|
func (s *FibonacciBackoff) NextDelay() time.Duration {
|
|
current := s.nextDelay
|
|
s.prevDelay, s.nextDelay = s.nextDelay, s.prevDelay+s.nextDelay
|
|
return current
|
|
}
|
|
|
|
func (s *FibonacciBackoff) Next() bool {
|
|
if s.currentRetries >= s.maxRetries {
|
|
return false
|
|
}
|
|
s.currentRetries++
|
|
return true
|
|
}
|
|
|
|
func (s *FibonacciBackoff) Retries() (uint, uint) {
|
|
return s.currentRetries, s.maxRetries
|
|
}
|
|
|
|
func (s *FibonacciBackoff) Name() string {
|
|
return "fibonacci"
|
|
}
|
|
|
|
func (s *FibonacciBackoff) Reset() {
|
|
s.prevDelay, s.nextDelay, s.currentRetries = 0, s.initialDelay, 0
|
|
}
|