Skip to content

Commit

Permalink
Merge pull request #143 from imjaroiswebdev/support-ratelimit-reset
Browse files Browse the repository at this point in the history
[CSGI-2170 ] Add support for handling API REST rate limiting headers
  • Loading branch information
imjaroiswebdev authored Dec 1, 2023
2 parents a11b2f7 + df68b20 commit 09be11e
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pagerduty/pagerduty.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import (
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"

"github.com/google/go-querystring/query"
"github.com/heimweh/go-pagerduty/persistentconfig"
Expand Down Expand Up @@ -568,6 +570,21 @@ func (c *Client) decodeErrorResponse(res *Response) error {
v := &errorResponse{Error: &Error{ErrorResponse: res}}
err := c.DecodeJSON(res, v)

// Delaying retry based on ratelimit-reset recommended by PagerDuty
// https://developer.pagerduty.com/docs/72d3b724589e3-rest-api-rate-limits#reaching-the-limit
ratelimitReset := res.Response.Header.Get("ratelimit-reset")
if res.Response.StatusCode == http.StatusTooManyRequests && ratelimitReset != "" {
waitFor, err := strconv.ParseInt(ratelimitReset, 10, 0)
if err == nil {
reqMethod := res.Response.Request.Method
reqEndpoint := res.Response.Request.URL
log.Printf("[INFO] Rate limit hit, throttling by %d seconds until next retry to %s: %s", waitFor, strings.ToUpper(reqMethod), reqEndpoint)
time.Sleep(time.Duration(waitFor) * time.Second)
v.Error.needToRetry = true
return v.Error
}
}

isUsingScopedAPITokenFromCredentials := *c.Config.APIAuthTokenType == AuthTokenTypeUseAppCredentials
isOauthScopeMissing := isUsingScopedAPITokenFromCredentials && res.Response.StatusCode == http.StatusForbidden
needNewOauthScopedAccessToken := isUsingScopedAPITokenFromCredentials && res.Response.StatusCode == http.StatusUnauthorized
Expand Down

0 comments on commit 09be11e

Please sign in to comment.