retry

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package retry provides a faithful port of the npm p-retry / async-retry libraries: it retries a function with exponential backoff.

The sleep function is injectable via Options.Sleep so that tests can verify the backoff schedule without waiting on real time.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Do

func Do(fn func(attempt int) error, opts Options) error

Do calls fn, retrying with exponential backoff on error until it succeeds, the retry budget is exhausted, or an AbortError is returned.

fn receives the 1-based attempt number. The error returned by the final failed attempt is returned to the caller (unwrapped from AbortError).

Types

type AbortError

type AbortError struct {
	Err error
}

AbortError wraps an error to signal that retrying must stop immediately. The wrapped error is returned to the caller of Do.

func Abort

func Abort(err error) *AbortError

Abort creates an AbortError that stops retrying immediately when returned from the retried function.

func (*AbortError) Error

func (a *AbortError) Error() string

Error implements the error interface.

func (*AbortError) Unwrap

func (a *AbortError) Unwrap() error

Unwrap returns the wrapped error so errors.Is / errors.As work through it.

type Options

type Options struct {
	// Retries is the maximum number of retries after the first attempt. A
	// value of 0 means the function is attempted exactly once. This mirrors
	// the "retries" option of node-retry / p-retry.
	Retries int
	// Factor is the exponential backoff factor. Defaults to 2 when zero.
	Factor float64
	// MinTimeout is the delay before the first retry. Defaults to 1s when
	// zero.
	MinTimeout time.Duration
	// MaxTimeout caps the delay between retries. Defaults to no cap
	// (math.MaxInt64) when zero.
	MaxTimeout time.Duration
	// OnRetry, if set, is called before each retry with the error that caused
	// the retry and the attempt number that just failed (1-based).
	OnRetry func(err error, attempt int)
	// Sleep, if set, is used instead of time.Sleep. It makes the backoff
	// injectable for testing.
	Sleep func(d time.Duration)
}

Options configures Do.

func (Options) Backoff

func (o Options) Backoff(attempt int) time.Duration

Backoff computes the delay before the given retry attempt. attempt is 1-based, where attempt 1 is the delay before the first retry.

The formula is min(MaxTimeout, MinTimeout * Factor^(attempt-1)).

Jump to

Keyboard shortcuts

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