forked from renovatebot/renovate
/
index.ts
430 lines (384 loc) · 12.4 KB
/
index.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
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import merge from 'deepmerge';
import got, { Options, RequestError } from 'got';
import hasha from 'hasha';
import { infer as Infer, ZodType } from 'zod';
import { HOST_DISABLED } from '../../constants/error-messages';
import { pkg } from '../../expose.cjs';
import { logger } from '../../logger';
import { ExternalHostError } from '../../types/errors/external-host-error';
import * as memCache from '../cache/memory';
import { clone } from '../clone';
import { resolveBaseUrl } from '../url';
import { applyAuthorization, removeAuthorization } from './auth';
import { hooks } from './hooks';
import { applyHostRules } from './host-rules';
import { getQueue } from './queue';
import { getThrottle } from './throttle';
import type {
GotJSONOptions,
GotOptions,
HttpOptions,
HttpRequestOptions,
HttpResponse,
InternalHttpOptions,
RequestStats,
} from './types';
// TODO: refactor code to remove this (#9651)
import './legacy';
export { RequestError as HttpError };
type JsonArgs<
Opts extends HttpOptions & HttpRequestOptions<ResT>,
ResT = unknown,
Schema extends ZodType<ResT> = ZodType<ResT>
> = {
url: string;
httpOptions?: Opts;
schema?: Schema;
};
type Task<T> = () => Promise<HttpResponse<T>>;
function cloneResponse<T extends Buffer | string | any>(
response: HttpResponse<T>
): HttpResponse<T> {
const { body, statusCode, headers } = response;
// clone body and headers so that the cached result doesn't get accidentally mutated
// Don't use json clone for buffers
return {
statusCode,
body: body instanceof Buffer ? (body.slice() as T) : clone<T>(body),
headers: clone(headers),
authorization: !!response.authorization,
};
}
function applyDefaultHeaders(options: Options): void {
const renovateVersion = pkg.version;
options.headers = {
...options.headers,
'user-agent':
process.env.RENOVATE_USER_AGENT ??
`RenovateBot/${renovateVersion} (https://github.com/renovatebot/renovate)`,
};
}
// Note on types:
// options.requestType can be either 'json' or 'buffer', but `T` should be
// `Buffer` in the latter case.
// We don't declare overload signatures because it's immediately wrapped by
// `request`.
async function gotTask<T>(
url: string,
options: GotOptions,
requestStats: Omit<RequestStats, 'duration' | 'statusCode'>
): Promise<HttpResponse<T>> {
logger.trace({ url, options }, 'got request');
let duration = 0;
let statusCode = 0;
try {
// Cheat the TS compiler using `as` to pick a specific overload.
// Otherwise it doesn't typecheck.
const resp = await got<T>(url, { ...options, hooks } as GotJSONOptions);
statusCode = resp.statusCode;
duration =
resp.timings.phases.total ??
/* istanbul ignore next: can't be tested */ 0;
return resp;
} catch (error) {
if (error instanceof RequestError) {
statusCode =
error.response?.statusCode ??
/* istanbul ignore next: can't be tested */ -1;
duration =
error.timings?.phases.total ??
/* istanbul ignore next: can't be tested */ -1;
const method = options.method?.toUpperCase() ?? 'GET';
const code = error.code ?? 'UNKNOWN';
const retryCount = error.request?.retryCount ?? -1;
logger.debug(
`${method} ${url} = (code=${code}, statusCode=${statusCode} retryCount=${retryCount}, duration=${duration})`
);
}
throw error;
} finally {
const httpRequests = memCache.get<RequestStats[]>('http-requests') || [];
httpRequests.push({ ...requestStats, duration, statusCode });
memCache.set('http-requests', httpRequests);
}
}
export class Http<Opts extends HttpOptions = HttpOptions> {
private options?: GotOptions;
constructor(protected hostType: string, options: HttpOptions = {}) {
this.options = merge<GotOptions>(options, { context: { hostType } });
}
protected async request<T>(
requestUrl: string | URL,
httpOptions: InternalHttpOptions & HttpRequestOptions<T> = {}
): Promise<HttpResponse<T>> {
let url = requestUrl.toString();
if (httpOptions?.baseUrl) {
url = resolveBaseUrl(httpOptions.baseUrl, url);
}
let options: GotOptions = merge<GotOptions>(
{
method: 'get',
...this.options,
hostType: this.hostType,
},
httpOptions
);
const etagCache =
httpOptions.etagCache && options.method === 'get'
? httpOptions.etagCache
: null;
if (etagCache) {
options.headers = {
...options.headers,
'If-None-Match': etagCache.etag,
};
}
if (process.env.NODE_ENV === 'test') {
options.retry = 0;
}
options.hooks = {
beforeRedirect: [removeAuthorization],
};
applyDefaultHeaders(options);
options = applyHostRules(url, options);
if (options.enabled === false) {
logger.debug(`Host is disabled - rejecting request. HostUrl: ${url}`);
throw new Error(HOST_DISABLED);
}
options = applyAuthorization(options);
// use sha512: https://www.npmjs.com/package/hasha#algorithm
const memCacheKey =
options.memCache !== false &&
(options.method === 'get' || options.method === 'head')
? hasha([
'got-',
JSON.stringify({
url,
headers: options.headers,
method: options.method,
}),
])
: null;
let resPromise: Promise<HttpResponse<T>> | null = null;
// Cache GET requests unless memCache=false
if (memCacheKey) {
resPromise = memCache.get(memCacheKey);
}
// istanbul ignore else: no cache tests
if (!resPromise) {
const startTime = Date.now();
const httpTask: Task<T> = () => {
const queueDuration = Date.now() - startTime;
return gotTask(url, options, {
method: options.method ?? 'get',
url,
queueDuration,
});
};
const throttle = getThrottle(url);
const throttledTask: Task<T> = throttle
? () => throttle.add<HttpResponse<T>>(httpTask)
: httpTask;
const queue = getQueue(url);
const queuedTask: Task<T> = queue
? () => queue.add<HttpResponse<T>>(throttledTask)
: throttledTask;
resPromise = queuedTask();
if (memCacheKey) {
memCache.set(memCacheKey, resPromise);
}
}
try {
const res = memCacheKey
? cloneResponse(await resPromise)
: await resPromise;
res.authorization = !!options?.headers?.authorization;
if (etagCache && res.statusCode === 304) {
res.body = clone(etagCache.data);
}
return res;
} catch (err) {
const { abortOnError, abortIgnoreStatusCodes } = options;
if (abortOnError && !abortIgnoreStatusCodes?.includes(err.statusCode)) {
throw new ExternalHostError(err);
}
throw err;
}
}
get(
url: string,
options: HttpOptions & HttpRequestOptions<string> = {}
): Promise<HttpResponse> {
return this.request<string>(url, options);
}
head(url: string, options: HttpOptions = {}): Promise<HttpResponse> {
return this.request<string>(url, { ...options, method: 'head' });
}
getBuffer(
url: string,
options: HttpOptions = {}
): Promise<HttpResponse<Buffer>> {
return this.request<Buffer>(url, {
...options,
responseType: 'buffer',
});
}
private async requestJson<ResT = unknown>(
method: InternalHttpOptions['method'],
{ url, httpOptions: requestOptions, schema }: JsonArgs<Opts, ResT>
): Promise<HttpResponse<ResT>> {
const { body, ...httpOptions } = { ...requestOptions };
const opts: InternalHttpOptions = {
...httpOptions,
method,
responseType: 'json',
};
// signal that we expect a json response
opts.headers = {
accept: 'application/json',
...opts.headers,
};
if (body) {
opts.json = body;
}
const res = await this.request<ResT>(url, opts);
if (!schema) {
return res;
}
res.body = await schema.parseAsync(res.body);
return res;
}
private resolveArgs<ResT = unknown>(
arg1: string,
arg2: Opts | ZodType<ResT> | undefined,
arg3: ZodType<ResT> | undefined
): JsonArgs<Opts, ResT> {
const res: JsonArgs<Opts, ResT> = { url: arg1 };
if (arg2 instanceof ZodType<ResT>) {
res.schema = arg2;
} else if (arg2) {
res.httpOptions = arg2;
}
if (arg3) {
res.schema = arg3;
}
return res;
}
getJson<ResT>(
url: string,
options?: Opts & HttpRequestOptions<ResT>
): Promise<HttpResponse<ResT>>;
getJson<ResT, Schema extends ZodType<ResT> = ZodType<ResT>>(
url: string,
schema: Schema
): Promise<HttpResponse<Infer<Schema>>>;
getJson<ResT, Schema extends ZodType<ResT> = ZodType<ResT>>(
url: string,
options: Opts & HttpRequestOptions<Infer<Schema>>,
schema: Schema
): Promise<HttpResponse<Infer<Schema>>>;
getJson<ResT = unknown, Schema extends ZodType<ResT> = ZodType<ResT>>(
arg1: string,
arg2?: (Opts & HttpRequestOptions<ResT>) | Schema,
arg3?: Schema
): Promise<HttpResponse<ResT>> {
const args = this.resolveArgs<ResT>(arg1, arg2, arg3);
return this.requestJson<ResT>('get', args);
}
headJson(url: string, httpOptions?: Opts): Promise<HttpResponse<never>> {
return this.requestJson<never>('head', { url, httpOptions });
}
postJson<T>(url: string, options?: Opts): Promise<HttpResponse<T>>;
postJson<T, Schema extends ZodType<T> = ZodType<T>>(
url: string,
schema: Schema
): Promise<HttpResponse<Infer<Schema>>>;
postJson<T, Schema extends ZodType<T> = ZodType<T>>(
url: string,
options: Opts,
schema: Schema
): Promise<HttpResponse<Infer<Schema>>>;
postJson<T = unknown, Schema extends ZodType<T> = ZodType<T>>(
arg1: string,
arg2?: Opts | Schema,
arg3?: Schema
): Promise<HttpResponse<T>> {
const args = this.resolveArgs(arg1, arg2, arg3);
return this.requestJson<T>('post', args);
}
putJson<T>(url: string, options?: Opts): Promise<HttpResponse<T>>;
putJson<T, Schema extends ZodType<T> = ZodType<T>>(
url: string,
schema: Schema
): Promise<HttpResponse<Infer<Schema>>>;
putJson<T, Schema extends ZodType<T> = ZodType<T>>(
url: string,
options: Opts,
schema: Schema
): Promise<HttpResponse<Infer<Schema>>>;
putJson<T = unknown, Schema extends ZodType<T> = ZodType<T>>(
arg1: string,
arg2?: Opts | Schema,
arg3?: ZodType
): Promise<HttpResponse<T>> {
const args = this.resolveArgs(arg1, arg2, arg3);
return this.requestJson<T>('put', args);
}
patchJson<T>(url: string, options?: Opts): Promise<HttpResponse<T>>;
patchJson<T, Schema extends ZodType<T> = ZodType<T>>(
url: string,
schema: Schema
): Promise<HttpResponse<Infer<Schema>>>;
patchJson<T, Schema extends ZodType<T> = ZodType<T>>(
url: string,
options: Opts,
schema: Schema
): Promise<HttpResponse<Infer<Schema>>>;
patchJson<T = unknown, Schema extends ZodType<T> = ZodType<T>>(
arg1: string,
arg2?: Opts | Schema,
arg3?: Schema
): Promise<HttpResponse<T>> {
const args = this.resolveArgs(arg1, arg2, arg3);
return this.requestJson<T>('patch', args);
}
deleteJson<T>(url: string, options?: Opts): Promise<HttpResponse<T>>;
deleteJson<T, Schema extends ZodType<T> = ZodType<T>>(
url: string,
schema: Schema
): Promise<HttpResponse<Infer<Schema>>>;
deleteJson<T, Schema extends ZodType<T> = ZodType<T>>(
url: string,
options: Opts,
schema: Schema
): Promise<HttpResponse<Infer<Schema>>>;
deleteJson<T = unknown, Schema extends ZodType<T> = ZodType<T>>(
arg1: string,
arg2?: Opts | Schema,
arg3?: Schema
): Promise<HttpResponse<T>> {
const args = this.resolveArgs(arg1, arg2, arg3);
return this.requestJson<T>('delete', args);
}
stream(url: string, options?: HttpOptions): NodeJS.ReadableStream {
// TODO: fix types (#7154)
let combinedOptions: any = {
method: 'get',
...this.options,
hostType: this.hostType,
...options,
};
let resolvedUrl = url;
// istanbul ignore else: needs test
if (options?.baseUrl) {
resolvedUrl = resolveBaseUrl(options.baseUrl, url);
}
applyDefaultHeaders(combinedOptions);
combinedOptions = applyHostRules(resolvedUrl, combinedOptions);
if (combinedOptions.enabled === false) {
throw new Error(HOST_DISABLED);
}
combinedOptions = applyAuthorization(combinedOptions);
return got.stream(resolvedUrl, combinedOptions);
}
}