-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathweb.ts
More file actions
249 lines (220 loc) · 6.03 KB
/
web.ts
File metadata and controls
249 lines (220 loc) · 6.03 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
import dns from 'node:dns'
import { snakeCase } from 'snake-case'
import { request, setGlobalDispatcher, errors, Dispatcher } from 'undici'
import { version } from '../../package.json'
import {
IRequestHeaders,
IServiceParams,
PostResults,
PutResults,
UploaderArgs,
UploaderEnvs,
UploaderInputs,
} from '../types'
import { UploadLogger, info, logError } from './logger'
import { addProxyIfNeeded } from './proxy'
import { sleep } from './util'
const maxRetries = 4
const baseBackoffDelayMs = 1000 // Adjust this value based on your needs.
/**
*
* @param {Object} inputs
* @param {NodeJS.ProcessEnv} inputs.envs
* @param {Object} serviceParams
* @returns Object
*/
export function populateBuildParams(
inputs: UploaderInputs,
serviceParams: Partial<IServiceParams>,
): Partial<IServiceParams> {
const { args, envs } = inputs
serviceParams.name = args.name || envs.CODECOV_NAME || ''
serviceParams.tag = args.tag || ''
if (typeof args.flags === 'string') {
serviceParams.flags = args.flags
} else {
serviceParams.flags = args.flags.join(',')
}
serviceParams.parent = args.parent || ''
return serviceParams
}
export function getPackage(source: string): string {
if (source) {
return `${source}-uploader-${version}`
} else {
return `uploader-${version}`
}
}
async function requestWithRetry(
url: string,
options: Dispatcher.RequestOptions,
retryCount = 0,
): Promise<Dispatcher.ResponseData> {
try {
const response = await request(url, options)
return response
} catch (error: unknown) {
if (
((error instanceof errors.UndiciError && error.code == 'ECONNRESET') ||
error instanceof errors.ConnectTimeoutError ||
error instanceof errors.SocketError) &&
retryCount < maxRetries
) {
const backoffDelay = baseBackoffDelayMs * 2 ** retryCount
await sleep(backoffDelay)
UploadLogger.verbose('Request to Codecov failed. Retrying...')
logError(`Request error: ${error.message}`)
return requestWithRetry(url, options, retryCount + 1)
}
throw error
}
}
export async function uploadToCodecovPUT(
putAndResultUrlPair: PostResults,
uploadFile: string | Buffer,
envs: UploaderEnvs,
args: UploaderArgs,
): Promise<PutResults> {
info('Uploading...')
const requestHeaders = generateRequestHeadersPUT(
putAndResultUrlPair.putURL,
uploadFile,
envs,
args,
)
if (requestHeaders.agent) {
setGlobalDispatcher(requestHeaders.agent)
}
dns.setDefaultResultOrder('ipv4first')
const response = await requestWithRetry(
requestHeaders.url.origin,
requestHeaders.options,
)
if (response.statusCode !== 200) {
const data = await response.body.text()
throw new Error(
`There was an error fetching the storage URL during PUT: ${response.statusCode} - ${data}`,
)
}
return { status: 'success', resultURL: putAndResultUrlPair.resultURL }
}
export async function uploadToCodecovPOST(
postURL: URL,
token: string,
query: string,
source: string,
envs: UploaderEnvs,
args: UploaderArgs,
): Promise<string> {
const requestHeaders = generateRequestHeadersPOST(
postURL,
token,
query,
source,
envs,
args,
)
if (requestHeaders.agent) {
setGlobalDispatcher(requestHeaders.agent)
}
dns.setDefaultResultOrder('ipv4first')
const response = await requestWithRetry(
requestHeaders.url.origin,
requestHeaders.options,
)
if (response.statusCode !== 200) {
const data = await response.body.text()
throw new Error(
`There was an error fetching the storage URL during POST: ${response.statusCode} - ${data}`,
)
}
return await response.body.text()
}
/**
*
* @param {Object} queryParams
* @returns {string}
*/
export function generateQuery(queryParams: Partial<IServiceParams>): string {
return new URLSearchParams(
Object.entries(queryParams).map(([key, value]) => [snakeCase(key), value]),
).toString()
}
export function parsePOSTResults(putAndResultUrlPair: string): PostResults {
info(putAndResultUrlPair)
// JS for [[:graph:]] https://www.regular-expressions.info/posixbrackets.html
const re = /([\x21-\x7E]+)[\r\n]?/gm
const matches = putAndResultUrlPair.match(re)
if (matches === null) {
throw new Error(
`Parsing results from POST failed: (${putAndResultUrlPair})`,
)
}
if (matches?.length !== 2) {
throw new Error(
`Incorrect number of urls when parsing results from POST: ${matches.length}`,
)
}
if (matches[0] === undefined || matches[1] === undefined) {
throw new Error(
`Invalid URLs received when parsing results from POST: ${matches[0]},${matches[1]}`,
)
}
const resultURL = new URL(matches[0].trimEnd())
const putURL = new URL(matches[1])
// This match may have trailing 0x0A and 0x0D that must be trimmed
return { putURL, resultURL }
}
export function displayChangelog(): void {
info(`The change log for this version (v${version}) can be found at`)
info(`https://github.com/codecov/uploader/blob/v${version}/CHANGELOG.md`)
}
export function generateRequestHeadersPOST(
postURL: URL,
token: string,
query: string,
source: string,
envs: UploaderEnvs,
args: UploaderArgs,
): IRequestHeaders {
const url = new URL(
`upload/v4?package=${getPackage(source)}&token=${token}&${query}`,
postURL,
)
const headers = {
'X-Upload-Token': token,
'X-Reduced-Redundancy': 'false',
}
return {
agent: addProxyIfNeeded(envs, args),
url: url,
options: {
headers,
method: 'POST',
origin: postURL,
path: `${url.pathname}${url.search}`,
},
}
}
export function generateRequestHeadersPUT(
uploadURL: URL,
uploadFile: string | Buffer,
envs: UploaderEnvs,
args: UploaderArgs,
): IRequestHeaders {
const headers = {
'Content-Type': 'text/plain',
'Content-Encoding': 'gzip',
}
return {
agent: addProxyIfNeeded(envs, args),
url: uploadURL,
options: {
body: uploadFile,
headers,
method: 'PUT',
origin: uploadURL,
path: `${uploadURL.pathname}${uploadURL.search}`,
},
}
}