-
Notifications
You must be signed in to change notification settings - Fork 250
Expand file tree
/
Copy pathhttp.ts
More file actions
265 lines (238 loc) · 8.7 KB
/
http.ts
File metadata and controls
265 lines (238 loc) · 8.7 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
/* eslint-disable @typescript-eslint/no-base-to-string */
import {dirname} from './path.js'
import {createFileWriteStream, fileExistsSync, mkdirSync, unlinkFileSync} from './fs.js'
import {runWithTimer} from './metadata.js'
import {maxRequestTimeForNetworkCallsMs, skipNetworkLevelRetry} from './environment.js'
import {httpsAgent, sanitizedHeadersOutput} from '../../private/node/api/headers.js'
import {sanitizeURL} from '../../private/node/api/urls.js'
import {outputContent, outputDebug, outputToken} from '../../public/node/output.js'
import {NetworkRetryBehaviour, simpleRequestWithDebugLog} from '../../private/node/api.js'
import {DEFAULT_MAX_TIME_MS} from '../../private/node/sleep-with-backoff.js'
import FormData from 'form-data'
import nodeFetch, {RequestInfo, RequestInit, Response} from 'node-fetch'
export {FetchError, Request, Response} from 'node-fetch'
/**
* Create a new FormData object.
*
* @returns A FormData object.
*/
export function formData(): FormData {
return new FormData()
}
type AbortSignal = RequestInit['signal']
type PresetFetchBehaviour = 'default' | 'non-blocking' | 'slow-request'
type AutomaticCancellationBehaviour =
| {
useAbortSignal: true
timeoutMs: number
}
| {
useAbortSignal: false
}
| {
useAbortSignal: AbortSignal | (() => AbortSignal)
}
export type RequestBehaviour = NetworkRetryBehaviour & AutomaticCancellationBehaviour
export type RequestModeInput = PresetFetchBehaviour | RequestBehaviour
/**
* Specify the behaviour of a network request.
*
* - default: Requests are automatically retried, and are subject to automatic cancellation if they're taking too long.
* This is generally desirable.
* - non-blocking: Requests are not retried if they fail with a network error, and are automatically cancelled if
* they're taking too long. This is good for throwaway requests, like polling or tracking.
* - slow-request: Requests are not retried if they fail with a network error, and are not automatically cancelled.
* This is good for slow requests that should be give the chance to complete, and are unlikely to be safe to retry.
*
* Some request behaviours may be de-activated by the environment, and this function takes care of that concern. You
* can also provide a customised request behaviour.
*
* @param preset - The preset to use.
* @param env - Process environment variables.
* @returns A request behaviour object.
*/
export function requestMode(
preset: RequestModeInput = 'default',
env: NodeJS.ProcessEnv = process.env,
): RequestBehaviour {
const networkLevelRetryIsSupported = !skipNetworkLevelRetry(env)
switch (preset) {
case 'default':
return {
useNetworkLevelRetry: networkLevelRetryIsSupported,
maxRetryTimeMs: DEFAULT_MAX_TIME_MS,
useAbortSignal: true,
timeoutMs: maxRequestTimeForNetworkCallsMs(env),
}
case 'non-blocking':
return {
useNetworkLevelRetry: false,
useAbortSignal: true,
timeoutMs: maxRequestTimeForNetworkCallsMs(env),
}
case 'slow-request':
return {
useNetworkLevelRetry: false,
useAbortSignal: false,
}
}
return {
...preset,
useNetworkLevelRetry: networkLevelRetryIsSupported && preset.useNetworkLevelRetry,
} as RequestBehaviour
}
interface FetchOptions {
url: RequestInfo
behaviour: RequestBehaviour
init?: RequestInit
logRequest: boolean
useHttpsAgent: boolean
}
/**
* Create an AbortSignal for automatic request cancellation, from a request behaviour.
*
* @param behaviour - The request behaviour.
* @returns An AbortSignal.
*/
export function abortSignalFromRequestBehaviour(behaviour: RequestBehaviour): AbortSignal {
let signal: AbortSignal
if (behaviour.useAbortSignal === true) {
signal = AbortSignal.timeout(behaviour.timeoutMs)
} else if (behaviour.useAbortSignal && typeof behaviour.useAbortSignal === 'function') {
signal = behaviour.useAbortSignal()
} else if (behaviour.useAbortSignal) {
signal = behaviour.useAbortSignal
}
return signal
}
async function innerFetch({url, behaviour, init, logRequest, useHttpsAgent}: FetchOptions): Promise<Response> {
if (logRequest) {
outputDebug(outputContent`Sending ${init?.method ?? 'GET'} request to URL ${sanitizeURL(url.toString())}
With request headers:
${sanitizedHeadersOutput((init?.headers ?? {}) as {[header: string]: string})}
`)
}
let agent: RequestInit['agent']
if (useHttpsAgent) {
agent = await httpsAgent()
}
const request = async () => {
// each time we make the request, we need to potentially reset the abort signal, as the request logic may make
// the same request multiple times.
let signal = abortSignalFromRequestBehaviour(behaviour)
// it's possible to provide a signal through the request's init structure.
if (init?.signal) {
signal = init.signal
}
return nodeFetch(url, {...init, agent, signal})
}
return runWithTimer('cmd_all_timing_network_ms')(async () => {
return simpleRequestWithDebugLog({
url: url.toString(),
request,
...behaviour,
})
})
}
/**
* An interface that abstracts way node-fetch. When Node has built-in
* support for "fetch" in the standard library, we can drop the node-fetch
* dependency from here.
* Note that we are exposing types from "node-fetch". The reason being is that
* they are consistent with the Web API so if we drop node-fetch in the future
* it won't require changes from the callers.
*
* The CLI's fetch function supports special behaviours, like automatic retries. These are disabled by default through
* this function.
*
* @param url - This defines the resource that you wish to fetch.
* @param init - An object containing any custom settings that you want to apply to the request.
* @param preferredBehaviour - A request behaviour object that overrides the default behaviour.
* @returns A promise that resolves with the response.
*/
export async function fetch(
url: RequestInfo,
init?: RequestInit,
preferredBehaviour?: RequestModeInput,
): Promise<Response> {
const options = {
url,
init,
logRequest: false,
useHttpsAgent: false,
// all special behaviours are disabled by default
behaviour: preferredBehaviour ? requestMode(preferredBehaviour) : requestMode('non-blocking'),
} as const
return innerFetch(options)
}
/**
* A fetch function to use with Shopify services. The function ensures the right
* TLS configuragion is used based on the environment in which the service is running
* (e.g. Local). NB: headers/auth are the responsibility of the caller.
*
* By default, the CLI's fetch function's special behaviours, like automatic retries, are enabled.
*
* @param url - This defines the resource that you wish to fetch.
* @param init - An object containing any custom settings that you want to apply to the request.
* @param preferredBehaviour - A request behaviour object that overrides the default behaviour.
* @returns A promise that resolves with the response.
*/
export async function shopifyFetch(
url: RequestInfo,
init?: RequestInit,
preferredBehaviour?: RequestModeInput,
): Promise<Response> {
const options = {
url,
init,
logRequest: true,
useHttpsAgent: true,
// special behaviours enabled by default
behaviour: preferredBehaviour ? requestMode(preferredBehaviour) : requestMode(),
}
return innerFetch(options)
}
/**
* Download a file from a URL to a local path.
*
* @param url - The URL to download from.
* @param to - The local path to download to.
* @returns - A promise that resolves with the local path.
*/
export function downloadFile(url: string, to: string): Promise<string> {
const sanitizedUrl = sanitizeURL(url)
outputDebug(`Downloading ${sanitizedUrl} to ${to}`)
return runWithTimer('cmd_all_timing_network_ms')(() => {
return new Promise<string>((resolve, reject) => {
if (!fileExistsSync(dirname(to))) {
mkdirSync(dirname(to))
}
const file = createFileWriteStream(to)
// if we can't remove the file for some reason (seen on windows), that's ok -- it's in a temporary directory
const tryToRemoveFile = () => {
try {
unlinkFileSync(to)
// eslint-disable-next-line no-catch-all/no-catch-all
} catch (err: unknown) {
outputDebug(outputContent`Failed to remove file ${outputToken.path(to)}: ${outputToken.raw(String(err))}`)
}
}
file.on('finish', () => {
file.close()
resolve(to)
})
file.on('error', (err) => {
tryToRemoveFile()
reject(err)
})
nodeFetch(url, {redirect: 'follow'})
.then((res) => {
res.body?.pipe(file)
})
.catch((err) => {
tryToRemoveFile()
reject(err)
})
})
})
}