forked from DataDog/datadog-ci
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.ts
259 lines (218 loc) · 7.34 KB
/
api.ts
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
import {stringify} from 'querystring'
import {AxiosError, AxiosPromise, AxiosRequestConfig} from 'axios'
import FormData from 'form-data'
import {getRequestBuilder} from '../../helpers/utils'
import {MAX_TESTS_TO_TRIGGER} from './command'
import {CriticalError} from './errors'
import {
APIConfiguration,
Batch,
Payload,
PollResult,
PresignedUrlResponse,
ServerBatch,
ServerTest,
SyntheticsCIConfig,
TestSearchResult,
Trigger,
} from './interfaces'
import {ciTriggerApp, getDatadogHost, retry} from './utils'
const MAX_RETRIES = 3
const DELAY_BETWEEN_RETRIES = 500 // In ms
interface BackendError {
errors: string[]
}
export class EndpointError extends Error {
constructor(public message: string, public status: number) {
super(message)
Object.setPrototypeOf(this, EndpointError.prototype)
}
}
export const formatBackendErrors = (requestError: AxiosError<BackendError>) => {
if (requestError.response?.data?.errors) {
const serverHead = `query on ${requestError.config.baseURL}${requestError.config.url} returned:`
const errors = requestError.response.data.errors
if (errors.length > 1) {
const formattedErrors = errors.map((message: string) => ` - ${message}`)
return `${serverHead}\n${formattedErrors.join('\n')}`
} else if (errors.length) {
return `${serverHead} "${errors[0]}"`
} else {
return `error querying ${requestError.config.baseURL}${requestError.config.url}`
}
}
return `could not query ${requestError.config.baseURL}${requestError.config.url}\n${requestError.message}`
}
const triggerTests = (request: (args: AxiosRequestConfig) => AxiosPromise<Trigger>) => async (data: Payload) => {
const resp = await retryRequest(
{
data,
headers: {'X-Trigger-App': ciTriggerApp},
method: 'POST',
url: '/synthetics/tests/trigger/ci',
},
request
)
return resp.data
}
const getTest = (request: (args: AxiosRequestConfig) => AxiosPromise<ServerTest>) => async (testId: string) => {
const resp = await retryRequest(
{
url: `/synthetics/tests/${testId}`,
},
request
)
return resp.data
}
const searchTests = (request: (args: AxiosRequestConfig) => AxiosPromise<TestSearchResult>) => async (
query: string
) => {
const resp = await retryRequest(
{
params: {
// Search for one more test than limit to detect if too many tests are returned
count: MAX_TESTS_TO_TRIGGER + 1,
text: query,
},
url: '/synthetics/tests/search',
},
request
)
return resp.data
}
const getBatch = (request: (args: AxiosRequestConfig) => AxiosPromise<{data: ServerBatch}>) => async (
batchId: string
): Promise<Batch> => {
const resp = await retryRequest({url: `/synthetics/ci/batch/${batchId}`}, request, retryOn5xxOr404Errors)
const serverBatch = resp.data.data
return {
results: serverBatch.results.filter((r) => r.status !== 'skipped') as Batch['results'],
status: serverBatch.status,
}
}
const pollResults = (request: (args: AxiosRequestConfig) => AxiosPromise<{results: PollResult[]}>) => async (
resultIds: string[]
) => {
const resp = await retryRequest(
{
params: {
result_ids: JSON.stringify(resultIds),
},
url: '/synthetics/tests/poll_results',
},
request,
retryOn5xxOr404Errors
)
return resp.data.results
}
const getTunnelPresignedURL = (request: (args: AxiosRequestConfig) => AxiosPromise<{url: string}>) => async (
testIds: string[]
) => {
const resp = await retryRequest(
{
params: {
test_id: testIds,
},
paramsSerializer: (params) => stringify(params),
url: '/synthetics/ci/tunnel',
},
request
)
return resp.data
}
const getMobileApplicationPresignedURL = (
request: (args: AxiosRequestConfig) => AxiosPromise<PresignedUrlResponse>
) => async (applicationId: string, md5: string) => {
const resp = await retryRequest(
{
data: {md5},
method: 'POST',
url: `/synthetics/mobile/applications/${applicationId}/presigned-url`,
},
request
)
return resp.data
}
const uploadMobileApplication = (request: (args: AxiosRequestConfig) => AxiosPromise<void>) => async (
fileBuffer: Buffer,
presignedUrlParams: PresignedUrlResponse['presigned_url_params']
) => {
const form = new FormData()
Object.entries(presignedUrlParams.fields).forEach(([key, value]) => {
form.append(key, value)
})
form.append('file', fileBuffer)
await retryRequest(
{
data: form,
headers: {...form.getHeaders(), 'Content-Length': form.getLengthSync()},
maxBodyLength: Infinity,
maxContentLength: Infinity,
method: 'POST',
url: presignedUrlParams.url,
},
request
)
}
type RetryPolicy = (retries: number, error: AxiosError) => number | undefined
const retryOn5xxErrors: RetryPolicy = (retries, error) => {
if (retries < MAX_RETRIES && is5xxError(error)) {
return DELAY_BETWEEN_RETRIES
}
}
const retryOn5xxOr404Errors: RetryPolicy = (retries, error) => {
const retryOn5xxDelay = retryOn5xxErrors(retries, error)
if (retryOn5xxDelay) {
return retryOn5xxDelay
}
if (retries < MAX_RETRIES && isNotFoundError(error)) {
return DELAY_BETWEEN_RETRIES
}
}
const getErrorHttpStatus = (error: AxiosError | EndpointError) =>
'status' in error ? error.status : error.response?.status
export const isForbiddenError = (error: AxiosError | EndpointError) => getErrorHttpStatus(error) === 403
export const isNotFoundError = (error: AxiosError | EndpointError) => getErrorHttpStatus(error) === 404
export const is5xxError = (error: AxiosError | EndpointError) => {
const statusCode = getErrorHttpStatus(error)
return statusCode && statusCode >= 500 && statusCode <= 599
}
const retryRequest = <T>(
args: AxiosRequestConfig,
request: (args: AxiosRequestConfig) => AxiosPromise<T>,
retryPolicy: RetryPolicy = retryOn5xxErrors
) => retry(() => request(args), retryPolicy)
export const apiConstructor = (configuration: APIConfiguration) => {
const {baseUrl, baseIntakeUrl, baseUnstableUrl, apiKey, appKey, proxyOpts} = configuration
const baseOptions = {apiKey, appKey, proxyOpts}
const request = getRequestBuilder({...baseOptions, baseUrl})
const requestUnstable = getRequestBuilder({...baseOptions, baseUrl: baseUnstableUrl})
const requestIntake = getRequestBuilder({...baseOptions, baseUrl: baseIntakeUrl})
return {
getBatch: getBatch(request),
getMobileApplicationPresignedURL: getMobileApplicationPresignedURL(requestUnstable),
getTest: getTest(request),
getTunnelPresignedURL: getTunnelPresignedURL(requestIntake),
pollResults: pollResults(request),
searchTests: searchTests(request),
triggerTests: triggerTests(requestIntake),
uploadMobileApplication: uploadMobileApplication(request),
}
}
export type APIHelper = ReturnType<typeof apiConstructor>
export const getApiHelper = (config: SyntheticsCIConfig): APIHelper => {
if (!config.appKey) {
throw new CriticalError('MISSING_APP_KEY')
}
if (!config.apiKey) {
throw new CriticalError('MISSING_API_KEY')
}
return apiConstructor({
apiKey: config.apiKey,
appKey: config.appKey,
baseIntakeUrl: getDatadogHost({useIntake: true, apiVersion: 'v1', config}),
baseUnstableUrl: getDatadogHost({useIntake: false, apiVersion: 'unstable', config}),
baseUrl: getDatadogHost({useIntake: false, apiVersion: 'v1', config}),
proxyOpts: config.proxy,
})
}