@@ -24,6 +24,7 @@ import (
2424 "net/http"
2525 "os"
2626 "strconv"
27+ "strings"
2728 "time"
2829
2930 "github.com/google/go-github/v84/github"
@@ -91,31 +92,22 @@ func (t *rateLimitTransport) RoundTrip(req *http.Request) (*http.Response, error
9192 if resp == nil {
9293 return resp , nil
9394 }
94- retryable := resp .StatusCode == http .StatusForbidden ||
95- resp .StatusCode == http .StatusTooManyRequests ||
96- resp .StatusCode == http .StatusInternalServerError
97- if ! retryable {
95+
96+ kind := classifyResponse (resp )
97+ if kind == kindNone {
9898 return resp , nil
9999 }
100-
101- delay := retryDelay (resp , attempt )
102- retryHint := retryDelayHint (resp , attempt )
103100 if attempt >= maxRateLimitRetryAttempts {
101+ log .Printf ("GitHub API still failing after %d retries (status=%d); giving up" , attempt , resp .StatusCode )
104102 return resp , nil
105103 }
106104 if ! canRetryBody {
107105 return resp , nil
108106 }
109107
110- if resp .StatusCode == http .StatusInternalServerError {
111- log .Printf ("GitHub API server error (500), waiting %s before retry" , delay .Round (time .Second ))
112- } else {
113- if requestedWait , requestedFrom , ok := requestedRateLimitWait (resp ); ok {
114- log .Printf ("GitHub API rate limited (%d), waiting %s before retry (%s). GitHub asked to wait %s (%s)" , resp .StatusCode , delay .Round (time .Second ), retryHint , requestedWait .Round (time .Second ), requestedFrom )
115- } else {
116- log .Printf ("GitHub API rate limited (%d), waiting %s before retry (%s)" , resp .StatusCode , delay .Round (time .Second ), retryHint )
117- }
118- }
108+ delay , source := retryDelay (resp , kind , attempt )
109+ logRetry (resp , kind , delay , source )
110+
119111 _ , _ = io .Copy (io .Discard , resp .Body )
120112 _ = resp .Body .Close ()
121113
@@ -131,72 +123,106 @@ func (t *rateLimitTransport) RoundTrip(req *http.Request) (*http.Response, error
131123 }
132124}
133125
134- func retryDelay (resp * http.Response , attempt int ) time.Duration {
135- // For server errors, use a short exponential backoff (5s, 10s, 20s, …)
136- if resp .StatusCode == http .StatusInternalServerError {
137- backoff := min (time .Duration (float64 (defaultServerErrorDelay )* math .Pow (2 , float64 (attempt ))), maxSecondaryRetryDelay )
138- return max (backoff , time .Second )
139- }
140- delay , _ := rateLimitRetryDelay (resp , attempt )
141- return delay
142- }
126+ type responseKind int
143127
144- func retryDelayHint (resp * http.Response , secondaryAttempt int ) string {
145- if resp .StatusCode == http .StatusInternalServerError {
146- return "exponential backoff after 500 response"
128+ const (
129+ kindNone responseKind = iota
130+ kindPrimaryRateLimit
131+ kindSecondaryRateLimit
132+ kindServerError
133+ )
134+
135+ // classifyResponse decides whether a response is retryable per
136+ // https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api.
137+ //
138+ // A 403/429 is only treated as a rate limit when GitHub provides a Retry-After
139+ // header or X-RateLimit-Remaining=0. Bare 403s are permission errors and
140+ // retrying them is wasteful.
141+ func classifyResponse (resp * http.Response ) responseKind {
142+ switch resp .StatusCode {
143+ case http .StatusForbidden , http .StatusTooManyRequests :
144+ hasRetryAfter := resp .Header .Get ("Retry-After" ) != ""
145+ exhausted := resp .Header .Get ("X-RateLimit-Remaining" ) == "0"
146+ switch {
147+ case exhausted :
148+ return kindPrimaryRateLimit
149+ case hasRetryAfter :
150+ return kindSecondaryRateLimit
151+ default :
152+ return kindNone
153+ }
154+ case http .StatusInternalServerError ,
155+ http .StatusBadGateway ,
156+ http .StatusServiceUnavailable ,
157+ http .StatusGatewayTimeout :
158+ return kindServerError
159+ default :
160+ return kindNone
147161 }
148- _ , hint := rateLimitRetryDelay (resp , secondaryAttempt )
149- return hint
150162}
151163
152- func rateLimitRetryDelay (resp * http.Response , secondaryAttempt int ) (time.Duration , string ) {
153- retryAfter := parseRetryAfter (resp .Header .Get ("Retry-After" ))
154- if retryAfter > 0 {
155- return retryAfter , "from Retry-After header"
164+ func retryDelay (resp * http.Response , kind responseKind , attempt int ) (time.Duration , string ) {
165+ if d := parseRetryAfter (resp .Header .Get ("Retry-After" )); d > 0 {
166+ return d , "Retry-After header"
156167 }
157168
158- remaining := resp . Header . Get ( "X-RateLimit-Remaining" )
159- if remaining == "0" {
169+ switch kind {
170+ case kindPrimaryRateLimit :
160171 if reset := parseUnixTime (resp .Header .Get ("X-RateLimit-Reset" )); ! reset .IsZero () {
161- return max (time .Until (reset )+ time .Second , time .Second ), "from X-RateLimit-Reset header"
172+ return max (time .Until (reset )+ time .Second , time .Second ), "X-RateLimit-Reset header"
162173 }
174+ return secondaryBackoff (attempt ), "rate-limit backoff (no reset header)"
175+ case kindSecondaryRateLimit :
176+ return secondaryBackoff (attempt ), "secondary rate-limit backoff"
177+ case kindServerError :
178+ return serverErrorBackoff (attempt ), "exponential backoff after server error"
163179 }
180+ return time .Second , ""
181+ }
164182
165- // Secondary limit guidance from GitHub docs: wait at least 1 minute and increase with backoff.
166- backoff := max (min (time .Duration (float64 (defaultSecondaryRetryDelay )* math .Pow (2 , float64 (secondaryAttempt ))), maxSecondaryRetryDelay ), time .Second )
167- return backoff , "using secondary rate-limit backoff"
183+ // secondaryBackoff implements the GitHub-recommended "at least 1 minute,
184+ // increase exponentially" backoff for secondary rate limits.
185+ func secondaryBackoff (attempt int ) time.Duration {
186+ d := time .Duration (float64 (defaultSecondaryRetryDelay ) * math .Pow (2 , float64 (attempt )))
187+ return max (min (d , maxSecondaryRetryDelay ), defaultSecondaryRetryDelay )
168188}
169189
170- func requestedRateLimitWait (resp * http.Response ) (time.Duration , string , bool ) {
171- retryAfter := parseRetryAfter (resp .Header .Get ("Retry-After" ))
172- if retryAfter > 0 {
173- return retryAfter , "Retry-After header" , true
174- }
190+ func serverErrorBackoff (attempt int ) time.Duration {
191+ d := time .Duration (float64 (defaultServerErrorDelay ) * math .Pow (2 , float64 (attempt )))
192+ return max (min (d , maxSecondaryRetryDelay ), time .Second )
193+ }
175194
176- remaining := resp .Header .Get ("X-RateLimit-Remaining" )
177- if remaining == "0" {
178- if reset := parseUnixTime (resp .Header .Get ("X-RateLimit-Reset" )); ! reset .IsZero () {
179- return max (time .Until (reset ), time .Second ), "X-RateLimit-Reset header" , true
180- }
195+ func logRetry (resp * http.Response , kind responseKind , delay time.Duration , source string ) {
196+ rounded := delay .Round (time .Second )
197+ resource := resp .Header .Get ("X-RateLimit-Resource" )
198+ suffix := ""
199+ if resource != "" {
200+ suffix = " resource=" + resource
181201 }
182202
183- return 0 , "" , false
203+ switch kind {
204+ case kindPrimaryRateLimit :
205+ log .Printf ("GitHub API primary rate limit hit (%d%s); waiting %s before retry (%s)" , resp .StatusCode , suffix , rounded , source )
206+ case kindSecondaryRateLimit :
207+ log .Printf ("GitHub API secondary rate limit hit (%d%s); waiting %s before retry (%s)" , resp .StatusCode , suffix , rounded , source )
208+ case kindServerError :
209+ log .Printf ("GitHub API server error (%d); waiting %s before retry (%s)" , resp .StatusCode , rounded , source )
210+ }
184211}
185212
186213func parseRetryAfter (value string ) time.Duration {
214+ value = strings .TrimSpace (value )
187215 if value == "" {
188216 return 0
189217 }
190- seconds , err := strconv .Atoi (value )
191- if err == nil {
218+ if seconds , err := strconv .Atoi (value ); err == nil {
192219 if seconds < 1 {
193220 seconds = 1
194221 }
195222 return time .Duration (seconds ) * time .Second
196223 }
197224 if ts , err := http .ParseTime (value ); err == nil {
198- d := max (time .Until (ts ), time .Second )
199- return d
225+ return max (time .Until (ts ), time .Second )
200226 }
201227 return 0
202228}
0 commit comments