27 lines
retry/retry.go
WithBackoff retries an operation with a fixed delay between attempts.
// Package retry provides a helper for retrying operations with configurable backoff.
package retry
 
import (
	"context"
	"time"
)
 
// WithBackoff calls fn up to maxAttempts times, pausing delay between each attempt.
// It returns nil as soon as fn returns nil.
// If ctx is cancelled during a backoff sleep, the helper must return ctx.Err()
// immediately without completing the sleep or making another attempt.
// Parameters: ctx — controls cancellation and deadline; fn — the operation to retry;
// maxAttempts — total number of calls including the first; delay — pause between retries.
func WithBackoff(ctx context.Context, maxAttempts int, delay time.Duration, fn func(context.Context) error) error {
	var err error
	for i := 0; i < maxAttempts; i++ {
		err = fn(ctx)
		if err == nil {
			return nil
		}
		if i < maxAttempts-1 {
			time.Sleep(delay)
		}
	}
	return err
}