curb

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2025 License: MIT Imports: 5 Imported by: 0

README

🔁 curb

curb is a small, composable Go package that provides retry logic with exponential backoff and jitter. It's designed for simplicity, testability, and real-world use cases like retrying API calls or transient network operations.


✨ Features

  • Generic retry helper with Retry[T]
  • Exponential backoff with jitter
  • Configurable retry attempts (default: 5)
  • Clean and minimal API

📦 Installation

go get github.com/isaporiti/curb


Documentation

Overview

Package curb provides a generic retry mechanism with configurable backoff delays and jitter. It is useful for wrapping operations that may fail transiently, such as network or API calls.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidMaxAttempts is returned when an invalid max attempt count is configured.
	ErrInvalidMaxAttempts = errors.New("curb: max attempts should be between 1 and 10")
)

Functions

func Retry

func Retry[T any](ctx context.Context, fn func() (T, error), opts ...option) (T, error)

Retry retries the given function `fn` up to a configurable number of times, applying an exponential backoff with jitter between attempts. It stops early if the function succeeds or if the context is canceled. Returns the result of `fn`, or an error if all attempts fail or the context expires.

Example usage:

res, err := curb.Retry(ctx, func() (Result, error) {
    return someUnstableOperation()
}, curb.WithMaxAttempts(3))

func WithMaxAttempts

func WithMaxAttempts(m int) option

WithMaxAttempts sets the maximum number of retry attempts (must be between 1 and 10).

func WithSleeper

func WithSleeper(s func(time.Duration) <-chan time.Time) option

WithSleeper allows customization of the delay function used between retries.

This option is primarily useful for testing, where you may want to avoid actual time delays by injecting a mocked or fake sleeper function. The provided sleeper function should return a channel that signals when to resume execution.

Example usage:

fakeSleeper := func(d time.Duration) <-chan time.Time {
    ch := make(chan time.Time, 1)
    ch <- time.Now()
    return ch
}

curb.Retry(ctx, fn, curb.WithSleeper(fakeSleeper))

Types

type ErrRetriesExhausted

type ErrRetriesExhausted struct {
	// MaxAttempts indicates how many times the function was retried.
	MaxAttempts int
}

ErrRetriesExhausted is returned when all retry attempts are exhausted.

func (ErrRetriesExhausted) Error

func (e ErrRetriesExhausted) Error() string

Error implements the error interface for ErrRetriesExhausted.

Jump to

Keyboard shortcuts

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