-
Notifications
You must be signed in to change notification settings - Fork 10
/
transport.go
356 lines (315 loc) · 8.82 KB
/
transport.go
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
package statsig
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
StatsigAPI = "https://statsigapi.net/v1"
StatsigCDN = "https://api.statsigcdn.com/v1"
)
const (
maxRetries = 5
backoffMultiplier = 10
)
type transport struct {
sdkKey string
metadata statsigMetadata // Safe to read from but not thread safe to write into. If value needs to change, please ensure thread safety.
client *http.Client
options *Options
}
func newTransport(secret string, options *Options) *transport {
defer func() {
if err := recover(); err != nil {
Logger().LogError(err)
}
}()
return &transport{
metadata: getStatsigMetadata(),
sdkKey: secret,
client: &http.Client{
Timeout: time.Second * 3,
Transport: options.Transport,
},
options: options,
}
}
type RequestOptions struct {
retries int
backoff time.Duration
header map[string]string
}
func (opts *RequestOptions) fill_defaults() {
if opts.backoff == 0 {
opts.backoff = time.Second
}
}
func (transport *transport) download_config_specs(sinceTime int64, responseBody interface{}, diagnostics *marker) (*http.Response, error) {
diagnostics.downloadConfigSpecs().networkRequest().start().mark()
var endpoint string
if transport.options.DisableCDN {
endpoint = fmt.Sprintf("/download_config_specs?sinceTime=%d", sinceTime)
} else {
endpoint = fmt.Sprintf("/download_config_specs/%s.json?sinceTime=%d", transport.sdkKey, sinceTime)
}
options := RequestOptions{}
if transport.options.FallbackToStatsigAPI {
options.retries = 1
}
return transport.get(endpoint, responseBody, options, diagnostics)
}
func (transport *transport) get_id_lists(responseBody interface{}, diagnostics *marker) (*http.Response, error) {
diagnostics.getIdListSources().networkRequest().start().mark()
options := RequestOptions{}
if transport.options.FallbackToStatsigAPI {
options.retries = 1
}
return transport.post("/get_id_lists", nil, responseBody, options, diagnostics)
}
func (transport *transport) get_id_list(url string, headers map[string]string) (*http.Response, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, &TransportError{Err: err}
}
for k, v := range headers {
req.Header.Set(k, v)
}
res, err := transport.client.Do(req)
if err != nil {
var statusCode int
if res != nil {
statusCode = res.StatusCode
}
return res, &TransportError{
RequestMetadata: &RequestMetadata{
StatusCode: statusCode,
Endpoint: url,
Retries: 0,
},
Err: err}
}
return res, nil
}
func (transport *transport) log_event(
event []interface{},
responseBody interface{},
options RequestOptions,
) (*http.Response, error) {
input := logEventInput{
Events: event,
StatsigMetadata: transport.metadata,
}
if options.header == nil {
options.header = make(map[string]string)
}
options.header["statsig-event-count"] = strconv.Itoa(len(event))
return transport.post("/log_event", input, responseBody, options, nil)
}
func (transport *transport) post(
endpoint string,
body interface{},
responseBody interface{},
options RequestOptions,
diagnostics *marker,
) (*http.Response, error) {
return transport.doRequest("POST", endpoint, body, responseBody, options, diagnostics)
}
func (transport *transport) get(
endpoint string,
responseBody interface{},
options RequestOptions,
diagnostics *marker,
) (*http.Response, error) {
return transport.doRequest("GET", endpoint, nil, responseBody, options, diagnostics)
}
func (transport *transport) buildRequest(method, endpoint string, body interface{}, header map[string]string) (*http.Request, error) {
if transport.options.LocalMode {
return nil, nil
}
var bodyBuf io.Reader
if body != nil {
bodyBytes, err := json.Marshal(body)
if err != nil {
return nil, err
}
bodyBuf = bytes.NewBuffer(bodyBytes)
if strings.Contains(endpoint, "log_event") {
var compressedBody bytes.Buffer
gz := gzip.NewWriter(&compressedBody)
_, _ = gz.Write(bodyBytes)
gz.Close()
bodyBuf = &compressedBody
}
} else {
if method == "POST" {
bodyBuf = bytes.NewBufferString("{}")
}
}
url, err := transport.buildURL(endpoint, false)
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, url.String(), bodyBuf)
if err != nil {
return nil, err
}
req.Header.Add("STATSIG-API-KEY", transport.sdkKey)
req.Header.Set("Content-Type", "application/json")
if strings.Contains(endpoint, "log_event") {
req.Header.Set("Content-Encoding", "gzip")
}
req.Header.Add("STATSIG-CLIENT-TIME", strconv.FormatInt(getUnixMilli(), 10))
req.Header.Add("STATSIG-SERVER-SESSION-ID", transport.metadata.SessionID)
req.Header.Add("STATSIG-SDK-TYPE", transport.metadata.SDKType)
req.Header.Add("STATSIG-SDK-VERSION", transport.metadata.SDKVersion)
req.Header.Add("STATSIG-SDK-LANGUAGE-VERSION", transport.metadata.LanguageVersion)
for k, v := range header {
req.Header.Add(k, v)
}
return req, nil
}
func (t *transport) buildURL(path string, isRetry bool) (*url.URL, error) {
var api string
useDefaultAPI := isRetry && t.options.FallbackToStatsigAPI
endpoint := strings.TrimPrefix(path, "/v1")
if strings.Contains(endpoint, "download_config_specs") {
if useDefaultAPI {
api = StatsigCDN
} else {
api = defaultString(t.options.APIOverrides.DownloadConfigSpecs, defaultString(t.options.API, StatsigCDN))
}
} else if strings.Contains(endpoint, "get_id_list") {
if useDefaultAPI {
api = StatsigAPI
} else {
api = defaultString(t.options.APIOverrides.GetIDLists, defaultString(t.options.API, StatsigAPI))
}
} else if strings.Contains(endpoint, "log_event") {
if useDefaultAPI {
api = StatsigAPI
} else {
api = defaultString(t.options.APIOverrides.LogEvent, defaultString(t.options.API, StatsigAPI))
}
} else {
if useDefaultAPI {
api = StatsigAPI
} else {
api = defaultString(t.options.API, StatsigAPI)
}
}
return url.Parse(strings.TrimSuffix(api, "/") + endpoint)
}
func (t *transport) updateRequestForRetry(r *http.Request) *http.Request {
retryURL, err := t.buildURL(r.URL.Path, true)
if err == nil && strings.Compare(r.URL.Host, retryURL.Host) != 0 {
retryRequest, err := http.NewRequest(r.Method, retryURL.String(), r.Body)
if err == nil {
return retryRequest
}
}
return nil
}
func (transport *transport) doRequest(
method string,
endpoint string,
in interface{},
out interface{},
options RequestOptions,
diagnostics *marker,
) (*http.Response, error) {
request, err := transport.buildRequest(method, endpoint, in, options.header)
if request == nil || err != nil {
if err != nil {
return nil, &TransportError{Err: err}
}
return nil, nil
}
options.fill_defaults()
response, err, attempts := retry(options.retries, time.Duration(options.backoff), func() (*http.Response, bool, error) {
response, err := transport.client.Do(request)
if diagnostics != nil {
diagnostics.end()
if response != nil {
diagnostics.success(successfulStatusCode(response.StatusCode))
diagnostics.statusCode(response.StatusCode)
diagnostics.sdkRegion(safeGetFirst(response.Header["X-Statsig-Region"]))
} else {
diagnostics.success(false)
}
diagnostics.mark()
}
if err != nil {
return response, response != nil, err
}
retryRequest := transport.updateRequestForRetry(request)
if retryRequest != nil {
request = retryRequest
}
drainAndCloseBody := func() {
if response.Body != nil {
// Drain body to re-use the same connection
_, _ = io.Copy(io.Discard, response.Body)
response.Body.Close()
}
}
defer drainAndCloseBody()
if successfulStatusCode(response.StatusCode) {
return response, false, transport.parseResponse(response, out)
}
return response, retryableStatusCode(response.StatusCode), fmt.Errorf("%s", response.Status)
})
if err != nil {
if response == nil {
return response, &TransportError{Err: err}
}
return response, &TransportError{
RequestMetadata: &RequestMetadata{
StatusCode: response.StatusCode,
Endpoint: endpoint,
Retries: attempts,
},
Err: err,
}
}
return response, nil
}
func (transport *transport) parseResponse(response *http.Response, out interface{}) error {
if out == nil {
return nil
}
return json.NewDecoder(response.Body).Decode(&out)
}
func retry(retries int, backoff time.Duration, fn func() (*http.Response, bool, error)) (*http.Response, error, int) {
attempts := 0
for {
if response, retry, err := fn(); retry {
if retries <= 0 {
return response, err, attempts
}
retries--
attempts++
time.Sleep(backoff)
backoff = backoff * backoffMultiplier
} else {
return response, err, attempts
}
}
}
func retryableStatusCode(code int) bool {
switch code {
case 408, 500, 502, 503, 504, 522, 524, 599:
return true
default:
return false
}
}
func successfulStatusCode(code int) bool {
return code >= 200 && code < 300
}