Skip to content

Commit

Permalink
github/commitstatus: make negative sleep time impossible
Browse files Browse the repository at this point in the history
In the spirit of the book A Philosophy of Software Design by
John Ousterhout, section "Define errors out of existence".

Talk:
https://youtu.be/bmSAYlu0NcY?t=1313
  • Loading branch information
marco-m-pix4d committed Jul 25, 2023
1 parent 772e1be commit 58d1155
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 14 deletions.
19 changes: 7 additions & 12 deletions github/commitstatus.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,8 @@ func (s CommitStatus) Add(sha, state, targetURL, description string) error {
if err != nil {
return err
}
timeToSleep, reason, err := checkForRetry(response, s.target.WaitTime,
timeToSleep, reason := checkForRetry(response, s.target.WaitTime,
s.target.MaxSleepTime, s.target.Jitter)
if err != nil {
return fmt.Errorf("internal error: %s", err)
}
if timeToSleep == 0 {
break
}
Expand Down Expand Up @@ -262,7 +259,7 @@ func min(a, b int) int {
// 2. The HTTP status code is in a retryable subset of the 5xx status codes.
// In this case, it returns the same as the input parameter waitTime.
func checkForRetry(res httpResponse, waitTime, maxSleepTime, jitter time.Duration,
) (time.Duration, string, error) {
) (time.Duration, string) {
retryableStatusCodes := []int{
http.StatusInternalServerError, // 500
http.StatusBadGateway, // 502
Expand All @@ -287,23 +284,21 @@ func checkForRetry(res httpResponse, waitTime, maxSleepTime, jitter time.Duratio

switch {
case sleepTime == 0:
return 0, "", nil
return 0, ""
case sleepTime > maxSleepTime:
return 0, "", nil
return 0, ""
case sleepTime < maxSleepTime:
return sleepTime, "rate limited", nil
default:
return 0, "", fmt.Errorf("unexpected: negative sleep time: %s", sleepTime)
return sleepTime, "rate limited"
}
}

// Do we have a retryable HTTP status code ?
if slices.Contains(retryableStatusCodes, res.statusCode) {
return waitTime, http.StatusText(res.statusCode), nil
return waitTime, http.StatusText(res.statusCode)
}

// The status code could be 200 OK or any other error we did not process before.
// In any case, there is nothing to sleep, return 0 and let the caller take a
// decision.
return 0, "", nil
return 0, ""
}
3 changes: 1 addition & 2 deletions github/commitstatus_private_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@ func TestCheckForRetrySuccess(t *testing.T) {
}

run := func(t *testing.T, tc testCase) {
sleep, reason, err := checkForRetry(tc.res, tc.waitTime, maxSleepTime, tc.jitter)
sleep, reason := checkForRetry(tc.res, tc.waitTime, maxSleepTime, tc.jitter)

assert.NilError(t, err)
assert.Equal(t, sleep, tc.wantSleep)
assert.Equal(t, reason, tc.wantReason)
}
Expand Down

0 comments on commit 58d1155

Please sign in to comment.