Documentation
¶
Overview ¶
Package retry is an exploration use of Go 1.22's experimental range functions to provide a "retry loop". It was inspired by Xe Iaso's post I wish Go had a retry block.
This code is a proof-of-concept only; it's received only light testing and is not intended for production use. Because it uses an experimental Go feature you must set GOEXPERIMENT=rangefunc when building.
Index ¶
Constants ¶
const ( // DefaultRetries is the default value used for [Retry.Retries] // if no value is provided. DefaultRetries = 3 // DefaultBackoff is the default value used for [Retry.Backoff] // if not value is provided. DefaultBackoff = time.Second * 5 )
Variables ¶
var ErrRetriesExceeded = errors.New("retry count exceeded")
ErrRetriesExceeded is the error value returned if all attempted retries fail.
Functions ¶
This section is empty.
Types ¶
type Retry ¶
type Retry struct { // Retries is the number of times a failed request will be retried // before the request is considered failed. // // This must be a non-negative value. Retries int // Timeout is an optional time limit applied to each yielded context. // // This must be a non-negative value. Timeout time.Duration // Backoff is the initial cooldown delay applied between a failed // request and the next retry. // // This must be a non-negative value. Backoff time.Duration // contains filtered or unexported fields }
Retry controls the behavior of a retry loop.
A Retry object should not be reused.
func (*Retry) Err ¶
Err returns the error result from a retried operation.
It returns [nil] if any request succeeded, ErrRetriesExceeded if all retry attempts failed, or the context error if its done channel was signaled.
func (*Retry) Retry ¶
Retry returns a range function to retry a fallible request.
The returned iter.Seq2 should be used as the range in a for loop. Each iteration through the loop is passed a child context.Context of ctx and an associated cancel function. Cancel causes are recorded, and if the request fails (due to, e.g., the retries failing) then all cause errors are joined together and returned in Retry.Err.
A randomized exponential backoff is applied between any failed request and before attempting to retry the loop.
The caller should ensure that any blocking I/O is bound to the yielded context. Failure to do so can cause the loop to hang.