Documentation
¶
Overview ¶
Package retrier provides a generic retry mechanism with exponential backoff and jitter.
Index ¶
- type DebugLogger
- type DelaySuggestioner
- type NoOpLogger
- type Result
- type RetryError
- type RetryErrorCause
- type RetryOption
- func WithInitialDuration(d time.Duration) RetryOption
- func WithJitter(d time.Duration) RetryOption
- func WithLogAttrs(attrs ...any) RetryOption
- func WithMaxAttempts(n int) RetryOption
- func WithMaxDuration(d time.Duration) RetryOption
- func WithMultiplier(m float64) RetryOption
- func WithRetryPolicy(p RetryPolicy) RetryOption
- type RetryPolicy
- type RetryableError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type DebugLogger ¶
type DebugLogger interface {
// Enabled returns true if debug logging is enabled.
// When false, the retry handler will skip logging entirely for efficiency.
Enabled() bool
// LogRetry logs retry attempts with backoff information.
// Parameters:
// - ctx: context for the retry operation
// - attempt: current attempt number (1-based)
// - maxAttempts: maximum number of attempts allowed
// - backoff: the delay before the next retry (0 for success/exhausted)
// - err: the error that triggered the retry (nil on success)
// - attrs: optional alternating key-value pairs (string, any, string, any, ...)
// following Go's slog convention for structured logging.
LogRetry(ctx context.Context, attempt int, maxAttempts int, backoff time.Duration, err error, attrs ...any)
}
DebugLogger provides structured debug logging capabilities for the retry package. Users can implement this interface to provide custom logging behavior. When debug mode is disabled, use NoOpLogger for zero overhead.
type DelaySuggestioner ¶ added in v1.0.3
type DelaySuggestioner interface {
error
// SuggestedDelay returns the delay suggested by the server or protocol.
// Return 0 if no delay is suggested (use calculated backoff).
SuggestedDelay() time.Duration
}
DelaySuggestioner is an optional interface that errors can implement to suggest a backoff delay. This is useful for protocols that communicate backoff hints, such as HTTP 429 with Retry-After header or gRPC retry-info.
When an error implements this interface, the suggested delay is used as the minimum backoff for the initial attempt: max(serverDelay, calculatedBackoff).
type NoOpLogger ¶
type NoOpLogger struct{}
NoOpLogger is a no-operation implementation of DebugLogger. It provides zero overhead when debug mode is disabled. All methods are empty and Enabled() always returns false.
func NewNoOpLogger ¶
func NewNoOpLogger() *NoOpLogger
NewNoOpLogger creates a new NoOpLogger instance.
func (*NoOpLogger) Enabled ¶
func (n *NoOpLogger) Enabled() bool
Enabled returns false - debug logging is disabled.
type Result ¶
type Result[T any] struct { // contains filtered or unexported fields }
Result encapsulates the immutable outcome of a retry operation. It holds either a successful value or an error, along with metadata about the execution.
func NewFailureResult ¶
NewFailureResult creates a Result representing a failed retry operation.
func NewSuccessResult ¶
NewSuccessResult creates a Result representing a successful retry operation.
func Retry ¶
func Retry[T any](ctx context.Context, logger DebugLogger, fn func() (T, error), opts ...RetryOption) Result[T]
Retry executes the provided function with retry logic. It will retry the function up to MaxAttempts times, applying exponential backoff with jitter between attempts.
Type parameter T represents the return type of the function being retried. Returns a Result containing the value (if successful), error (if failed), and the number of attempts made.
The ctx parameter allows cancellation of the retry operation. If the context is cancelled during a backoff delay, the function returns immediately with ErrContextCancelled.
The logger parameter provides debug logging capabilities. When debug mode is disabled (NoOpLogger), there is zero overhead from logging.
opts are functional options to configure retry behavior:
- WithMaxAttempts(n int): Maximum retry attempts (default: 3)
- WithJitter(d time.Duration): Random delay added to backoff (default: 0)
- WithInitialDuration(d time.Duration): Initial backoff duration (default: 1s)
- WithMultiplier(m float64): Backoff multiplier (default: 2.0)
- WithMaxDuration(d time.Duration): Maximum backoff duration (default: 1m)
- WithRetryPolicy(p RetryPolicy): Default retry policy for standard errors (default: RetryPolicyAuto)
Error handling:
- If the error implements RetryableError, its RetryPolicy() is used
- Standard errors use the configured DefaultRetryPolicy (defaults to RetryPolicyAuto)
Example:
result := retrier.Retry(ctx, logger, fn,
retrier.WithMaxAttempts(5),
retrier.WithJitter(100*time.Millisecond),
retrier.WithInitialDuration(1*time.Second),
)
func (Result[T]) Decompose ¶ added in v1.0.1
Decompose returns the result as a tuple (value, attempts, error). This provides idiomatic Go error handling for traditionalists:
value, attempts, err := retrier.Retry(ctx, logger, fn).Decompose()
if err != nil {
// handle error
}
func (Result[T]) Unwrap ¶ added in v1.0.1
func (r Result[T]) Unwrap() T
Unwrap returns the successful value or panics if failed. Use only when failure is impossible or should crash.
type RetryError ¶
type RetryError struct {
Message string
Cause RetryErrorCause
// contains filtered or unexported fields
}
RetryError represents an error that occurred during retry attempts. It stores the original error for debugging and implements the RetryableError interface.
func NewRetryError ¶
func NewRetryError(cause RetryErrorCause, message string, policy RetryPolicy, wrapped error) *RetryError
NewRetryError creates a new RetryError with explicit classification. Parameters:
- cause: The error cause (ErrZeroAttempt or ErrExhaustedAttempts)
- message: Human-readable error message
- policy: RetryPolicyAuto, RetryPolicyManual, or RetryPolicyNever
- wrapped: The original error that caused the retry failure (may be nil)
func (*RetryError) Error ¶
func (e *RetryError) Error() string
Error returns the error message implementing the error interface.
func (*RetryError) Is ¶
func (e *RetryError) Is(target error) bool
Is allows errors.Is to match RetryError types.
func (*RetryError) RetryPolicy ¶
func (e *RetryError) RetryPolicy() RetryPolicy
RetryPolicy returns the automatic retry behavior for this error. When RetryError is returned (exhausted attempts), it returns the cached policy.
func (*RetryError) Unwrap ¶
func (e *RetryError) Unwrap() error
Unwrap returns the wrapped error for error chain support.
type RetryErrorCause ¶
type RetryErrorCause string
RetryErrorCause represents the cause of a retry error.
const ( // ErrZeroAttempt indicates that MaxAttempts was set to 0. ErrZeroAttempt RetryErrorCause = "zero attempt" // ErrExhaustedAttempts indicates that all retry attempts were exhausted. ErrExhaustedAttempts RetryErrorCause = "exhausted attempt" // ErrContextCancelled indicates that the context was cancelled during retry. ErrContextCancelled RetryErrorCause = "context cancelled" )
type RetryOption ¶ added in v1.0.1
type RetryOption func(*retryConfig)
RetryOption is a functional option for configuring retry behavior.
func WithInitialDuration ¶ added in v1.0.1
func WithInitialDuration(d time.Duration) RetryOption
WithInitialDuration sets the initial backoff duration. Default is 1 second.
func WithJitter ¶ added in v1.0.1
func WithJitter(d time.Duration) RetryOption
WithJitter sets the maximum random duration added to backoff delays. This helps avoid thundering herd problems. Default is 0 (no jitter).
func WithLogAttrs ¶ added in v1.0.3
func WithLogAttrs(attrs ...any) RetryOption
WithLogAttrs sets additional attributes to be passed to the logger. Attributes follow Go's slog convention for structured logging - alternating key-value pairs (string, any, string, any, ...). These attributes are passed to LogRetry calls for structured logging context.
func WithMaxAttempts ¶ added in v1.0.1
func WithMaxAttempts(n int) RetryOption
WithMaxAttempts sets the maximum number of retry attempts. Default is 3.
func WithMaxDuration ¶ added in v1.0.1
func WithMaxDuration(d time.Duration) RetryOption
WithMaxDuration sets the maximum backoff duration. Default is 1 minute.
func WithMultiplier ¶ added in v1.0.1
func WithMultiplier(m float64) RetryOption
WithMultiplier sets the backoff multiplier. Each subsequent delay is multiplied by this value. Default is 2.0.
func WithRetryPolicy ¶ added in v1.0.1
func WithRetryPolicy(p RetryPolicy) RetryOption
WithRetryPolicy sets the default retry policy for standard errors. Default is RetryPolicyAuto (standard errors are retried automatically).
type RetryPolicy ¶
type RetryPolicy int
RetryPolicy defines automatic retry behavior. This controls whether Retry() will attempt exponential backoff.
const ( // RetryPolicyAuto indicates the error should be retried automatically // with exponential backoff. RetryPolicyAuto RetryPolicy = iota // RetryPolicyManual indicates the error should not be auto-retried, // but is eligible for manual retry. RetryPolicyManual // RetryPolicyNever indicates a permanent failure that should not be retried. RetryPolicyNever )
type RetryableError ¶
type RetryableError interface {
error
// RetryPolicy controls automatic retry behavior.
// Used by the retry handler to decide whether to retry.
RetryPolicy() RetryPolicy
}
RetryableError is an interface that errors must implement to be handled by the retry mechanism. Users should implement this interface on their custom error types to control retry behavior.
Directories
¶
| Path | Synopsis |
|---|---|
|
example
|
|
|
fetch
command
Package main contains a fake HTTP server for demonstrating the retrier package.
|
Package main contains a fake HTTP server for demonstrating the retrier package. |
|
fetch/simple_logger
Package simple_logger provides a simple implementation of the retrier.DebugLogger interface that prints retry information to stdout.
|
Package simple_logger provides a simple implementation of the retrier.DebugLogger interface that prints retry information to stdout. |
|
rate_limit
command
Package main demonstrates handling HTTP 429 Rate Limit responses with Retry-After headers.
|
Package main demonstrates handling HTTP 429 Rate Limit responses with Retry-After headers. |