-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
179 lines (156 loc) · 4.42 KB
/
Copy pathhttp.go
File metadata and controls
179 lines (156 loc) · 4.42 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
package flow
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
)
const maxRetries = 3
type httpClient struct {
baseURL string
apiKey string
apiSecret string
timeout time.Duration
client *http.Client
}
func newHTTPClient(apiKey, apiSecret, baseURL string, timeout time.Duration) *httpClient {
return &httpClient{
baseURL: baseURL,
apiKey: apiKey,
apiSecret: apiSecret,
timeout: timeout,
client: &http.Client{Timeout: timeout},
}
}
func (h *httpClient) do(ctx context.Context, method, path string, body interface{}, params map[string]string) ([]byte, error) {
fullURL := h.baseURL + path
if len(params) > 0 {
q := url.Values{}
for k, v := range params {
if v != "" {
q.Set(k, v)
}
}
if qs := q.Encode(); qs != "" {
fullURL += "?" + qs
}
}
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("flow: marshal error: %w", err)
}
bodyReader = bytes.NewReader(data)
}
var lastErr error
for attempt := 0; attempt < maxRetries; attempt++ {
req, err := http.NewRequestWithContext(ctx, method, fullURL, bodyReader)
if err != nil {
return nil, fmt.Errorf("flow: request error: %w", err)
}
req.Header.Set("X-API-Key", h.apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "flow-go/"+Version)
if h.apiSecret != "" {
req.Header.Set("X-API-Secret", h.apiSecret)
}
// Reset body reader for retries
if body != nil {
data, _ := json.Marshal(body)
bodyReader = bytes.NewReader(data)
req.Body = io.NopCloser(bodyReader)
}
resp, err := h.client.Do(req)
if err != nil {
lastErr = err
if attempt < maxRetries-1 {
time.Sleep(time.Duration(1<<attempt) * 500 * time.Millisecond)
continue
}
return nil, &FlowError{Message: err.Error(), Code: "network_error"}
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("flow: read body error: %w", err)
}
if shouldRetry(resp.StatusCode) && attempt < maxRetries-1 {
wait := time.Duration(1<<attempt) * 500 * time.Millisecond
if resp.StatusCode == 429 {
if ra := resp.Header.Get("Retry-After"); ra != "" {
if secs, err := strconv.ParseFloat(ra, 64); err == nil {
wait = time.Duration(secs * float64(time.Second))
}
}
}
time.Sleep(wait)
continue
}
if resp.StatusCode >= 400 {
return nil, parseError(resp.StatusCode, respBody, resp.Header)
}
if resp.StatusCode == 204 {
return nil, nil
}
return respBody, nil
}
if lastErr != nil {
return nil, &FlowError{Message: lastErr.Error(), Code: "network_error"}
}
return nil, &FlowError{Message: "max retries exceeded", Code: "network_error"}
}
func (h *httpClient) get(ctx context.Context, path string, params map[string]string) ([]byte, error) {
return h.do(ctx, http.MethodGet, path, nil, params)
}
func (h *httpClient) post(ctx context.Context, path string, body interface{}) ([]byte, error) {
return h.do(ctx, http.MethodPost, path, body, nil)
}
func shouldRetry(status int) bool {
return status == 429 || status == 500 || status == 502 || status == 503 || status == 504
}
func parseError(status int, body []byte, headers http.Header) error {
var errBody struct {
Detail string `json:"detail"`
Message string `json:"message"`
Error string `json:"error"`
Code string `json:"code"`
Errors []map[string]string `json:"errors"`
}
_ = json.Unmarshal(body, &errBody)
msg := errBody.Detail
if msg == "" {
msg = errBody.Message
}
if msg == "" {
msg = errBody.Error
}
if msg == "" {
msg = string(body)
}
base := FlowError{Message: msg, Code: errBody.Code, Status: status}
switch status {
case 401:
return &AuthenticationError{FlowError: base}
case 404:
return &NotFoundError{FlowError: base}
case 422:
return &ValidationError{FlowError: base, Errors: errBody.Errors}
case 429:
var retryAfter float64
if ra := headers.Get("Retry-After"); ra != "" {
retryAfter, _ = strconv.ParseFloat(ra, 64)
}
return &RateLimitError{FlowError: base, RetryAfter: retryAfter}
default:
if status >= 500 {
return &ServerError{FlowError: base}
}
return &base
}
}