| 106 | } |
| 107 | |
| 108 | func retryWithBackoffContext(ctx context.Context, fn func() error) error { |
| 109 | backoff := initialBackoff |
| 110 | var lastErr error |
| 111 | |
| 112 | for attempt := 0; attempt <= maxRetries; attempt++ { |
| 113 | if err := ctx.Err(); err != nil { |
| 114 | return err |
| 115 | } |
| 116 | lastErr = fn() |
| 117 | if lastErr == nil { |
| 118 | return nil |
| 119 | } |
| 120 | if errors.Is(lastErr, context.Canceled) || errors.Is(lastErr, context.DeadlineExceeded) { |
| 121 | return lastErr |
| 122 | } |
| 123 | if !isTransientError(lastErr) { |
| 124 | return lastErr |
| 125 | } |
| 126 | if attempt == maxRetries { |
| 127 | break |
| 128 | } |
| 129 | delay, isRateLimit := retryDelay(lastErr, backoff) |
| 130 | if err := retrySleep(ctx, delay); err != nil { |
| 131 | return err |
| 132 | } |
| 133 | if !isRateLimit { |
| 134 | backoff *= 2 |
| 135 | if backoff > maxBackoff { |
| 136 | backoff = maxBackoff |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | return lastErr |
| 142 | } |