Documentation
¶
Index ¶
- func Do[T any](ctx context.Context, action func(context.Context) (T, error), opts ...Option) (T, error)
- func DoErr(ctx context.Context, action func(context.Context) error, opts ...Option) error
- func DoErrHedged(ctx context.Context, action func(context.Context) error, opts ...Option) error
- func DoErrState(ctx context.Context, action func(context.Context, RetryState) error, ...) error
- func DoErrStateHedged(ctx context.Context, action func(context.Context, RetryState) error, ...) error
- func DoHedged[T any](ctx context.Context, action func(context.Context) (T, error), opts ...Option) (T, error)
- func DoState[T any](ctx context.Context, action func(context.Context, RetryState) (T, error), ...) (T, error)
- func DoStateHedged[T any](ctx context.Context, action func(context.Context, RetryState) (T, error), ...) (T, error)
- func FatalError(err error) error
- func WithTestingBypass(ctx context.Context) context.Context
- type AdaptiveBucket
- type Backoff
- type Config
- func (c *Config) Do(ctx context.Context, action func(context.Context) (any, error)) (any, error)
- func (c *Config) DoErr(ctx context.Context, action func(context.Context) error) error
- func (c *Config) DoErrHedged(ctx context.Context, action func(context.Context) error) error
- func (c *Config) DoHedged(ctx context.Context, action func(context.Context) (any, error)) (any, error)
- type Instrumenter
- type Option
- func WithAdaptiveBucket(bucket *AdaptiveBucket) Option
- func WithBackoff(backoff Backoff) Option
- func WithBaseDelay(delay time.Duration) Option
- func WithCircuitBreaker(cb *circuit.Breaker) Option
- func WithFallback[T any](f func(context.Context, error) (T, error)) Option
- func WithFallbackErr(f func(context.Context, error) error) Option
- func WithHedgingDelay(delay time.Duration) Option
- func WithInstrumenter(instr Instrumenter) Option
- func WithMaxAttempts(attempts uint) Option
- func WithMaxDelay(delay time.Duration) Option
- func WithName(name string) Option
- func WithPanicRecovery() Option
- func WithRetryIf(target error) Option
- func WithRetryIfFunc(f func(error) bool) Option
- type PanicError
- type RetryAfterError
- type RetryState
- type Retryer
- type StateMachine
- type TransitionFunc
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Do ¶
func Do[T any](ctx context.Context, action func(context.Context) (T, error), opts ...Option) (T, error)
Do executes an action with retry logic using the provided options. This generic function handles functions returning (T, error).
func DoErr ¶
DoErr executes an action with retry logic using the provided options. This function handles functions returning only error.
func DoErrHedged ¶
DoErrHedged executes an action using speculative retries (hedging).
func DoErrState ¶
func DoErrState(ctx context.Context, action func(context.Context, RetryState) error, opts ...Option) error
DoErrState executes a stateful action with retry logic using the provided options.
func DoErrStateHedged ¶
func DoErrStateHedged(ctx context.Context, action func(context.Context, RetryState) error, opts ...Option) error
DoErrStateHedged executes a stateful action with speculative retries (hedging).
func DoHedged ¶
func DoHedged[T any](ctx context.Context, action func(context.Context) (T, error), opts ...Option) (T, error)
DoHedged executes an action using speculative retries (hedging). It starts multiple attempts concurrently if previous ones take too long.
func DoState ¶
func DoState[T any](ctx context.Context, action func(context.Context, RetryState) (T, error), opts ...Option) (T, error)
DoState executes a stateful action with retry logic using the provided options. The RetryState is passed to the closure, allowing it to adapt to failure history.
func DoStateHedged ¶
func DoStateHedged[T any](ctx context.Context, action func(context.Context, RetryState) (T, error), opts ...Option) (T, error)
DoStateHedged executes a stateful action with speculative retries (hedging).
func FatalError ¶
FatalError wraps an error to indicate that the retry loop should terminate immediately.
Types ¶
type AdaptiveBucket ¶
type AdaptiveBucket struct {
// contains filtered or unexported fields
}
AdaptiveBucket implements a client-side token bucket rate limiter for retries. It protects downstream services from thundering herds by depleting tokens when retries occur and refilling them on successful responses. This allows a fleet of clients to quickly cut off traffic to a degraded system, providing macro-level protection.
func DefaultAdaptiveBucket ¶
func DefaultAdaptiveBucket() *AdaptiveBucket
DefaultAdaptiveBucket creates a new AdaptiveBucket with standard defaults (max capacity: 500, retry cost: 5, success refill: 1).
func NewAdaptiveBucket ¶
func NewAdaptiveBucket(maxCapacity, retryCost, successRefill float64) *AdaptiveBucket
NewAdaptiveBucket creates a new AdaptiveBucket with the specified configuration. A common AWS-style configuration is maxCapacity=500, retryCost=5, successRefill=1.
func (*AdaptiveBucket) AcquireRetryToken ¶
func (b *AdaptiveBucket) AcquireRetryToken() bool
AcquireRetryToken attempts to consume a token for a retry. Returns true if a token was successfully consumed, false if the bucket is empty.
func (*AdaptiveBucket) AddSuccessToken ¶
func (b *AdaptiveBucket) AddSuccessToken()
AddSuccessToken adds a fraction of a token back to the bucket upon a successful response.
type Backoff ¶
type Backoff interface {
// Next calculates the duration to wait before the specified attempt.
// The attempt parameter is 0-indexed.
Next(attempt uint) time.Duration
}
Backoff defines the interface for temporal distribution of retries.
func NewFullJitter ¶
NewFullJitter returns a Backoff implementation using the AWS Full Jitter algorithm. The base duration dictates the initial delay, and the cap defines the absolute maximum.
type Config ¶
type Config struct {
Name string
MaxAttempts uint
BaseDelay time.Duration
MaxDelay time.Duration
HedgingDelay time.Duration
Backoff Backoff
Policy *retryPolicy
Instrumenter Instrumenter
CircuitBreaker *circuit.Breaker
Fallback any
AdaptiveBucket *AdaptiveBucket
RecoverPanics bool
}
Config represents the configuration for the retry execution.
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a reasonable production-grade configuration.
func (*Config) DoErrHedged ¶
DoErrHedged satisfies the Retryer interface.
type Instrumenter ¶
type Instrumenter interface {
// BeforeAttempt is called before each execution attempt.
// It can return a new context (e.g., to inject trace spans).
BeforeAttempt(ctx context.Context, state RetryState) context.Context
// AfterAttempt is called after each execution attempt.
AfterAttempt(ctx context.Context, state RetryState)
}
Instrumenter defines the lifecycle hooks for monitoring retry executions. It is a zero-dependency interface to allow custom implementations for logging, metrics, and tracing.
type Option ¶
type Option func(*Config)
Option defines a functional option for configuring a retry execution.
func WithAdaptiveBucket ¶
func WithAdaptiveBucket(bucket *AdaptiveBucket) Option
WithAdaptiveBucket sets a token bucket for adaptive retries. The bucket should be shared across multiple executions to protect downstream services globally.
func WithBackoff ¶
WithBackoff sets a custom backoff algorithm.
func WithBaseDelay ¶
WithBaseDelay sets the initial delay for the backoff algorithm.
func WithCircuitBreaker ¶
WithCircuitBreaker integrates a circuit breaker into the retry execution.
func WithFallback ¶
WithFallback sets a function to be called if all retries are exhausted or if the circuit breaker is open. T must match the return type of the retry action.
func WithFallbackErr ¶
WithFallbackErr sets a fallback function for operations that only return an error.
func WithHedgingDelay ¶
WithHedgingDelay sets the delay for speculative retries (hedging). If a response doesn't arrive within this delay, another attempt is started concurrently.
func WithInstrumenter ¶
func WithInstrumenter(instr Instrumenter) Option
WithInstrumenter sets a telemetry instrumenter.
func WithMaxAttempts ¶
WithMaxAttempts sets the maximum number of execution attempts.
func WithMaxDelay ¶
WithMaxDelay sets the maximum delay for the backoff algorithm.
func WithPanicRecovery ¶ added in v1.0.1
func WithPanicRecovery() Option
WithPanicRecovery enables recovering from panics during execution. If a panic occurs, it is converted into a PanicError and treated as a retryable error.
func WithRetryIf ¶
WithRetryIf sets a specific error to trigger a retry.
func WithRetryIfFunc ¶
WithRetryIfFunc sets a custom function to determine if an error should be retried.
type PanicError ¶ added in v1.0.1
PanicError represents a recovered panic during execution.
func (*PanicError) Error ¶ added in v1.0.1
func (p *PanicError) Error() string
Error implements the error interface.
type RetryAfterError ¶
RetryAfterError is implemented by errors that specify how long to wait before retrying. This is commonly used with HTTP 429 (Too Many Requests) or 503 (Service Unavailable) to respect Retry-After headers. It also supports pushback signals to cancel all retries.
type RetryState ¶
type RetryState struct {
// Name is the optional identifier for the operation being retried.
Name string
// Attempt is the current 0-indexed retry iteration.
Attempt uint
// MaxAttempts is the maximum number of attempts allowed.
MaxAttempts uint
// LastError is the error encountered in the previous attempt.
LastError error
// TotalDuration is the cumulative time spent across all attempts and sleeps.
TotalDuration time.Duration
// NextDelay is the duration to be slept before the next attempt.
NextDelay time.Duration
}
RetryState encapsulates the current state of a retry execution.
type Retryer ¶
type Retryer interface {
// Do executes a function that returns a value and an error.
Do(ctx context.Context, action func(context.Context) (any, error)) (any, error)
// DoHedged executes a function using speculative retries (hedging).
DoHedged(ctx context.Context, action func(context.Context) (any, error)) (any, error)
// DoErr executes a function that returns only an error.
DoErr(ctx context.Context, action func(context.Context) error) error
// DoErrHedged executes a function using speculative retries (hedging).
DoErrHedged(ctx context.Context, action func(context.Context) error) error
}
Retryer defines the interface for executing actions with resilience.
type StateMachine ¶ added in v1.0.2
StateMachine represents a resilient state machine inspired by Erlang's gen_statem. Every state transition is protected by the configured resilience policies.
func NewStateMachine ¶ added in v1.0.2
func NewStateMachine[S any, D any, E any](initialState S, initialData D, transition TransitionFunc[S, D, E], opts ...Option) *StateMachine[S, D, E]
NewStateMachine creates a new resilient state machine with the provided initial state, data, and transition function.
func (*StateMachine[S, D, E]) GetData ¶ added in v1.0.2
func (sm *StateMachine[S, D, E]) GetData() D
GetData returns the current data of the state machine.
func (*StateMachine[S, D, E]) GetState ¶ added in v1.0.2
func (sm *StateMachine[S, D, E]) GetState() S
GetState returns the current state of the state machine.
func (*StateMachine[S, D, E]) Handle ¶ added in v1.0.2
func (sm *StateMachine[S, D, E]) Handle(ctx context.Context, event E) error
Handle processes an event and performs a state transition. The transition is executed within a resilience envelope (Retries, Circuit Breakers, etc.). If the transition succeeds, the state machine updates its internal state and data.
type TransitionFunc ¶ added in v1.0.2
type TransitionFunc[S any, D any, E any] func(ctx context.Context, state S, data D, event E, rs RetryState) (S, D, error)
TransitionFunc defines the signature for a state transition function. It takes the current state, data, and event, and returns the next state and data. It also receives the current RetryState to allow transitions to adapt to failure history.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
adaptiveretry
command
|
|
|
basic
command
|
|
|
circuitbreaker
command
|
|
|
fallback
command
|
|
|
hedging
command
|
|
|
http
command
|
|
|
panicrecovery
command
|
|
|
pushback
command
|
|
|
stateful
command
|
|
|
statemachine
command
|
|
|
telemetry
|
|