Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,15 @@ const (
maxRetryBackoff = 2 * time.Second
maxResponseBodySize = 10 * 1024 * 1024
defaultAPIBaseURL = "https://api.gumroad.com/v2"

// A 429 is a budget, not a hiccup: the public API allows 500 requests per 10 seconds per
// token, and gumroad.com allows 6,000 requests per hour per IP, so a paginated walk can spend
// a whole budget by itself. Back off far enough that a retry does not just spend more of it,
// and give up with an explanation when the server names a wait longer than this — retrying
// inside an edge block only keeps the caller's IP in it.
initialRateLimitBackoff = 1 * time.Second
maxRateLimitBackoff = 4 * time.Second
maxRateLimitWait = 5 * time.Second
)

func defaultBaseURL() string {
Expand Down Expand Up @@ -244,6 +253,19 @@ func (c *Client) doPreparedWithContext(

if shouldRetry(method, attempt, resp.StatusCode) {
delay := retryDelay(attempt, resp.Header.Get("Retry-After"))
if resp.StatusCode == http.StatusTooManyRequests {
wait, ok := ParseRetryAfter(resp.Header.Get("Retry-After"))
if ok && wait > maxRateLimitWait {
err := parseAPIError(resp.StatusCode, data)
var apiErr *APIError
if errors.As(err, &apiErr) {
apiErr.RetryAfter = wait
}
logResponse(resp.StatusCode, len(data), err, start)
return nil, err
}
delay = rateLimitRetryDelay(attempt, wait, ok)
}
c.debugf("retry method=%s url=%s attempt=%d wait=%s reason=%q", method, logURL, attempt+1, delay, resp.Status)
if err := c.snoozeCtx(ctx, delay); err != nil {
return nil, fmt.Errorf("request failed: %w", err)
Expand Down Expand Up @@ -369,6 +391,20 @@ func retryDelay(attempt int, retryAfter string) time.Duration {
return time.Duration(backoff)
}

// rateLimitRetryDelay backs off in whole seconds for a 429 that names no wait, so a retry does not
// spend more of a budget that is already exhausted.
func rateLimitRetryDelay(attempt int, retryAfter time.Duration, hasRetryAfter bool) time.Duration {
if hasRetryAfter {
return retryAfter
}

backoff := float64(initialRateLimitBackoff) * math.Pow(2, float64(attempt))
if backoff > float64(maxRateLimitBackoff) {
backoff = float64(maxRateLimitBackoff)
}
return time.Duration(backoff)
}

// ParseRetryAfter reads a Retry-After value (seconds or an HTTP date). ok is
// false when the header is absent or carries no usable wait.
func ParseRetryAfter(value string) (time.Duration, bool) {
Expand Down
52 changes: 52 additions & 0 deletions internal/api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,58 @@ func TestClient_GetRetriesTransientStatus(t *testing.T) {
}
}

func TestClient_GetStopsOnRateLimitThatNamesALongWait(t *testing.T) {
attempts := 0
srv := setupTestServer(t, func(w http.ResponseWriter, r *http.Request) {
attempts++
w.Header().Set("Retry-After", "120")
w.WriteHeader(http.StatusTooManyRequests)
})
c := newTestClient(srv)
c.sleep = func(context.Context, time.Duration) error {
t.Fatal("unexpected retry sleep inside an exhausted request budget")
return nil
}

_, err := c.Get("/sales", nil)
var apiErr *APIError
if !errors.As(err, &apiErr) {
t.Fatalf("expected *APIError, got %T", err)
}
if apiErr.RetryAfter != 2*time.Minute {
t.Fatalf("got RetryAfter %s, want 2m", apiErr.RetryAfter)
}
if apiErr.GetHint() != HintRateLimited {
t.Fatalf("got hint %q, want the rate-limit hint", apiErr.GetHint())
}
if attempts != 1 {
t.Fatalf("got %d attempts, want 1", attempts)
}
}

func TestClient_GetBacksOffInSecondsOnRateLimitWithoutAWait(t *testing.T) {
attempts := 0
srv := setupTestServer(t, func(w http.ResponseWriter, r *http.Request) {
attempts++
w.WriteHeader(http.StatusTooManyRequests)
})
c := newTestClient(srv)
var slept []time.Duration
c.sleep = func(_ context.Context, d time.Duration) error {
slept = append(slept, d)
return nil
}

_, err := c.Get("/sales", nil)
assertAPIError(t, err, http.StatusTooManyRequests, "Rate limited.")
if attempts != 3 {
t.Fatalf("got %d attempts, want 3", attempts)
}
if len(slept) != 2 || slept[0] != time.Second || slept[1] != 2*time.Second {
t.Fatalf("got retry sleeps %v, want [1s 2s]", slept)
}
}

func TestClient_PostDoesNotRetryTransientStatus(t *testing.T) {
attempts := 0
srv := setupTestServer(t, func(w http.ResponseWriter, r *http.Request) {
Expand Down
9 changes: 7 additions & 2 deletions internal/api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ const HintRunAuthLogin = "Run: gumroad auth login. For CI/agents with an existin
// endpoint's own scope refusal carries a message and is left untouched.
const HintMissingScope = "Check that your token has the required scope. A token authorized for a team store keeps only the scopes that member's role allows; run: gumroad auth login (as the store's own account for the full set)"

// A 429 is a spent budget, not a hiccup: every page of a walk is another request, and both the
// public API (per token) and gumroad.com's edge (per IP) count them, so a full history walk can
// exhaust a budget on its own. Name the budgets and the one-request alternative.
const HintRateLimited = "Rate limits count every page: the public API allows 500 requests per 10 seconds per token and gumroad.com allows 6,000 requests per hour per IP. Wait for the window to reset, narrow the range with --after/--before, or run `gumroad sales export` to fetch the whole history in one request."

var (
ErrNotAuthenticated = errors.New("not authenticated")
ErrAccessDenied = errors.New("access denied")
Expand Down Expand Up @@ -98,9 +103,9 @@ func rewriteError(statusCode int, msg string) (message, hint string) {
return "Resource not found.", "Check the resource ID and try again."
case 429:
if msg != "" {
return msg, "Wait a moment and retry."
return msg, HintRateLimited
}
return "Rate limited.", "Wait a moment and retry."
return "Rate limited.", HintRateLimited
default:
if msg != "" {
return msg, ""
Expand Down
3 changes: 2 additions & 1 deletion internal/api/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,8 @@ func TestAPIError_Hints(t *testing.T) {
{"403", 403, `{"success":false}`, HintMissingScope},
{"403 with an endpoint message", 403, `{"success":false,"message":"Custom HTML pages are not enabled for your account."}`, "Check that your token has the required scope."},
{"404", 404, `{"success":false}`, "Check the resource ID and try again."},
{"429", 429, `{"success":false,"message":"Rate limited"}`, "Wait a moment and retry."},
{"429", 429, `{"success":false,"message":"Rate limited"}`, HintRateLimited},
{"429 without a message", 429, `{"success":false}`, HintRateLimited},
{"500", 500, `{"success":false}`, ""},
}

Expand Down
3 changes: 2 additions & 1 deletion skills/gumroad/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Always follow these rules:
- For operations that can prompt for confirmation (delete, refund, workflow step adds, workflow delay changes, mutating admin actions, `files abort`, `files complete` replay, product updates that remove files, or `products content set` when omitted page IDs will be deleted), add `--yes` to skip confirmation.
- Pass `--quiet` to suppress spinners and status messages.
- Pass `--dry-run` to preview mutating requests without executing them.
- Use `--page-delay 200ms` with `--all` to avoid rate limits on large datasets.
- Use `--all` deliberately: it costs one request per page (100 sales per page, so a 60,000-sale history is about 600 requests), and both the API (500 requests per 10 seconds per token) and gumroad.com (6,000 requests per hour per IP) count them. `--page-delay 200ms` spaces requests out but does not reduce how many there are; to read a whole history, prefer `sales export` (one request, CSV delivered by email) and analyze the file locally.
- Prices are in whole currency units (e.g. `--price 10.00` for $10), not cents. The CLI converts internally. Use `--currency eur` to change currency.
- Products are published immediately on create. Pass `--draft` to save an unpublished draft instead, then `gumroad products publish <id>` to make it live; `gumroad products unpublish <id>` takes a published product down. If the account cannot publish yet (unconfirmed email, no payout method), create still succeeds but saves a draft and prints the reason.
- Product cover and thumbnail uploads support JPEG, PNG, and GIF. WebP is not supported by the API and the CLI rejects it before upload.
Expand Down Expand Up @@ -836,5 +836,6 @@ gumroad webhooks delete <id> --yes --json --no-input
## Tips

- Use `--all` with `products list`, `sales list`, `subscribers list`, `payouts list` to fetch every page automatically.
- A `429` means a request budget is spent, not that the request was wrong: the CLI backs off in seconds and then stops with both limits named instead of retrying into the block. Wait for the window, narrow the range with `--after`/`--before`, or use `sales export` for the whole history in one request.
- Use `--plain` for tab-separated output suitable for `cut`, `awk`, and other Unix tools.
- Run `gumroad <command> --help` for full flag details on any command.
Loading