{"modulePath":"github.com/codeGROOVE-dev/retry","version":"v1.3.1","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package retry\n\nPackage retry provides a simple and flexible retry mechanism for Go. It allows executing functions with automatic retry on failure, with configurable backoff strategies, retry conditions, and error handling.\n\nThe package is safe for concurrent use.\n\nThe package is inspired by Try::Tiny::Retry from Perl.\n\nBasic usage:\n\n\turl := \"http://example.com\"\n\tvar body []byte\n\n\terr := retry.Do(\n\t\tfunc() error {\n\t\t\tresp, err := http.Get(url)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tbody, err = io.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t)\n\nWith data return:\n\n\tbody, err := retry.DoWithData(\n\t\tfunc() ([]byte, error) {\n\t\t\tresp, err := http.Get(url)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\treturn io.ReadAll(resp.Body)\n\t\t},\n\t)\n\n## Functions\n\n```go\nfunc BackOffDelay(attempt uint, _ error, config *Config) time.Duration\n```\nBackOffDelay implements exponential backoff delay strategy. Each retry attempt doubles the delay, up to a maximum.\n\n```go\nfunc Do(retryableFunc RetryableFunc, opts ...Option) error\n```\nDo executes the retryable function with the provided options. It returns nil if the function succeeds, or an error if all retry attempts fail.\n\nBy default, it will retry up to 10 times with exponential backoff and jitter. The behavior can be customized using Option functions.\n\n```go\nfunc DoWithData[T any](retryableFunc RetryableFuncWithData[T], opts ...Option) (T, error)\n```\nDoWithData executes the retryable function with the provided options and returns the function's data. It returns the data and nil error if the function succeeds, or zero value and error if all retry attempts fail.\n\nBy default, it will retry up to 10 times with exponential backoff and jitter. The behavior can be customized using Option functions.\n\n```go\nfunc FixedDelay(_ uint, _ error, config *Config) time.Duration\n```\nFixedDelay implements a constant delay strategy. The delay is always config.delay regardless of attempt number.\n\n```go\nfunc FullJitterBackoffDelay(attempt uint, _ error, config *Config) time.Duration\n```\nFullJitterBackoffDelay implements exponential backoff with full jitter. It returns a random delay between 0 and min(maxDelay, baseDelay \\* 2^attempt).\n\n```go\nfunc IsRecoverable(err error) bool\n```\nIsRecoverable reports whether err is recoverable. It returns false if err is or wraps an unrecoverable error.\n\n```go\nfunc RandomDelay(_ uint, _ error, config *Config) time.Duration\n```\nRandomDelay implements a random delay strategy. Returns a random duration between 0 and config.maxJitter.\n\n```go\nfunc Unrecoverable(err error) error\n```\nUnrecoverable wraps an error to mark it as unrecoverable. When an unrecoverable error is returned, the retry mechanism will stop immediately.\n\n## Types\n\n```go\ntype Config struct {\n\t// contains filtered or unexported fields\n}\n```\nConfig holds all configuration options for retry behavior. It is typically populated using Option functions and should not be constructed directly. Use the various Option functions like Attempts, Delay, and RetryIf to configure retry behavior.\n\n```go\ntype DelayTypeFunc func(attempt uint, err error, config *Config) time.Duration\n```\nDelayTypeFunc calculates the delay duration before the next retry attempt. The attempt parameter is the zero-based index of the attempt.\n\n```go\nfunc CombineDelay(delays ...DelayTypeFunc) DelayTypeFunc\n```\nCombineDelay creates a DelayTypeFunc that sums the delays from multiple strategies. The total delay is capped at math.MaxInt64 to prevent overflow.\n\n```go\ntype Error []error\n```\nError represents a collection of errors that occurred during retry attempts. It implements the error interface and provides compatibility with errors.Is, errors.As, and errors.Unwrap.\n\n```go\nfunc (e Error) As(target any) bool\n```\nAs finds the first error in e that matches target, and if so, sets target to that error value and returns true. It implements support for errors.As.\n\n```go\nfunc (e Error) Error() string\n```\nError returns a string representation of all errors that occurred during retry attempts. Each error is prefixed with its attempt number.\n\n```go\nfunc (e Error) Is(target error) bool\n```\nIs reports whether any error in e matches target. It implements support for errors.Is.\n\n```go\nfunc (e Error) Unwrap() error\n```\nUnwrap returns the last error for compatibility with errors.Unwrap. When you need to unwrap all errors, you should use WrappedErrors instead.\n\nExample:\n\n\terr := Do(\n\t\tfunc() error {\n\t\t\treturn errors.New(\"original error\")\n\t\t},\n\t\tAttempts(1),\n\t)\n\tfmt.Println(errors.Unwrap(err)) // \"original error\" is printed\n\n```go\nfunc (e Error) WrappedErrors() []error\n```\nWrappedErrors returns the list of errors that this Error is wrapping. It is an implementation of the \\`errwrap.Wrapper\\` interface in package \\[errwrap]([https://github.com/hashicorp/errwrap](https://github.com/hashicorp/errwrap)) so that \\`retry.Error\\` can be used with that library.\n\n```go\ntype IfFunc func(error) bool\n```\nIfFunc is the signature for functions that determine whether to retry after an error. It returns true if the error is retryable, false otherwise.\n\n```go\ntype OnRetryFunc func(attempt uint, err error)\n```\nOnRetryFunc is the signature for functions called after each retry attempt. The attempt parameter is the zero-based index of the attempt.\n\n```go\ntype Option func(*Config)\n```\nOption configures retry behavior. Options are applied in the order provided to Do or DoWithData. Later options override earlier ones if they modify the same configuration field.\n\n```go\nfunc Attempts(attempts uint) Option\n```\nAttempts sets the maximum number of retry attempts. Setting to 0 enables infinite retries. Default is 10.\n\n```go\nfunc AttemptsForError(attempts uint, err error) Option\n```\nAttemptsForError sets a specific number of retry attempts for a particular error. These attempts are counted against the total retry limit. The retry stops when either the specific error limit or total limit is reached. Note: errors are compared using errors.Is for matching.\n\n```go\nfunc Context(ctx context.Context) Option\n```\nContext sets the context for retry operations. The retry loop will stop if the context is cancelled or times out. Default is context.Background().\n\nExample with timeout:\n\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cancel()\n\n\tretry.Do(\n\t\tfunc() error {\n\t\t\treturn doSomething()\n\t\t},\n\t\tretry.Context(ctx),\n\t)\n\n```go\nfunc Delay(delay time.Duration) Option\n```\nDelay sets the base delay duration between retry attempts. Default is 100ms. The actual delay may be modified by the DelayType function.\n\n```go\nfunc DelayType(delayType DelayTypeFunc) Option\n```\nDelayType sets the delay calculation function between retries. Default is CombineDelay(BackOffDelay, RandomDelay).\n\n```go\nfunc LastErrorOnly(lastErrorOnly bool) Option\n```\nLastErrorOnly configures whether to return only the last error that occurred, or wrap all errors together. Default is false (return all errors).\n\n```go\nfunc MaxDelay(maxDelay time.Duration) Option\n```\nMaxDelay sets the maximum delay duration between retry attempts. This caps the delay calculated by DelayType functions. By default, there is no maximum (0 means no limit).\n\n```go\nfunc MaxJitter(maxJitter time.Duration) Option\n```\nMaxJitter sets the maximum random jitter duration for RandomDelay. Default is 100ms.\n\n```go\nfunc OnRetry(onRetry OnRetryFunc) Option\n```\nOnRetry sets a callback function that is called after each failed attempt. This is useful for logging or other side effects.\n\nExample:\n\n\tretry.Do(\n\t\tfunc() error {\n\t\t\treturn errors.New(\"some error\")\n\t\t},\n\t\tretry.OnRetry(func(attempt uint, err error) {\n\t\t\tlog.Printf(\"#%d: %s\\n\", attempt, err)\n\t\t}),\n\t)\n\n```go\nfunc RetryIf(retryIf IfFunc) Option\n```\nRetryIf controls whether a retry should be attempted after an error (assuming there are any retry attempts remaining)\n\nskip retry if special error example:\n\n\tretry.Do(\n\t\tfunc() error {\n\t\t\treturn errors.New(\"special error\")\n\t\t},\n\t\tretry.RetryIf(func(err error) bool {\n\t\t\tif err.Error() == \"special error\" {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t)\n\nBy default RetryIf stops execution if the error is wrapped using \\`retry.Unrecoverable\\`, so above example may also be shortened to:\n\n\tretry.Do(\n\t\tfunc() error {\n\t\t\treturn retry.Unrecoverable(errors.New(\"special error\"))\n\t\t}\n\t)\n\n```go\nfunc UntilSucceeded() Option\n```\nUntilSucceeded configures infinite retry attempts until success. Equivalent to Attempts(0).\n\n```go\nfunc WithTimer(t Timer) Option\n```\nWithTimer provides a way to swap out timer implementations. This is primarily useful for testing.\n\nExample:\n\n\ttype mockTimer struct{}\n\n\tfunc (mockTimer) After(d time.Duration) \u003c-chan time.Time {\n\t\treturn time.After(0) // immediate return for tests\n\t}\n\n\tretry.Do(\n\t\tfunc() error { ... },\n\t\tretry.WithTimer(mockTimer{}),\n\t)\n\n```go\nfunc WrapContextErrorWithLastError(wrap bool) Option\n```\nWrapContextErrorWithLastError configures whether to wrap context errors with the last function error. This is useful when using infinite retries (Attempts(0)) with context cancellation, as it preserves information about what error was occurring when the context expired. Default is false.\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tretry.Do(\n\t\tfunc() error {\n\t\t\t...\n\t\t},\n\t\tretry.Context(ctx),\n\t\tretry.Attempts(0),\n\t\tretry.WrapContextErrorWithLastError(true),\n\t)\n\n```go\ntype RetryIfFunc = IfFunc //nolint:revive // Keeping RetryIfFunc name for backwards compatibility\n\n```\nRetryIfFunc is an alias for IfFunc for backwards compatibility. Deprecated: Use IfFunc instead.\n\n```go\ntype RetryableFunc func() error\n```\nRetryableFunc is the function signature for retryable functions used with Do.\n\n```go\ntype RetryableFuncWithData[T any] func() (T, error)\n```\nRetryableFuncWithData is the function signature for retryable functions that return data. Used with DoWithData.\n\n```go\ntype Timer interface {\n\t// After returns a channel that sends the current time after the duration elapses.\n\t// It should behave like time.After.\n\tAfter(time.Duration) \u003c-chan time.Time\n}\n```\nTimer provides an interface for time operations in retry logic. This abstraction allows for mocking time in tests and implementing custom timing behaviors. The standard implementation uses time.After.\n\nSecurity note: Custom Timer implementations must return a valid channel that either receives a time value or blocks. Returning nil will cause the retry to fail immediately.\n\n","path":"github.com/codeGROOVE-dev/retry","name":"retry","synopsis":"Package retry provides a simple and flexible retry mechanism for Go.","isRedistributable":true}
