-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
413 lines (361 loc) · 10.4 KB
/
http.go
File metadata and controls
413 lines (361 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package cloudlayer
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"math"
"math/rand"
"mime/multipart"
"net/http"
"strconv"
"strings"
"time"
)
// requestOptions controls per-request behavior.
type requestOptions struct {
params map[string]string // query parameters
retryable bool // eligible for auto-retry on 429/5xx
absolutePath bool // use path as-is, don't prepend apiVersion
}
// apiErrorBody is the shape of API error response JSON bodies.
type apiErrorBody struct {
StatusCode *int `json:"statusCode,omitempty"`
ErrorField *string `json:"error,omitempty"`
Message *string `json:"message,omitempty"`
}
// doRequest performs a JSON API request with optional retry.
func (c *Client) doRequest(ctx context.Context, method, path string, body interface{}, result interface{}, opts *requestOptions) (*ResponseHeaders, error) {
if opts == nil {
opts = &requestOptions{}
}
fullURL := c.buildURL(path, opts)
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshaling request body: %w", err)
}
bodyReader = bytes.NewReader(data)
}
maxAttempts := 1
if opts.retryable {
maxAttempts = 1 + c.maxRetries
}
var lastErr error
for attempt := 0; attempt < maxAttempts; attempt++ {
if attempt > 0 {
delay := c.retryDelay(attempt, lastErr)
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(delay):
}
// Re-create body reader for retry
if body != nil {
data, _ := json.Marshal(body)
bodyReader = bytes.NewReader(data)
}
}
req, err := http.NewRequestWithContext(ctx, method, fullURL, bodyReader)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
c.setHeaders(req, "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
lastErr = &NetworkError{
Message: err.Error(),
Err: err,
RequestPath: path,
RequestMethod: method,
}
if !opts.retryable {
return nil, lastErr
}
continue
}
headers := parseResponseHeaders(resp)
// Success
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
if resp.StatusCode == 204 || result == nil {
_ = resp.Body.Close()
return headers, nil
}
defer func() { _ = resp.Body.Close() }()
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
return headers, &APIError{
StatusCode: resp.StatusCode,
StatusText: resp.Status,
Message: "failed to decode response: " + err.Error(),
RequestPath: path,
RequestMethod: method,
}
}
return headers, nil
}
// Error — read body for error details
apiErr := c.buildError(resp, path, method)
_ = resp.Body.Close()
// Should we retry?
if opts.retryable && isRetryableStatus(resp.StatusCode) && attempt < maxAttempts-1 {
lastErr = apiErr
continue
}
return headers, apiErr
}
return nil, lastErr
}
// doRawRequest performs a request and returns the raw response for binary handling.
// The caller is responsible for closing resp.Body.
func (c *Client) doRawRequest(ctx context.Context, method, path string, body interface{}, opts *requestOptions) (*http.Response, *ResponseHeaders, error) {
if opts == nil {
opts = &requestOptions{}
}
fullURL := c.buildURL(path, opts)
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, nil, fmt.Errorf("marshaling request body: %w", err)
}
bodyReader = bytes.NewReader(data)
}
req, err := http.NewRequestWithContext(ctx, method, fullURL, bodyReader)
if err != nil {
return nil, nil, fmt.Errorf("creating request: %w", err)
}
c.setHeaders(req, "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
if ctx.Err() != nil {
return nil, nil, ctx.Err()
}
return nil, nil, &NetworkError{
Message: err.Error(),
Err: err,
RequestPath: path,
RequestMethod: method,
}
}
headers := parseResponseHeaders(resp)
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return resp, headers, nil
}
apiErr := c.buildError(resp, path, method)
_ = resp.Body.Close()
return nil, headers, apiErr
}
// doMultipartRequest performs a multipart form request.
func (c *Client) doMultipartRequest(ctx context.Context, path string, file *FileInput, fields map[string]string, result interface{}, opts *requestOptions) (*ResponseHeaders, error) {
if opts == nil {
opts = &requestOptions{}
}
fullURL := c.buildURL(path, opts)
var buf bytes.Buffer
writer := multipart.NewWriter(&buf)
// Add file
part, err := writer.CreateFormFile("file", file.Filename)
if err != nil {
return nil, fmt.Errorf("creating form file: %w", err)
}
if _, err := io.Copy(part, file.Reader); err != nil {
return nil, fmt.Errorf("writing file content: %w", err)
}
// Add other fields
for key, val := range fields {
if err := writer.WriteField(key, val); err != nil {
return nil, fmt.Errorf("writing form field %q: %w", key, err)
}
}
if err := writer.Close(); err != nil {
return nil, fmt.Errorf("closing multipart writer: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullURL, &buf)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
c.setHeaders(req, writer.FormDataContentType())
resp, err := c.httpClient.Do(req)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, &NetworkError{
Message: err.Error(),
Err: err,
RequestPath: path,
RequestMethod: http.MethodPost,
}
}
defer func() { _ = resp.Body.Close() }()
headers := parseResponseHeaders(resp)
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
if resp.StatusCode == 204 || result == nil {
return headers, nil
}
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
return headers, &APIError{
StatusCode: resp.StatusCode,
StatusText: resp.Status,
Message: "failed to decode response: " + err.Error(),
RequestPath: path,
RequestMethod: http.MethodPost,
}
}
return headers, nil
}
return headers, c.buildError(resp, path, http.MethodPost)
}
// buildURL constructs the full request URL.
func (c *Client) buildURL(path string, opts *requestOptions) string {
var base string
if opts != nil && opts.absolutePath {
base = c.baseURL + path
} else {
base = c.baseURL + "/" + string(c.apiVersion) + path
}
if opts != nil && len(opts.params) > 0 {
parts := make([]string, 0, len(opts.params))
for k, v := range opts.params {
parts = append(parts, k+"="+v)
}
base += "?" + strings.Join(parts, "&")
}
return base
}
// setHeaders sets common headers on a request.
func (c *Client) setHeaders(req *http.Request, contentType string) {
req.Header.Set("X-API-Key", c.apiKey)
req.Header.Set("User-Agent", c.userAgent)
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
for k, v := range c.customHeaders {
req.Header.Set(k, v)
}
}
// buildError constructs an appropriate error type from an HTTP response.
func (c *Client) buildError(resp *http.Response, path, method string) error {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
message := http.StatusText(resp.StatusCode)
// Try to parse error body for a message
var errBody apiErrorBody
if json.Unmarshal(body, &errBody) == nil {
if errBody.Message != nil && *errBody.Message != "" {
message = *errBody.Message
} else if errBody.ErrorField != nil && *errBody.ErrorField != "" {
message = *errBody.ErrorField
}
}
baseErr := APIError{
StatusCode: resp.StatusCode,
StatusText: http.StatusText(resp.StatusCode),
Message: message,
Body: body,
RequestPath: path,
RequestMethod: method,
}
switch resp.StatusCode {
case 401, 403:
return &AuthError{APIError: baseErr}
case 429:
retryAfter := parseRetryAfter(resp.Header.Get("Retry-After"))
return &RateLimitError{APIError: baseErr, RetryAfter: retryAfter}
default:
return &baseErr
}
}
// retryDelay calculates the delay before the next retry attempt.
func (c *Client) retryDelay(attempt int, lastErr error) time.Duration {
// Respect Retry-After header from rate limit errors
if rl, ok := lastErr.(*RateLimitError); ok && rl.RetryAfter != nil {
return time.Duration(*rl.RetryAfter) * time.Second
}
// Exponential backoff with jitter
baseDelay := time.Second
delay := baseDelay * time.Duration(math.Pow(2, float64(attempt-1)))
jitter := time.Duration(rand.Int63n(int64(baseDelay)))
return delay + jitter
}
// isRetryableStatus returns true for status codes that warrant a retry.
func isRetryableStatus(code int) bool {
switch code {
case 429, 500, 502, 503, 504:
return true
default:
return false
}
}
// parseRetryAfter parses the Retry-After header value as seconds.
func parseRetryAfter(value string) *int {
if value == "" {
return nil
}
// Try seconds
if n, err := strconv.Atoi(value); err == nil {
return &n
}
// Try HTTP-date
if t, err := http.ParseTime(value); err == nil {
seconds := int(time.Until(t).Seconds())
if seconds < 0 {
seconds = 0
}
return &seconds
}
return nil
}
// parseResponseHeaders extracts cl-* headers from the response.
func parseResponseHeaders(resp *http.Response) *ResponseHeaders {
h := &ResponseHeaders{}
if v := resp.Header.Get("cl-worker-job-id"); v != "" {
h.WorkerJobID = &v
}
if v := resp.Header.Get("cl-cluster-id"); v != "" {
h.ClusterID = &v
}
if v := resp.Header.Get("cl-worker"); v != "" {
h.Worker = &v
}
if v := resp.Header.Get("cl-bandwidth"); v != "" {
if n, err := strconv.Atoi(v); err == nil {
h.Bandwidth = &n
}
}
if v := resp.Header.Get("cl-process-time"); v != "" {
if n, err := strconv.Atoi(v); err == nil {
h.ProcessTime = &n
}
}
if v := resp.Header.Get("cl-calls-remaining"); v != "" {
if n, err := strconv.Atoi(v); err == nil {
h.CallsRemaining = &n
}
}
if v := resp.Header.Get("cl-charged-time"); v != "" {
if n, err := strconv.Atoi(v); err == nil {
h.ChargedTime = &n
}
}
if v := resp.Header.Get("cl-bandwidth-cost"); v != "" {
if f, err := strconv.ParseFloat(v, 64); err == nil {
h.BandwidthCost = &f
}
}
if v := resp.Header.Get("cl-process-time-cost"); v != "" {
if f, err := strconv.ParseFloat(v, 64); err == nil {
h.ProcessTimeCost = &f
}
}
if v := resp.Header.Get("cl-api-credit-cost"); v != "" {
if f, err := strconv.ParseFloat(v, 64); err == nil {
h.APICreditCost = &f
}
}
return h
}