From 0122f28aedcdf50ceca3eac0a79a7c6bbe0f3ac7 Mon Sep 17 00:00:00 2001 From: Taylor Caldwell Date: Tue, 1 Dec 2026 16:00:05 -0800 Subject: [PATCH 1/3] Add --retry flag (Retry-After/rate-limit backoff) and surface X-Request-Id on errors --- api/client.go | 163 ++++++++++++++++++++++++++++++++++++++------ api/client_test.go | 124 +++++++++++++++++++++++++++++++++ api/execute.go | 7 ++ api/execute_test.go | 16 +++++ cli/root.go | 19 +++--- errors/errors.go | 17 ++++- 6 files changed, 315 insertions(+), 31 deletions(-) diff --git a/api/client.go b/api/client.go index fd34ee4..7befdd1 100644 --- a/api/client.go +++ b/api/client.go @@ -11,6 +11,7 @@ import ( "net/http" "os" "path/filepath" + "strconv" "strings" "time" @@ -22,14 +23,15 @@ import ( // RequestOptions contains common options for API requests type RequestOptions struct { - Method string - Endpoint string - Headers []string - Data string - AuthType string - Username string - Verbose bool - Trace bool + Method string + Endpoint string + Headers []string + Data string + AuthType string + Username string + Verbose bool + Trace bool + MaxRetries int } // MultipartOptions contains options specific to multipart requests @@ -62,6 +64,8 @@ type ApiClient struct { // clients leave it false so a missing credential surfaces as a clear auth // error instead of a confusing server-side 401. allowUnauthenticated bool + sleep func(time.Duration) + now func() time.Time } // NewApiClient creates a new ApiClient @@ -158,22 +162,136 @@ func (c *ApiClient) BuildMultipartRequest(options MultipartOptions) (*http.Reque ) } -// SendRequest sends an HTTP request +// SendRequest sends an HTTP request, optionally retrying 429 and 503 responses +// when options.MaxRetries > 0 using Retry-After / rate-limit reset headers. func (c *ApiClient) SendRequest(options RequestOptions) (json.RawMessage, error) { - req, err := c.BuildRequest(options) - if err != nil { - return nil, err + maxRetries := options.MaxRetries + if maxRetries < 0 { + maxRetries = 0 } - c.logRequest(req, options.Verbose) + for attempt := 0; ; attempt++ { + req, err := c.BuildRequest(options) + if err != nil { + return nil, err + } - resp, err := c.client.Do(req) - if err != nil { - return nil, xurlErrors.NewHTTPError(err) + c.logRequest(req, options.Verbose) + + resp, err := c.client.Do(req) + if err != nil { + return nil, xurlErrors.NewHTTPError(err) + } + + if attempt < maxRetries && isRetryableStatus(resp.StatusCode) { + delay := retryDelay(resp, attempt, c.currentTime()) + reqID := responseRequestID(resp) + _, _ = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + + if reqID != "" { + fmt.Fprintf( + os.Stderr, + "Retrying in %s (attempt %d/%d, status %d, request-id: %s)\n", + delay.Round(time.Second), + attempt+1, + maxRetries, + resp.StatusCode, + reqID, + ) + } else { + fmt.Fprintf( + os.Stderr, + "Retrying in %s (attempt %d/%d, status %d)\n", + delay.Round(time.Second), + attempt+1, + maxRetries, + resp.StatusCode, + ) + } + c.sleepFor(delay) + continue + } + + res, procErr := c.processResponse(resp, options.Verbose) + resp.Body.Close() + return res, procErr } - defer resp.Body.Close() +} - return c.processResponse(resp, options.Verbose) +func (c *ApiClient) currentTime() time.Time { + if c.now != nil { + return c.now() + } + return time.Now() +} + +func (c *ApiClient) sleepFor(d time.Duration) { + if c.sleep != nil { + c.sleep(d) + return + } + time.Sleep(d) +} + +func isRetryableStatus(statusCode int) bool { + return statusCode == http.StatusTooManyRequests || statusCode == http.StatusServiceUnavailable +} + +// retryDelay computes how long to wait before retrying a 429/503 response: +// 1. Standard RFC 9110 Retry-After header (delta-seconds or HTTP-date). +// 2. X API rate-limit reset headers on 429 (x-rate-limit-reset, 24h reset). +// 3. Exponential backoff (1s, 2s, 4s, ...) capped at 60s. +func retryDelay(resp *http.Response, attempt int, now time.Time) time.Duration { + if raw := strings.TrimSpace(resp.Header.Get("Retry-After")); raw != "" { + if secs, err := strconv.ParseInt(raw, 10, 64); err == nil { + if secs < 1 { + secs = 1 + } + return time.Duration(secs) * time.Second + } + if t, err := http.ParseTime(raw); err == nil { + d := t.Sub(now) + if d < time.Second { + return time.Second + } + return d.Round(time.Second) + } + } + + if resp.StatusCode == http.StatusTooManyRequests { + for _, hdr := range []string{ + "X-Rate-Limit-Reset", + "X-User-Limit-24hour-Reset", + "X-App-Limit-24hour-Reset", + } { + if raw := strings.TrimSpace(resp.Header.Get(hdr)); raw != "" { + if epoch, err := strconv.ParseInt(raw, 10, 64); err == nil && epoch > 0 { + d := time.Unix(epoch, 0).Sub(now) + if d < time.Second { + return time.Second + } + return d.Round(time.Second) + } + } + } + } + + backoff := time.Second << min(attempt, 6) + if backoff > 60*time.Second { + return 60 * time.Second + } + return backoff +} + +func responseRequestID(resp *http.Response) string { + if resp == nil { + return "" + } + if id := strings.TrimSpace(resp.Header.Get("X-Request-Id")); id != "" { + return id + } + return strings.TrimSpace(resp.Header.Get("X-Transaction-Id")) } // SendMultipartRequest sends an HTTP request with multipart form data @@ -244,7 +362,7 @@ func (c *ApiClient) StreamRequest(options RequestOptions) error { return xurlErrors.NewJSONError(err) } - return xurlErrors.NewAPIError(js) + return xurlErrors.NewAPIErrorWithMetadata(js, resp.StatusCode, responseRequestID(resp)) } scanner := bufio.NewScanner(resp.Body) @@ -425,10 +543,15 @@ func (c *ApiClient) processResponse(resp *http.Response, verbose bool) (json.Raw fmt.Println() } + reqID := responseRequestID(resp) + var js json.RawMessage if len(responseBody) > 0 { if err := json.Unmarshal(responseBody, &js); err != nil { if resp.StatusCode >= 400 { + if reqID != "" { + return nil, xurlErrors.NewHTTPError(fmt.Errorf("HTTP error: %s (request-id: %s)", resp.Status, reqID)) + } return nil, xurlErrors.NewHTTPError(fmt.Errorf("HTTP error: %s", resp.Status)) } js = json.RawMessage("{}") @@ -438,7 +561,7 @@ func (c *ApiClient) processResponse(resp *http.Response, verbose bool) (json.Raw } if resp.StatusCode >= 400 { - return nil, xurlErrors.NewAPIError(js) + return nil, xurlErrors.NewAPIErrorWithMetadata(js, resp.StatusCode, reqID) } return js, nil diff --git a/api/client_test.go b/api/client_test.go index b8bd67a..7de8706 100644 --- a/api/client_test.go +++ b/api/client_test.go @@ -7,7 +7,9 @@ import ( "os" "path/filepath" "strings" + "sync/atomic" "testing" + "time" "github.com/xdevplatform/xurl/auth" "github.com/xdevplatform/xurl/config" @@ -456,3 +458,125 @@ func TestExplicitUsernameDoesNotDowngradeToAppOnly(t *testing.T) { require.Error(t, err, "explicit user with a failed token must not downgrade to app-only") assert.False(t, xurlErrors.IsAPIError(err) && err.Error() == "", "should surface the refresh error") } + +func TestSendRequestRetriesWithRetryAfterAndSurfacesRequestID(t *testing.T) { + fixedNow := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + + t.Run("retries 429 honoring Retry-After seconds and succeeds", func(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := calls.Add(1) + w.Header().Set("X-Request-Id", "abcdef0123456789") + if n == 1 { + w.Header().Set("Retry-After", "7") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"title":"Too Many Requests","status":429}`)) + return + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"data":{"id":"1"}}`)) + })) + defer srv.Close() + + client := NewApiClient(&config.Config{APIBaseURL: srv.URL}, nil) + client.allowUnauthenticated = true + var sleeps []time.Duration + client.sleep = func(d time.Duration) { sleeps = append(sleeps, d) } + client.now = func() time.Time { return fixedNow } + + res, err := client.SendRequest(RequestOptions{ + Method: "GET", + Endpoint: "/2/tweets/1", + MaxRetries: 2, + }) + require.NoError(t, err) + assert.JSONEq(t, `{"data":{"id":"1"}}`, string(res)) + assert.Equal(t, int32(2), calls.Load()) + assert.Equal(t, []time.Duration{7 * time.Second}, sleeps) + }) + + t.Run("retries 429 using X-Rate-Limit-Reset when Retry-After is absent", func(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if calls.Add(1) == 1 { + w.Header().Set("X-Rate-Limit-Reset", "1796126415") // fixedNow + 15s + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"title":"Too Many Requests","status":429}`)) + return + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"ok":true}`)) + })) + defer srv.Close() + + client := NewApiClient(&config.Config{APIBaseURL: srv.URL}, nil) + client.allowUnauthenticated = true + var sleeps []time.Duration + client.sleep = func(d time.Duration) { sleeps = append(sleeps, d) } + client.now = func() time.Time { return fixedNow } + + _, err := client.SendRequest(RequestOptions{ + Method: "GET", + Endpoint: "/2/tweets/1", + MaxRetries: 1, + }) + require.NoError(t, err) + assert.Equal(t, []time.Duration{15 * time.Second}, sleeps) + }) + + t.Run("does not retry 400 and preserves X-Request-Id on API error", func(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.Header().Set("X-Request-Id", "feedface12345678") + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"title":"Invalid Request","status":400}`)) + })) + defer srv.Close() + + client := NewApiClient(&config.Config{APIBaseURL: srv.URL}, nil) + client.allowUnauthenticated = true + client.sleep = func(time.Duration) { t.Fatal("should not sleep on 400") } + + _, err := client.SendRequest(RequestOptions{ + Method: "GET", + Endpoint: "/2/tweets/1", + MaxRetries: 3, + }) + require.Error(t, err) + assert.Equal(t, int32(1), calls.Load()) + var apiErr *xurlErrors.Error + require.ErrorAs(t, err, &apiErr) + assert.Equal(t, 400, apiErr.StatusCode) + assert.Equal(t, "feedface12345678", apiErr.RequestID) + }) + + t.Run("retries 503 with exponential backoff and stops after MaxRetries", func(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.Header().Set("X-Transaction-Id", "tx-fallback-id") + w.WriteHeader(http.StatusServiceUnavailable) + _, _ = w.Write([]byte(`{"title":"Service Unavailable","status":503}`)) + })) + defer srv.Close() + + client := NewApiClient(&config.Config{APIBaseURL: srv.URL}, nil) + client.allowUnauthenticated = true + var sleeps []time.Duration + client.sleep = func(d time.Duration) { sleeps = append(sleeps, d) } + client.now = func() time.Time { return fixedNow } + + _, err := client.SendRequest(RequestOptions{ + Method: "GET", + Endpoint: "/2/tweets/1", + MaxRetries: 2, + }) + require.Error(t, err) + assert.Equal(t, int32(3), calls.Load()) + assert.Equal(t, []time.Duration{1 * time.Second, 2 * time.Second}, sleeps) + var apiErr *xurlErrors.Error + require.ErrorAs(t, err, &apiErr) + assert.Equal(t, "tx-fallback-id", apiErr.RequestID) + }) +} diff --git a/api/execute.go b/api/execute.go index b68e357..b5d661f 100644 --- a/api/execute.go +++ b/api/execute.go @@ -2,7 +2,10 @@ package api import ( "encoding/json" + "errors" "fmt" + + xurlErrors "github.com/xdevplatform/xurl/errors" "github.com/xdevplatform/xurl/utils" ) @@ -36,6 +39,10 @@ func handleRequestError(clientErr error) error { var rawJSON json.RawMessage if json.Unmarshal([]byte(clientErr.Error()), &rawJSON) == nil { utils.FormatAndPrintResponse(rawJSON) + var apiErr *xurlErrors.Error + if errors.As(clientErr, &apiErr) && apiErr.RequestID != "" { + return fmt.Errorf("request failed (request-id: %s)", apiErr.RequestID) + } return fmt.Errorf("request failed") } return clientErr diff --git a/api/execute_test.go b/api/execute_test.go index c48447d..7c951d0 100644 --- a/api/execute_test.go +++ b/api/execute_test.go @@ -52,4 +52,20 @@ func TestHandleRequestError(t *testing.T) { assert.Equal(t, "request failed", got.Error()) assert.Contains(t, buf.String(), "bad request", "the JSON error body should be printed") }) + + t.Run("JSON API error includes request-id when present", func(t *testing.T) { + var buf bytes.Buffer + defer redirectColor(&buf)() + + apiErr := xurlErrors.NewAPIErrorWithMetadata( + []byte(`{"title":"Too Many Requests","status":429}`), + 429, + "0123456789abcdef", + ) + got := handleRequestError(apiErr) + + require.Error(t, got) + assert.Equal(t, "request failed (request-id: 0123456789abcdef)", got.Error()) + assert.Contains(t, buf.String(), "Too Many Requests") + }) } diff --git a/cli/root.go b/cli/root.go index 3266ada..8a8e2e1 100644 --- a/cli/root.go +++ b/cli/root.go @@ -73,6 +73,7 @@ Commands are grouped by purpose below. Run 'xurl --help' for details.` trace, _ := cmd.Flags().GetBool("trace") forceStream, _ := cmd.Flags().GetBool("stream") mediaFile, _ := cmd.Flags().GetString("file") + maxRetries, _ := cmd.Flags().GetInt("retry") if len(args) == 0 { fmt.Fprintln(os.Stderr, "No URL provided") @@ -86,14 +87,15 @@ Commands are grouped by purpose below. Run 'xurl --help' for details.` client := api.NewApiClient(cfg, a) requestOptions := api.RequestOptions{ - Method: method, - Endpoint: url, - Headers: headers, - Data: data, - AuthType: authType, - Username: username, - Verbose: verbose, - Trace: trace, + Method: method, + Endpoint: url, + Headers: headers, + Data: data, + AuthType: authType, + Username: username, + Verbose: verbose, + Trace: trace, + MaxRetries: maxRetries, } err := api.HandleRequest(requestOptions, forceStream, mediaFile, client) if err != nil { @@ -115,6 +117,7 @@ Commands are grouped by purpose below. Run 'xurl --help' for details.` rootCmd.Flags().BoolP("trace", "t", false, "Add trace header to request") rootCmd.Flags().BoolP("stream", "s", false, "Force streaming mode for non-streaming endpoints") rootCmd.Flags().StringP("file", "F", "", "File to upload (for multipart requests)") + rootCmd.Flags().Int("retry", 0, "Retry 429/503 responses up to N times, honoring Retry-After and rate-limit reset headers") // Organise subcommands into scannable help sections. rootCmd.AddGroup( diff --git a/errors/errors.go b/errors/errors.go index f5767b3..f38b26a 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -17,9 +17,11 @@ const ( ) type Error struct { - Type string - Message string - cause error + Type string + Message string + StatusCode int + RequestID string + cause error } func (e *Error) Error() string { @@ -70,6 +72,15 @@ func NewAPIError(data json.RawMessage) *Error { return NewError(ErrTypeAPI, string(data), nil) } +func NewAPIErrorWithMetadata(data json.RawMessage, statusCode int, requestID string) *Error { + return &Error{ + Type: ErrTypeAPI, + Message: string(data), + StatusCode: statusCode, + RequestID: requestID, + } +} + func NewJSONError(cause error) *Error { return NewError(ErrTypeJSON, cause.Error(), cause) } From 73f3ce22524257d8b1d474e7755d384bda892164 Mon Sep 17 00:00:00 2001 From: Taylor Caldwell Date: Tue, 1 Dec 2026 17:28:56 -0800 Subject: [PATCH 2/3] Honor --retry in StreamRequest and SendMultipartRequest --- api/client.go | 92 ++++++++++++++++++++++++++++------------------ api/client_test.go | 79 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+), 36 deletions(-) diff --git a/api/client.go b/api/client.go index 7befdd1..ac7c5d0 100644 --- a/api/client.go +++ b/api/client.go @@ -165,20 +165,41 @@ func (c *ApiClient) BuildMultipartRequest(options MultipartOptions) (*http.Reque // SendRequest sends an HTTP request, optionally retrying 429 and 503 responses // when options.MaxRetries > 0 using Retry-After / rate-limit reset headers. func (c *ApiClient) SendRequest(options RequestOptions) (json.RawMessage, error) { - maxRetries := options.MaxRetries + resp, err := c.doWithRetry( + c.client, + options.MaxRetries, + func() (*http.Request, error) { return c.BuildRequest(options) }, + func(req *http.Request) { c.logRequest(req, options.Verbose) }, + ) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + return c.processResponse(resp, options.Verbose) +} + +func (c *ApiClient) doWithRetry( + httpClient *http.Client, + maxRetries int, + build func() (*http.Request, error), + logReq func(*http.Request), +) (*http.Response, error) { if maxRetries < 0 { maxRetries = 0 } for attempt := 0; ; attempt++ { - req, err := c.BuildRequest(options) + req, err := build() if err != nil { return nil, err } - c.logRequest(req, options.Verbose) + if logReq != nil { + logReq(req) + } - resp, err := c.client.Do(req) + resp, err := httpClient.Do(req) if err != nil { return nil, xurlErrors.NewHTTPError(err) } @@ -213,9 +234,7 @@ func (c *ApiClient) SendRequest(options RequestOptions) (json.RawMessage, error) continue } - res, procErr := c.processResponse(resp, options.Verbose) - resp.Body.Close() - return res, procErr + return resp, nil } } @@ -294,50 +313,51 @@ func responseRequestID(resp *http.Response) string { return strings.TrimSpace(resp.Header.Get("X-Transaction-Id")) } -// SendMultipartRequest sends an HTTP request with multipart form data +// SendMultipartRequest sends an HTTP request with multipart form data, +// optionally retrying 429 and 503 responses when options.MaxRetries > 0. func (c *ApiClient) SendMultipartRequest(options MultipartOptions) (json.RawMessage, error) { - req, err := c.BuildMultipartRequest(options) + resp, err := c.doWithRetry( + c.client, + options.MaxRetries, + func() (*http.Request, error) { return c.BuildMultipartRequest(options) }, + func(req *http.Request) { c.logRequest(req, options.Verbose) }, + ) if err != nil { return nil, err } - - c.logRequest(req, options.Verbose) - - resp, err := c.client.Do(req) - if err != nil { - return nil, xurlErrors.NewHTTPError(err) - } defer resp.Body.Close() return c.processResponse(resp, options.Verbose) } -// StreamRequest sends an HTTP request and streams the response +// StreamRequest sends an HTTP request and streams the response, optionally +// retrying initial connection 429 and 503 responses when options.MaxRetries > 0. func (c *ApiClient) StreamRequest(options RequestOptions) error { - req, err := c.BuildRequest(options) - if err != nil { - return err - } - - if options.Verbose { - fmt.Printf("\033[1;34m> %s\033[0m %s\n", req.Method, req.URL) - for key, values := range req.Header { - for _, value := range values { - fmt.Printf("\033[1;36m> %s\033[0m: %s\n", key, value) - } - } - fmt.Println() - } - - client := &http.Client{ - Timeout: 0, + streamClient := &http.Client{ + Timeout: 0, + Transport: c.client.Transport, } fmt.Printf("\033[1;32mConnecting to streaming endpoint: %s\033[0m\n", options.Endpoint) - resp, err := client.Do(req) + resp, err := c.doWithRetry( + streamClient, + options.MaxRetries, + func() (*http.Request, error) { return c.BuildRequest(options) }, + func(req *http.Request) { + if options.Verbose { + fmt.Printf("\033[1;34m> %s\033[0m %s\n", req.Method, req.URL) + for key, values := range req.Header { + for _, value := range values { + fmt.Printf("\033[1;36m> %s\033[0m: %s\n", key, value) + } + } + fmt.Println() + } + }, + ) if err != nil { - return xurlErrors.NewHTTPError(err) + return err } defer resp.Body.Close() diff --git a/api/client_test.go b/api/client_test.go index 7de8706..c425afc 100644 --- a/api/client_test.go +++ b/api/client_test.go @@ -2,6 +2,7 @@ package api import ( "encoding/json" + "io" "net/http" "net/http/httptest" "os" @@ -579,4 +580,82 @@ func TestSendRequestRetriesWithRetryAfterAndSurfacesRequestID(t *testing.T) { require.ErrorAs(t, err, &apiErr) assert.Equal(t, "tx-fallback-id", apiErr.RequestID) }) + + t.Run("StreamRequest retries 429 using Retry-After before streaming", func(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if calls.Add(1) == 1 { + w.Header().Set("Retry-After", "4") + w.Header().Set("X-Request-Id", "stream-429-id") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"title":"Too Many Requests","status":429}`)) + return + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("{\"data\":{\"id\":\"1\"}}\n")) + })) + defer srv.Close() + + client := NewApiClient(&config.Config{APIBaseURL: srv.URL}, nil) + client.allowUnauthenticated = true + var sleeps []time.Duration + client.sleep = func(d time.Duration) { sleeps = append(sleeps, d) } + client.now = func() time.Time { return fixedNow } + + err := client.StreamRequest(RequestOptions{ + Method: "GET", + Endpoint: "/2/tweets/search/stream", + MaxRetries: 2, + }) + require.NoError(t, err) + assert.Equal(t, int32(2), calls.Load()) + assert.Equal(t, []time.Duration{4 * time.Second}, sleeps) + }) + + t.Run("SendMultipartRequest retries 429 and rebuilds multipart body", func(t *testing.T) { + var calls atomic.Int32 + var receivedBodies []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.NoError(t, r.ParseMultipartForm(1024)) + f, _, err := r.FormFile("media") + require.NoError(t, err) + data, err := io.ReadAll(f) + f.Close() + require.NoError(t, err) + receivedBodies = append(receivedBodies, string(data)) + + if calls.Add(1) == 1 { + w.Header().Set("Retry-After", "3") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = w.Write([]byte(`{"title":"Too Many Requests","status":429}`)) + return + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"data":{"id":"media-1"}}`)) + })) + defer srv.Close() + + client := NewApiClient(&config.Config{APIBaseURL: srv.URL}, nil) + client.allowUnauthenticated = true + var sleeps []time.Duration + client.sleep = func(d time.Duration) { sleeps = append(sleeps, d) } + client.now = func() time.Time { return fixedNow } + + res, err := client.SendMultipartRequest(MultipartOptions{ + RequestOptions: RequestOptions{ + Method: "POST", + Endpoint: "/2/media/upload/123/append", + MaxRetries: 2, + }, + FormFields: map[string]string{"segment_index": "0"}, + FileField: "media", + FileName: "chunk.bin", + FileData: []byte("payload-bytes"), + }) + require.NoError(t, err) + assert.JSONEq(t, `{"data":{"id":"media-1"}}`, string(res)) + assert.Equal(t, int32(2), calls.Load()) + assert.Equal(t, []time.Duration{3 * time.Second}, sleeps) + assert.Equal(t, []string{"payload-bytes", "payload-bytes"}, receivedBodies) + }) } From 70232d1140357b6ba060d146dd078e471fc7a5ca Mon Sep 17 00:00:00 2001 From: Taylor Caldwell Date: Tue, 1 Dec 2026 17:37:55 -0800 Subject: [PATCH 3/3] Select exhausted rate-limit window reset and ceiling wait duration --- api/client.go | 69 ++++++++++++++++++++++++++++++++++------------ api/client_test.go | 34 +++++++++++++++++++++++ 2 files changed, 86 insertions(+), 17 deletions(-) diff --git a/api/client.go b/api/client.go index ac7c5d0..cdd7312 100644 --- a/api/client.go +++ b/api/client.go @@ -259,7 +259,9 @@ func isRetryableStatus(statusCode int) bool { // retryDelay computes how long to wait before retrying a 429/503 response: // 1. Standard RFC 9110 Retry-After header (delta-seconds or HTTP-date). -// 2. X API rate-limit reset headers on 429 (x-rate-limit-reset, 24h reset). +// 2. X API rate-limit reset headers on 429: prefers the latest reset among +// exhausted windows (`*-Remaining: 0`), falling back to the latest valid +// reset header across 15m and 24h windows. // 3. Exponential backoff (1s, 2s, 4s, ...) capped at 60s. func retryDelay(resp *http.Response, attempt int, now time.Time) time.Duration { if raw := strings.TrimSpace(resp.Header.Get("Retry-After")); raw != "" { @@ -270,30 +272,51 @@ func retryDelay(resp *http.Response, attempt int, now time.Time) time.Duration { return time.Duration(secs) * time.Second } if t, err := http.ParseTime(raw); err == nil { - d := t.Sub(now) - if d < time.Second { - return time.Second - } - return d.Round(time.Second) + return ceilSeconds(t.Sub(now)) } } if resp.StatusCode == http.StatusTooManyRequests { - for _, hdr := range []string{ - "X-Rate-Limit-Reset", - "X-User-Limit-24hour-Reset", - "X-App-Limit-24hour-Reset", - } { - if raw := strings.TrimSpace(resp.Header.Get(hdr)); raw != "" { - if epoch, err := strconv.ParseInt(raw, 10, 64); err == nil && epoch > 0 { - d := time.Unix(epoch, 0).Sub(now) - if d < time.Second { - return time.Second + type windowHeaders struct { + remaining string + reset string + } + windows := []windowHeaders{ + {remaining: "X-Rate-Limit-Remaining", reset: "X-Rate-Limit-Reset"}, + {remaining: "X-User-Limit-24hour-Remaining", reset: "X-User-Limit-24hour-Reset"}, + {remaining: "X-App-Limit-24hour-Remaining", reset: "X-App-Limit-24hour-Reset"}, + } + + var exhaustedReset int64 + var fallbackReset int64 + for _, w := range windows { + rawReset := strings.TrimSpace(resp.Header.Get(w.reset)) + if rawReset == "" { + continue + } + epoch, err := strconv.ParseInt(rawReset, 10, 64) + if err != nil || epoch <= 0 { + continue + } + if epoch > fallbackReset { + fallbackReset = epoch + } + if rawRem := strings.TrimSpace(resp.Header.Get(w.remaining)); rawRem != "" { + if rem, err := strconv.ParseInt(rawRem, 10, 64); err == nil && rem <= 0 { + if epoch > exhaustedReset { + exhaustedReset = epoch } - return d.Round(time.Second) } } } + + chosenReset := exhaustedReset + if chosenReset == 0 { + chosenReset = fallbackReset + } + if chosenReset > 0 { + return ceilSeconds(time.Unix(chosenReset, 0).Sub(now)) + } } backoff := time.Second << min(attempt, 6) @@ -303,6 +326,18 @@ func retryDelay(resp *http.Response, attempt int, now time.Time) time.Duration { return backoff } +// ceilSeconds rounds d up to the next whole second (minimum 1s) so retries +// never fire before a rate-limit reset boundary. +func ceilSeconds(d time.Duration) time.Duration { + if d <= time.Second { + return time.Second + } + if rem := d % time.Second; rem > 0 { + return d - rem + time.Second + } + return d +} + func responseRequestID(resp *http.Response) string { if resp == nil { return "" diff --git a/api/client_test.go b/api/client_test.go index c425afc..d72a505 100644 --- a/api/client_test.go +++ b/api/client_test.go @@ -7,6 +7,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "strconv" "strings" "sync/atomic" "testing" @@ -658,4 +659,37 @@ func TestSendRequestRetriesWithRetryAfterAndSurfacesRequestID(t *testing.T) { assert.Equal(t, []time.Duration{3 * time.Second}, sleeps) assert.Equal(t, []string{"payload-bytes", "payload-bytes"}, receivedBodies) }) + + t.Run("prefers exhausted 24-hour reset window over non-exhausted 15-minute window", func(t *testing.T) { + resp := &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: make(http.Header), + } + // 15-minute window still has quota remaining; 24-hour user window is exhausted. + resp.Header.Set("X-Rate-Limit-Remaining", "80") + resp.Header.Set("X-Rate-Limit-Reset", strconv.FormatInt(fixedNow.Add(15*time.Second).Unix(), 10)) + resp.Header.Set("X-User-Limit-24hour-Remaining", "0") + resp.Header.Set("X-User-Limit-24hour-Reset", strconv.FormatInt(fixedNow.Add(time.Hour).Unix(), 10)) + + delay := retryDelay(resp, 0, fixedNow) + assert.Equal(t, time.Hour, delay) + }) + + t.Run("rounds sub-second reset waits up so retries never fire early", func(t *testing.T) { + nowWithNanos := fixedNow.Add(600 * time.Millisecond) // 14.4s before fixedNow + 15s + + resetResp := &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: make(http.Header), + } + resetResp.Header.Set("X-Rate-Limit-Reset", strconv.FormatInt(fixedNow.Add(15*time.Second).Unix(), 10)) + assert.Equal(t, 15*time.Second, retryDelay(resetResp, 0, nowWithNanos)) + + dateResp := &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: make(http.Header), + } + dateResp.Header.Set("Retry-After", fixedNow.Add(15*time.Second).Format(http.TimeFormat)) + assert.Equal(t, 15*time.Second, retryDelay(dateResp, 0, nowWithNanos)) + }) }