Categorygithub.com/ssgreg/repeat
modulepackage
1.5.1
Repository: https://github.com/ssgreg/repeat.git
Documentation: pkg.go.dev

# README

Repeat

Alt text GoDoc Build Status Go Report Status GoCover

Go implementation of different backoff strategies useful for retrying operations and heartbeating.

Examples

Backoff

Let's imagine that we need to do a REST call on remote server but it could fail with a bunch of different issues. We can repeat failed operation using exponential backoff policies.

Exponential backoff is an algorithm that uses feedback to multiplicatively decrease the rate of some process, in order to gradually find an acceptable rate.

The example below tries to repeat operation 10 times using a full jitter backoff. See algorithm details here.

    // An example operation that do some useful stuff.
    // It fails five first times.
    var last time.Time
    op := func(c int) error {
        printInfo(c, &last)
        if c < 5 {
            return repeat.HintTemporary(errors.New("can't connect to a server"))
        }
        return nil
    }

    // Repeat op on any error, with 10 retries, with a backoff.
    err := repeat.Repeat(
        // Our op with additional call counter.
        repeat.FnWithCounter(op),
        // Force the repetition to stop in case the previous operation
        // returns nil.
        repeat.StopOnSuccess(),
        // 10 retries max.
        repeat.LimitMaxTries(10),
        // Specify a delay that uses a backoff.
        repeat.WithDelay(
            repeat.FullJitterBackoff(500*time.Millisecond).Set(),
        ),
    )

The example of output:

Attempt #0, Delay 0s
Attempt #1, Delay 373.617912ms
Attempt #2, Delay 668.004225ms
Attempt #3, Delay 1.220076558s
Attempt #4, Delay 2.716156336s
Attempt #5, Delay 6.458431017s
Repetition process is finished with: <nil>

Backoff with timeout

The example below is almost the same as the previous one. It adds one important feature - possibility to cancel operation repetition using context's timeout.

    // A context with cancel.
    // Repetition will be cancelled in 3 seconds.
    ctx, cancelFunc := context.WithCancel(context.Background())
    go func() {
        time.Sleep(3 * time.Second)
        cancelFunc()
    }()

    // Repeat op on any error, with 10 retries, with a backoff.
    err := repeat.Repeat(
        ...
        // Specify a delay that uses a backoff.
        repeat.WithDelay(
            repeat.FullJitterBackoff(500*time.Millisecond).Set(),
            repeat.SetContext(ctx),
        ),
        ...
    )

The example of output:

Attempt #0, Delay 0s
Attempt #1, Delay 358.728046ms
Attempt #2, Delay 845.361787ms
Attempt #3, Delay 61.527485ms
Repetition process is finished with: context canceled

Heartbeating

Let's imagine we need to periodically report execution progress to remote server. The example below repeats the operation each second until it will be cancelled using passed context.

    // An example operation that do heartbeat.
    var last time.Time
    op := func(c int) error {
        printInfo(c, &last)
        return nil
    }

    // A context with cancel.
    // Repetition will be cancelled in 7 seconds.
    ctx, cancelFunc := context.WithCancel(context.Background())
    go func() {
        time.Sleep(7 * time.Second)
        cancelFunc()
    }()

    err := repeat.Repeat(
        // Heartbeating op.
        repeat.FnWithCounter(op),
        // Delay with fixed backoff and context.
        repeat.WithDelay(
            repeat.FixedBackoff(time.Second).Set(),
            repeat.SetContext(ctx),
        ),
    )

The example of output:

Attempt #0, Delay 0s
Attempt #1, Delay 1.001129426s
Attempt #2, Delay 1.000155727s
Attempt #3, Delay 1.001131014s
Attempt #4, Delay 1.000500428s
Attempt #5, Delay 1.0008985s
Attempt #6, Delay 1.000417057s
Repetition process is finished with: context canceled

Heartbeating with error timeout

The example below is almost the same as the previous one but it will be cancelled using special error timeout. This timeout resets each time the operations return nil.

    // An example operation that do heartbeat.
    // It fails 5 times after 3 successfull tries.
    var last time.Time
    op := func(c int) error {
        printInfo(c, &last)
        if c > 3 && c < 8 {
            return repeat.HintTemporary(errors.New("can't connect to a server"))
        }
        return nil
    }

    err := repeat.Repeat(
        // Heartbeating op.
        repeat.FnWithCounter(op),
        // Delay with fixed backoff and error timeout.
        repeat.WithDelay(
            repeat.FixedBackoff(time.Second).Set(),
            repeat.SetErrorsTimeout(3*time.Second),
        ),
    )

The example of output:

Attempt #0, Delay 0s
Attempt #1, Delay 1.001634616s
Attempt #2, Delay 1.004912408s
Attempt #3, Delay 1.001021358s
Attempt #4, Delay 1.001249459s
Attempt #5, Delay 1.004320833s
Repetition process is finished with: can't connect to a server

# Packages

No description provided by the author

# Functions

Cause extracts the cause error from TemporaryError and StopError or return the passed one.
Compose composes all passed operations into a single one.
Cpp returns object that calls C (constructor) at first, then ops, then D (destructor).
Done does nothing, returns nil.
ExponentialBackoff create a builder for Delay's option.
ExponentialBackoffAlgorithm implements classic caped exponential backoff.
FixedBackoff create a builder for Delay's option.
FixedBackoffAlgorithm implements backoff with a fixed delay.
Fn wraps operation with no arguments.
FnDone returns nil even if wrapped op returns an error.
FnES wraps operation with no return value.
FnHintStop hints all operation errors as StopError.
FnHintTemporary hints all operation errors as temporary.
FnNope does not call pass op, returns input error.
FnOnError executes operation in case error is NOT nil.
FnOnlyOnce executes op only once permanently.
FnOnSuccess executes operation in case of error is nil.
FnPanic panics if op returns any error other than nil, TemporaryError and StopError.
FnRepeat is a Repeat operation.
FnS wraps operation with no arguments and return value.
FnWithCounter wraps operation with counter only.
FnWithErrorAndCounter wraps operation and adds call counter.
Forward returns the passed operation.
FullJitterBackoff create a builder for Delay's option.
FullJitterBackoffAlgorithm implements caped exponential backoff with jitter.
HintStop makes a StopError.
HintTemporary makes a TemporaryError.
IsStop checks if passed error is StopError.
IsTemporary checks if passed error is TemporaryError.
LimitMaxTries returns true if attempt number is less then max.
NewRepeater sets up everything to be able to repeat operations.
NewRepeaterExt returns object that wraps all ops with with the given opw and wraps composed operation with the given copw.
Nope does nothing, returns input error.
Once composes the operations and executes the result once.
Repeat repeat operations until one of them stops the repetition.
SetContext allows to set a context instead of default one.
SetContextHintStop instructs to use HintStop(nil) instead of context error in case of context expiration.
SetErrorsTimeout specifies the maximum timeout for repetition in case of error.
StopOnSuccess returns true in case of error is nil.
With returns object that calls C (constructor) at first, then ops, then D (destructor).
WithContext repeat operations until one of them stops the repetition or context will be canceled.
WithDelay constructs HeartbeatPredicate.
Wrap returns object that wraps all repeating ops with passed OpWrapper.
WrapOnce returns object that wraps all repeating ops combined into a single op with passed OpWrapper calling it once.
WrStopOnContextError stops an operation in case of context error.
WrWith returns wrapper that calls C (constructor) at first, then ops, then D (destructor).

# Structs

DelayOptions holds parameters for a heartbeat process.
ExponentialBackoffBuilder is an option builder.
FixedBackoffBuilder is an option builder.
FullJitterBackoffBuilder is an option builder.
StopError allows to stop repetition process without specifying a separate error.
TemporaryError allows not to stop repetitions process right now.

# Interfaces

Repeater represents general package concept.

# Type aliases

Operation is the type of function for repetition.
OpWrapper is the type of function for repetition.