retry

package
v1.25.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2025 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package retry provides intelligent retry mechanisms for handling transient failures

Package retry provides retry mechanism with exponential backoff for improved error handling and recovery

Index

Constants

View Source
const (
	// UnknownOperation represents an unknown operation name
	UnknownOperation = "unknown"
	// UnknownRegistry represents an unknown registry name
	UnknownRegistry = "unknown"
	// UnknownPlatform represents an unknown platform name
	UnknownPlatform = "unknown"
	// IntelligentDefaultMaxAttempts is the default maximum number of retry attempts for intelligent retry
	IntelligentDefaultMaxAttempts = 3
	// IntelligentDefaultInitialDelay is the default initial delay for intelligent retries
	IntelligentDefaultInitialDelay = 1 * time.Second
	// IntelligentDefaultMaxDelay is the default maximum delay for intelligent retries
	IntelligentDefaultMaxDelay = 60 * time.Second
	// IntelligentDefaultBaseMultiplier is the default base multiplier for intelligent exponential backoff
	IntelligentDefaultBaseMultiplier = 2.0
	// NetworkMaxAttempts is the maximum number of attempts for network errors
	NetworkMaxAttempts = 5
	// NetworkInitialDelay is the initial delay for network errors
	NetworkInitialDelay = 500 * time.Millisecond
	// NetworkMaxDelay is the maximum delay for network errors
	NetworkMaxDelay = 30 * time.Second
	// NetworkBaseMultiplier is the base multiplier for network errors
	NetworkBaseMultiplier = 1.5
	// RegistryMaxAttempts is the maximum number of attempts for registry errors
	RegistryMaxAttempts = 4
	// RegistryInitialDelay is the initial delay for registry errors
	RegistryInitialDelay = 2 * time.Second
	// RegistryMaxDelay is the maximum delay for registry errors
	RegistryMaxDelay = 120 * time.Second
	// RegistryBaseMultiplier is the base multiplier for registry errors
	RegistryBaseMultiplier = 2.5
	// RateLimitMaxAttempts is the maximum number of attempts for rate limiting errors
	RateLimitMaxAttempts = 6
	// RateLimitInitialDelay is the initial delay for rate limiting errors
	RateLimitInitialDelay = 5 * time.Second
	// RateLimitMaxDelay is the maximum delay for rate limiting errors
	RateLimitMaxDelay = 300 * time.Second
	// RateLimitBaseMultiplier is the base multiplier for rate limiting errors (golden ratio)
	RateLimitBaseMultiplier = 1.618
	// AuthMaxAttempts is the maximum number of attempts for authentication errors
	AuthMaxAttempts = 2
	// AuthInitialDelay is the initial delay for authentication errors
	AuthInitialDelay = 1 * time.Second
	// AuthMaxDelay is the maximum delay for authentication errors
	AuthMaxDelay = 10 * time.Second
	// AuthBaseMultiplier is the base multiplier for authentication errors
	AuthBaseMultiplier = 1.0
	// TimeoutMaxAttempts is the maximum number of attempts for timeout errors
	TimeoutMaxAttempts = 3
	// TimeoutInitialDelay is the initial delay for timeout errors
	TimeoutInitialDelay = 1 * time.Second
	// TimeoutMaxDelay is the maximum delay for timeout errors
	TimeoutMaxDelay = 30 * time.Second
	// TimeoutBaseMultiplier is the base multiplier for timeout errors
	TimeoutBaseMultiplier = 2.0
	// RecentSuccessMinutes is the time window for considering recent success
	RecentSuccessMinutes = 5
	// HighFailureThreshold is the threshold for high failure rate
	HighFailureThreshold = 5
	// MaxTimeoutAttempts is the maximum number of attempts when timeout patterns are detected
	MaxTimeoutAttempts = 6
	// LowSeverityMaxAttempts is the maximum number of attempts for low severity errors
	LowSeverityMaxAttempts = 8
	// JitterMinMultiplier is the minimum jitter multiplier
	JitterMinMultiplier = 0.5
	// JitterMaxMultiplier is the maximum jitter multiplier
	JitterMaxMultiplier = 1.0
	// JitterPercentage is the percentage of delay to use for jitter
	JitterPercentage = 0.5
	// FibonacciCap is the cap for fibonacci sequence to prevent overflow
	FibonacciCap = 1000
	// CommonErrorsLimit is the limit for common errors to keep
	CommonErrorsLimit = 10

	// SuccessDelayMultiplier is the multiplier for success delay
	SuccessDelayMultiplier = 0.5
	// SuccessMaxDelayMultiplier is the multiplier for success max delay
	SuccessMaxDelayMultiplier = 0.8
	// TimeoutAttemptsMultiplier is the multiplier for timeout attempts
	TimeoutAttemptsMultiplier = 1.5
	// CriticalDelayMultiplier is the multiplier for critical delay
	CriticalDelayMultiplier = 2.0
	// CriticalMaxDelayMultiplier is the multiplier for critical max delay
	CriticalMaxDelayMultiplier = 1.5
	// HighDelayMultiplier is the multiplier for high delay
	HighDelayMultiplier = 1.5
	// LowDelayMultiplier is the multiplier for low delay
	LowDelayMultiplier = 0.7
	// ConnectionRefusedAttempts is the number of attempts for connection refused errors
	ConnectionRefusedAttempts = 2
	// RandomDivisor is the divisor for random number generation
	RandomDivisor = 1000
	// FibonacciCapValue is the cap value for fibonacci sequence
	FibonacciCapValue = 1000
	// AverageLatencyDivisor is divisor for average latency calculation
	AverageLatencyDivisor = 2
)
View Source
const (
	// DefaultMaxAttempts is the default maximum number of retry attempts
	DefaultMaxAttempts = 3
	// DefaultMaxDelay is the default maximum delay between retries
	DefaultMaxDelay = 30 * time.Second
	// DefaultBackoff is the default exponential backoff multiplier
	DefaultBackoff = 2.0
	// PercentageMultiplier is used to convert ratio to percentage
	PercentageMultiplier = 100.0
)

Variables

View Source
var ErrMaxRetriesExceeded = errors.New("max retries exceeded")

ErrMaxRetriesExceeded is returned when max retries are exceeded

Functions

func IsRetryableError added in v1.25.4

func IsRetryableError(err error) bool

IsRetryableError checks if an error is retryable

func Retry added in v1.25.4

func Retry(ctx context.Context, config RetryConfig, fn func() error) error

Retry executes a function with retry logic

func RetryWithResult added in v1.25.4

func RetryWithResult[T any](ctx context.Context, config RetryConfig, fn func() (T, error)) (T, error)

RetryWithResult executes a function with retry logic and returns a result

Types

type ContextAnalyzer

type ContextAnalyzer struct {
	// contains filtered or unexported fields
}

ContextAnalyzer analyzes the context of operations

func NewContextAnalyzer

func NewContextAnalyzer() *ContextAnalyzer

NewContextAnalyzer creates a new context analyzer

func (*ContextAnalyzer) GetOperationContext

func (ca *ContextAnalyzer) GetOperationContext(operation string) *OperationContext

GetOperationContext returns context information for an operation

func (*ContextAnalyzer) RecordOperation

func (ca *ContextAnalyzer) RecordOperation(operation string, err error, duration time.Duration)

RecordOperation records an operation result

type ErrorClassification

type ErrorClassification struct {
	Type        ErrorType `json:"type"`
	IsRetryable bool      `json:"isRetryable"`
	Severity    string    `json:"severity"`
	Description string    `json:"description"`
}

ErrorClassification contains classification information for an error

type ErrorClassifier

type ErrorClassifier struct {
	// contains filtered or unexported fields
}

ErrorClassifier classifies different types of errors

func NewErrorClassifier

func NewErrorClassifier() *ErrorClassifier

NewErrorClassifier creates a new error classifier

func (*ErrorClassifier) ClassifyError

func (ec *ErrorClassifier) ClassifyError(err error) ErrorClassification

ClassifyError classifies an error and determines if it's retryable

type ErrorType

type ErrorType int

ErrorType represents the type of error

const (
	// ErrorTypeUnknown represents an unknown error type
	ErrorTypeUnknown ErrorType = iota
	// ErrorTypeNetwork represents network-related errors
	ErrorTypeNetwork
	// ErrorTypeRegistry represents registry-related errors
	ErrorTypeRegistry
	// ErrorTypeRateLimit represents rate limiting errors
	ErrorTypeRateLimit
	// ErrorTypeAuthentication represents authentication errors
	ErrorTypeAuthentication
	// ErrorTypeTimeout represents timeout errors
	ErrorTypeTimeout
	// ErrorTypeResourceExhaustion represents resource exhaustion errors
	ErrorTypeResourceExhaustion
	// ErrorTypeTemporary represents temporary errors
	ErrorTypeTemporary
	// ErrorTypePermanent represents permanent errors
	ErrorTypePermanent
)

type IntelligentRetry

type IntelligentRetry struct {
	// contains filtered or unexported fields
}

IntelligentRetry manages intelligent retry logic

func NewIntelligentRetry

func NewIntelligentRetry() *IntelligentRetry

NewIntelligentRetry creates a new intelligent retry instance

func (*IntelligentRetry) DetermineStrategy

func (ir *IntelligentRetry) DetermineStrategy(_ context.Context, operation string, err error) Strategy

DetermineStrategy determines the optimal retry strategy based on error type and context

func (*IntelligentRetry) GetNextDelay

func (ir *IntelligentRetry) GetNextDelay(ctx context.Context, attempt int, err error) time.Duration

GetNextDelay calculates the next delay for a retry attempt

func (*IntelligentRetry) GetOperationStats

func (ir *IntelligentRetry) GetOperationStats(operation string) *OperationContext

GetOperationStats returns statistics for an operation

func (*IntelligentRetry) RecordOperation

func (ir *IntelligentRetry) RecordOperation(_ context.Context, operation string, err error, duration time.Duration)

RecordOperation records the result of an operation for future analysis

func (*IntelligentRetry) ShouldRetry

func (ir *IntelligentRetry) ShouldRetry(ctx context.Context, attempt int, err error) bool

ShouldRetry determines if an operation should be retried

type OperationContext

type OperationContext struct {
	Operation      string        `json:"operation"`
	Registry       string        `json:"registry"`
	Platform       string        `json:"platform"`
	AttemptCount   int           `json:"attemptCount"`
	SuccessCount   int           `json:"successCount"`
	FailureCount   int           `json:"failureCount"`
	LastAttempt    time.Time     `json:"lastAttempt"`
	LastSuccess    time.Time     `json:"lastSuccess"`
	LastFailure    time.Time     `json:"lastFailure"`
	CommonErrors   []string      `json:"commonErrors"`
	AverageLatency time.Duration `json:"averageLatency"`
}

OperationContext contains context information about an operation

type RetryConfig added in v1.25.4

type RetryConfig struct {
	// MaxAttempts is the maximum number of retry attempts
	MaxAttempts int

	// InitialDelay is the initial delay before first retry
	InitialDelay time.Duration

	// MaxDelay is the maximum delay between retries
	MaxDelay time.Duration

	// Backoff is the exponential backoff multiplier
	Backoff float64

	// RetryableErrors is a function that determines if an error is retryable
	RetryableErrors func(error) bool
}

RetryConfig defines retry configuration

func DefaultRetryConfig added in v1.25.4

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns a default retry configuration

func (RetryConfig) String added in v1.25.4

func (c RetryConfig) String() string

String returns a string representation of the config

type RetryConfigBuilder added in v1.25.4

type RetryConfigBuilder struct {
	// contains filtered or unexported fields
}

RetryConfigBuilder helps build retry configurations

func NewRetryConfigBuilder added in v1.25.4

func NewRetryConfigBuilder() *RetryConfigBuilder

NewRetryConfigBuilder creates a new retry config builder

func (*RetryConfigBuilder) Build added in v1.25.4

func (b *RetryConfigBuilder) Build() RetryConfig

Build builds the retry configuration

func (*RetryConfigBuilder) WithBackoff added in v1.25.4

func (b *RetryConfigBuilder) WithBackoff(backoff float64) *RetryConfigBuilder

WithBackoff sets the backoff multiplier

func (*RetryConfigBuilder) WithInitialDelay added in v1.25.4

func (b *RetryConfigBuilder) WithInitialDelay(delay time.Duration) *RetryConfigBuilder

WithInitialDelay sets the initial delay

func (*RetryConfigBuilder) WithMaxAttempts added in v1.25.4

func (b *RetryConfigBuilder) WithMaxAttempts(attempts int) *RetryConfigBuilder

WithMaxAttempts sets the maximum number of attempts

func (*RetryConfigBuilder) WithMaxDelay added in v1.25.4

func (b *RetryConfigBuilder) WithMaxDelay(delay time.Duration) *RetryConfigBuilder

WithMaxDelay sets the maximum delay

func (*RetryConfigBuilder) WithRetryableErrors added in v1.25.4

func (b *RetryConfigBuilder) WithRetryableErrors(fn func(error) bool) *RetryConfigBuilder

WithRetryableErrors sets the retryable error function

type Strategy

type Strategy struct {
	BackoffAlgorithm string        `json:"backoffAlgorithm"`
	MaxAttempts      int           `json:"maxAttempts"`
	InitialDelay     time.Duration `json:"initialDelay"`
	MaxDelay         time.Duration `json:"maxDelay"`
	Jitter           bool          `json:"jitter"`
	ContextAware     bool          `json:"contextAware"`
	Adaptive         bool          `json:"adaptive"`
	BaseMultiplier   float64       `json:"baseMultiplier"`
}

Strategy defines retry behavior for different scenarios

type StrategySelector

type StrategySelector struct {
	// contains filtered or unexported fields
}

StrategySelector selects the optimal retry strategy

func NewStrategySelector

func NewStrategySelector() *StrategySelector

NewStrategySelector creates a new strategy selector

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL