-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretry.go
More file actions
61 lines (53 loc) · 2.05 KB
/
Copy pathretry.go
File metadata and controls
61 lines (53 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Adapters and helpers to use the [go-kit.retry] package for the GitHub API.
package github
import (
"errors"
"net/http"
"time"
"github.com/Pix4D/go-kit/retry"
)
// Backoff implements [retry.BackoffFunc] for GitHub.
func Backoff(first bool, previous, limit time.Duration, err error) time.Duration {
// Optimization: Are we rate limited?
// This allows to immediately terminate the retry loop if it would take too
// long, instead of keeping retrying and discovering at the end that we are
// still rate limited.
if ghErr, ok := errors.AsType[GitHubError](err); ok {
if RateLimited(ghErr) {
// Calculate the delay based solely on the server clock. This is
// unaffected by the inevitable clock drift between server and client.
delay := ghErr.RateLimitReset.Sub(ghErr.Date)
// We observed in production both a zero and a negative delay from
// GitHub. This can be due to race conditions in the GitHub backend
// or to other causes. Since this is a retry mechanism, we want to
// be resilient, so we optimize only if we are 100% sure.
if delay > 0 {
return delay
}
}
}
// We are here for two different reasons:
// 1. we are not rate limited (normal case)
// 2. we are rate limited but the calculated delay is either zero or negative
// (see beginning of this function).
return retry.ExponentialBackoff(first, previous, limit, nil)
}
// RateLimited returns true if the http.Response in err reports being rate limited.
// See https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#exceeding-the-rate-limit
func RateLimited(err GitHubError) bool {
return err.StatusCode == http.StatusForbidden && err.RateLimitRemaining == 0
}
// TransientError returns true if the http.Response in err has a status code
// that can be retried.
func TransientError(statusCode int) bool {
switch statusCode {
case
http.StatusInternalServerError, // 500
http.StatusBadGateway, // 502
http.StatusServiceUnavailable, // 503
http.StatusGatewayTimeout: // 504
return true
default:
return false
}
}