repeat

package
v0.0.0-...-91bf12d Latest Latest
Warning

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

Go to latest
Published: May 5, 2025 License: MIT Imports: 8 Imported by: 0

README ΒΆ

Repeat

The repeat package provides powerful and flexible retry logic for operations that may intermittently fail. It supports exponential backoff, jitter, advanced retry policies, and integration with contexts for cancellation.


Features

  • πŸ” Automatic retries with context awareness
  • πŸ“ˆ Optional exponential backoff with jitter
  • 🧠 Customizable error filters and retry policies
  • βŒ› Safe retry limits by count or duration
  • πŸ•ΈοΈ Plug-and-play HTTP and WebSocket examples

Installation

go get github.com/yourusername/repeat

Quick Start

Basic Retry Logic
err := repeat.Exec(ctx, func(ctx context.Context, attempt int) error {
	return trySomething() // return nil on success
})

Functional Options
  • Customize behavior with options:
err := repeat.Exec(
	ctx,
	myOperation,
	repeat.WithMaxAttempts(5),
	repeat.WithMinWait(500*time.Millisecond),
	repeat.WithExponentialBackoff(300*time.Millisecond, 5*time.Second),
	repeat.WithJitter(repeat.FullJitter),
)

Full Example: HTTP Retry Client
client := repeat.NewClient(nil, repeat.WithMaxAttempts(3))

req, _ := http.NewRequest("GET", "https://api.example.com", nil)
resp, err := client.Do(req)
  • Automatically retries failed 5xx responses using exponential backoff and jitter.

Full Example: WebSocket Retry Dialer
conn, err := repeat.ConnectWithRetry(ctx, func(ctx context.Context) (*websocket.Conn, error) {
	return websocket.DefaultDialer.DialContext(ctx, "wss://echo.websocket.org", nil)
})

Advanced Retry Policies
  • Use custom retry logic:
repeat.WithRetryPolicy(func(retryCount int, err error) bool {
	return retryCount < 5 && errors.Is(err, io.ErrUnexpectedEOF)
})
  • Or basic filters:
repeat.WithErrorFilter(func(err error) bool {
	return strings.Contains(err.Error(), "timeout")
})

Jitter Utilities

Full Jitter
repeat.WithJitter(repeat.FullJitter) // Randomizes full delay window
  • Define your own jitter logic:
repeat.WithJitter(func(d time.Duration) time.Duration {
	return time.Duration(float64(d) * 0.5) // 50% jitter
})

Constants
Name Value Description
DefaultMinWait 1s Minimum delay between attempts
DefaultMaxWait 1m Maximum allowed delay
DefaultBackoff 500ms Default base for exponential backoff
MaxBackoff 30s Max backoff cap
DefaultMaxRetries -1(infinite) Retry forever (with duration cap)
MaxTotalDuration 24h Safety guard for infinite retry

Errors
  • If MaxAttempts is reached: returns the last error wrapped with retry context.
  • If context is cancelled: returns context.Canceled or context.DeadlineExceeded.
  • Retry policies can short-circuit retries before limits are hit.

πŸ“ License


πŸ™Œ Contributions

  • PRs and suggestions welcome! Feel free to fork, open issues, or create a pull request πŸš€

  • Let me know if you want badges, a table of contents, or markdown export to file!

Documentation ΒΆ

Overview ΒΆ

Package repeat provides configurable retry logic with support for exponential backoff, jitter, and custom retry policies.

Index ΒΆ

Constants ΒΆ

View Source
const (
	DefaultMinWait    = time.Second
	DefaultMaxWait    = time.Minute
	DefaultMaxRetries = -1
	DefaultBackoff    = 500 * time.Millisecond
	MaxBackoff        = 30 * time.Second
	MaxTotalDuration  = 24 * time.Hour
)

Default configuration constants.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func ConnectWithRetry ΒΆ

func ConnectWithRetry(ctx context.Context, dial DialFunc, opts ...OptionSetter) (*websocket.Conn, error)

func Exec ΒΆ

func Exec(ctx context.Context, op Operation, opts ...OptionSetter) error

Exec executes operation with retry logic. ctx: Context for cancellation op: Operation to execute opts: Configuration options Returns: nil on success or wrapped error after exhausting retries

func FullJitter ΒΆ

func FullJitter(d time.Duration) time.Duration

FullJitter applies random delay up to specified duration.

Types ΒΆ

type ClientWithRetry ΒΆ

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

func NewClient ΒΆ

func NewClient(baseClient *http.Client, opts ...OptionSetter) *ClientWithRetry

func (*ClientWithRetry) Do ΒΆ

func (c *ClientWithRetry) Do(req *http.Request) (*http.Response, error)

type Config ΒΆ

type Config struct {
	MinTimeWait  time.Duration                        // Minimum delay between attempts
	MaxTimeWait  time.Duration                        // Maximum delay cap
	MaxRetries   int                                  // Maximum attempts (-1 = infinite)
	BackoffBase  time.Duration                        // Base duration for exponential backoff
	BackoffMax   time.Duration                        // Maximum backoff duration
	UseBackoff   bool                                 // Enable exponential backoff
	ErrorHandler func(err error) bool                 // Basic error filter
	JitterFunc   func(d time.Duration) time.Duration  // Delay randomizer
	ShouldRetry  func(retryCount int, err error) bool // Advanced retry policy
}

Config holds retry configuration parameters.

type DialFunc ΒΆ

type DialFunc func(ctx context.Context) (*websocket.Conn, error)

type Operation ΒΆ

type Operation func(ctx context.Context, retryCount int) error

Operation defines a function signature for operations to retry. ctx: Context for cancellation and deadlines retryCount: Current attempt number (0-indexed) Returns: error if operation failed, nil on success

type OptionSetter ΒΆ

type OptionSetter func(*Config)

OptionSetter modifies Config through functional options.

func WithErrorFilter ΒΆ

func WithErrorFilter(fn func(error) bool) OptionSetter

WithErrorFilter sets basic error evaluation callback.

func WithExponentialBackoff ΒΆ

func WithExponentialBackoff(base, max time.Duration) OptionSetter

WithExponentialBackoff enables backoff with base/max durations.

func WithJitter ΒΆ

func WithJitter(fn func(time.Duration) time.Duration) OptionSetter

WithJitter adds delay randomization function.

func WithMaxAttempts ΒΆ

func WithMaxAttempts(n int) OptionSetter

WithMaxAttempts limits number of retries (-1 for unlimited).

func WithMaxWait ΒΆ

func WithMaxWait(d time.Duration) OptionSetter

WithMaxWait sets maximum delay cap.

func WithMinWait ΒΆ

func WithMinWait(d time.Duration) OptionSetter

WithMinWait sets minimum delay between attempts.

func WithRetryPolicy ΒΆ

func WithRetryPolicy(fn func(int, error) bool) OptionSetter

WithRetryPolicy sets advanced retry decision function.

type TemporaryError ΒΆ

type TemporaryError struct {
	StatusCode int
}

TemporaryError represents a temporary error response.

func (*TemporaryError) Error ΒΆ

func (e *TemporaryError) Error() string

Error implements the error interface.

func (*TemporaryError) Temporary ΒΆ

func (e *TemporaryError) Temporary() bool

Temporary returns true if the error is temporary.

Jump to

Keyboard shortcuts

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