Documentation
¶
Overview ¶
Package retry provides retry policies with exponential backoff and optional jitter for resilient operation execution.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrUnretryable = errors.New("unretryable")
ErrUnretryable marks an error as one that Execute must not retry. Wrap a returned error with Unretryable (or return anything that wraps ErrUnretryable) to stop the retry loop immediately instead of exhausting the remaining attempts.
Functions ¶
func Unretryable ¶
Unretryable wraps err so Execute stops retrying on it. The original error is preserved in the chain, so errors.Is/As against it still work.
Types ¶
type Config ¶
type Config struct {
MaxAttempts uint `env:"MAX_ATTEMPTS" json:"maxAttempts" yaml:"maxAttempts"`
InitialDelay time.Duration `env:"INITIAL_DELAY" json:"initialDelay" yaml:"initialDelay"`
MaxDelay time.Duration `env:"MAX_DELAY" json:"maxDelay" yaml:"maxDelay"`
Multiplier float64 `env:"MULTIPLIER" json:"multiplier" yaml:"multiplier"`
UseJitter bool `env:"USE_JITTER" json:"useJitter" yaml:"useJitter"`
}
Config configures retry behavior.
func (*Config) EnsureDefaults ¶
func (cfg *Config) EnsureDefaults()
EnsureDefaults sets default values for zero (and invalid) fields. It clamps rather than merely zero-checking so a nonsensical config — a negative delay or a Multiplier below 1 that would shrink the backoff — can't produce a pathological policy, since the constructor returns no error to reject it.
type Policy ¶
type Policy interface {
Execute(ctx context.Context, operation func(ctx context.Context) error) error
}
Policy executes operations with retry logic.
func NewExponentialBackoffPolicy ¶
NewExponentialBackoffPolicy returns a Policy that retries with exponential backoff.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/primandproper/platform-go/v5/retry"
)
func main() {
policy := retry.NewExponentialBackoffPolicy(retry.Config{
MaxAttempts: 3,
InitialDelay: 10 * time.Millisecond,
MaxDelay: 100 * time.Millisecond,
Multiplier: 2.0,
})
attempts := 0
err := policy.Execute(context.Background(), func(_ context.Context) error {
attempts++
if attempts < 3 {
return fmt.Errorf("not yet")
}
return nil
})
fmt.Println(err)
fmt.Println(attempts)
}
Output: <nil> 3