rebuild the body on every attempt

This commit is contained in:
Miloš Jovanović 2026-09-24 20:46:26 -07:00
parent 726376f9a1
commit 18e8cb055e

View file

@ -35,53 +35,59 @@ func NewClient(key string, dryRun bool) *Client {
} }
// do applies the rate limit, retries once on 429, and returns the raw body. // do applies the rate limit, retries once on 429, and returns the raw body.
func (c *Client) do(ctx context.Context, method, path string, body io.Reader) ([]byte, error) { // rebuilds the body on every attempt
if err := c.limiter.Wait(ctx); err != nil { func (c *Client) do(ctx context.Context, method, path string, body []byte) ([]byte, error) {
return nil, err for attempt := 0; ; attempt++ {
} if err := c.limiter.Wait(ctx); err != nil {
return nil, err
}
var r io.Reader
if body != nil {
r = bytes.NewReader(body) // fresh reader each attempt
}
req, err := http.NewRequestWithContext(ctx, method, baseURL+path, r)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.key)
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req, err := http.NewRequestWithContext(ctx, method, baseURL+path, body) resp, err := c.http.Do(req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
req.Header.Set("Authorization", "Bearer "+c.key)
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.http.Do(req) if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
if err != nil { resp.Body.Close()
return nil, err wait := 30 * time.Second
} if s := resp.Header.Get("Retry-After"); s != "" {
defer resp.Body.Close() if secs, err := strconv.Atoi(s); err == nil {
wait = time.Duration(secs) * time.Second
if resp.StatusCode == http.StatusTooManyRequests { }
wait := 30 * time.Second }
if s := resp.Header.Get("Retry-After"); s != "" { log.Printf("rate limited; waiting %s", wait)
if secs, err := strconv.Atoi(s); err == nil { select {
wait = time.Duration(secs) * time.Second case <-time.After(wait):
continue
case <-ctx.Done():
return nil, ctx.Err()
} }
} }
log.Printf("rate limited; waiting %s", wait)
select { raw, err := io.ReadAll(resp.Body)
case <-time.After(wait): resp.Body.Close()
case <-ctx.Done(): if err != nil {
return nil, ctx.Err() return nil, err
} }
return c.do(ctx, method, path, body) if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf("%s %s: %d: %s", method, path, resp.StatusCode, truncate(raw))
}
return raw, nil
} }
raw, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf("%s %s: %d: %s", method, path, resp.StatusCode, truncate(raw))
}
return raw, nil
} }
func truncate(b []byte) string { func truncate(b []byte) string {
if len(b) > 300 { if len(b) > 300 {
return string(b[:300]) + "..." return string(b[:300]) + "..."