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
268 changes: 223 additions & 45 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -158,68 +162,237 @@ 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)
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
}

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)
}

// SendMultipartRequest sends an HTTP request with multipart form data
func (c *ApiClient) SendMultipartRequest(options MultipartOptions) (json.RawMessage, error) {
req, err := c.BuildMultipartRequest(options)
if err != nil {
return nil, err
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
}

c.logRequest(req, options.Verbose)
for attempt := 0; ; attempt++ {
req, err := build()
if err != nil {
return nil, err
}

if logReq != nil {
logReq(req)
}

resp, err := c.client.Do(req)
if err != nil {
return nil, xurlErrors.NewHTTPError(err)
resp, err := httpClient.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
}

return resp, nil
}
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()
}

// StreamRequest sends an HTTP request and streams the response
func (c *ApiClient) StreamRequest(options RequestOptions) error {
req, err := c.BuildRequest(options)
if err != nil {
return err
func (c *ApiClient) sleepFor(d time.Duration) {
if c.sleep != nil {
c.sleep(d)
return
}
time.Sleep(d)
}

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)
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: 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 != "" {
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 {
return ceilSeconds(t.Sub(now))
}
fmt.Println()
}

client := &http.Client{
Timeout: 0,
if resp.StatusCode == http.StatusTooManyRequests {
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
}
}
}
}

chosenReset := exhaustedReset
if chosenReset == 0 {
chosenReset = fallbackReset
}
if chosenReset > 0 {
return ceilSeconds(time.Unix(chosenReset, 0).Sub(now))
}
}

backoff := time.Second << min(attempt, 6)
if backoff > 60*time.Second {
return 60 * time.Second
}
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 ""
}
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,
// optionally retrying 429 and 503 responses when options.MaxRetries > 0.
func (c *ApiClient) SendMultipartRequest(options MultipartOptions) (json.RawMessage, error) {
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
}
defer resp.Body.Close()

return c.processResponse(resp, options.Verbose)
}

// 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 {
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()

Expand All @@ -244,7 +417,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)
Expand Down Expand Up @@ -425,10 +598,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("{}")
Expand All @@ -438,7 +616,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
Expand Down
Loading
Loading