-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathindex.ts
384 lines (366 loc) · 11.8 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
import is from '@sindresorhus/is';
import { dequal } from 'dequal';
import { HOST_DISABLED } from '../constants/error-messages';
import { logger } from '../logger';
import { ExternalHostError } from '../types/errors/external-host-error';
import * as memCache from '../util/cache/memory';
import * as packageCache from '../util/cache/package';
import { clone } from '../util/clone';
import { regEx } from '../util/regex';
import * as allVersioning from '../versioning';
import datasources from './api';
import { addMetaData } from './metadata';
import type {
DatasourceApi,
DigestConfig,
GetPkgReleasesConfig,
GetReleasesConfig,
Release,
ReleaseResult,
} from './types';
export * from './types';
export { isGetPkgReleasesConfig } from './common';
export const getDatasources = (): Map<string, DatasourceApi> => datasources;
export const getDatasourceList = (): string[] => Array.from(datasources.keys());
const cacheNamespace = 'datasource-releases';
function getDatasourceFor(datasource: string): DatasourceApi {
return datasources.get(datasource);
}
type GetReleasesInternalConfig = GetReleasesConfig & GetPkgReleasesConfig;
function logError(datasource, lookupName, err): void {
const { statusCode, code: errCode, url } = err;
if (statusCode === 404) {
logger.debug({ datasource, lookupName, url }, 'Datasource 404');
} else if (statusCode === 401 || statusCode === 403) {
logger.debug({ datasource, lookupName, url }, 'Datasource unauthorized');
} else if (errCode) {
logger.debug(
{ datasource, lookupName, url, errCode },
'Datasource connection error'
);
} else {
logger.debug({ datasource, lookupName, err }, 'Datasource unknown error');
}
}
async function getRegistryReleases(
datasource: DatasourceApi,
config: GetReleasesConfig,
registryUrl: string
): Promise<ReleaseResult> {
const cacheKey = `${datasource.id} ${registryUrl} ${config.lookupName}`;
if (datasource.caching) {
const cachedResult = await packageCache.get<ReleaseResult>(
cacheNamespace,
cacheKey
);
// istanbul ignore if
if (cachedResult) {
logger.debug({ cacheKey }, 'Returning cached datasource response');
return cachedResult;
}
}
const res = await datasource.getReleases({ ...config, registryUrl });
if (res?.releases.length) {
res.registryUrl ??= registryUrl;
}
// cache non-null responses unless marked as private
if (datasource.caching && res && !res.isPrivate) {
logger.trace({ cacheKey }, 'Caching datasource response');
const cacheMinutes = 15;
await packageCache.set(cacheNamespace, cacheKey, res, cacheMinutes);
}
return res;
}
function firstRegistry(
config: GetReleasesInternalConfig,
datasource: DatasourceApi,
registryUrls: string[]
): Promise<ReleaseResult> {
if (registryUrls.length > 1) {
logger.warn(
{ datasource: datasource.id, depName: config.depName, registryUrls },
'Excess registryUrls found for datasource lookup - using first configured only'
);
}
const registryUrl = registryUrls[0];
return getRegistryReleases(datasource, config, registryUrl);
}
async function huntRegistries(
config: GetReleasesInternalConfig,
datasource: DatasourceApi,
registryUrls: string[]
): Promise<ReleaseResult> {
let res: ReleaseResult;
let caughtError;
for (const registryUrl of registryUrls) {
try {
res = await getRegistryReleases(datasource, config, registryUrl);
if (res) {
break;
}
} catch (err) {
if (err instanceof ExternalHostError) {
throw err;
}
// We'll always save the last-thrown error
caughtError = err;
logger.trace({ err }, 'datasource hunt failure');
}
}
if (res) {
return res;
}
if (caughtError) {
throw caughtError;
}
return null;
}
async function mergeRegistries(
config: GetReleasesInternalConfig,
datasource: DatasourceApi,
registryUrls: string[]
): Promise<ReleaseResult> {
let combinedRes: ReleaseResult;
let caughtError;
for (const registryUrl of registryUrls) {
try {
const res = await getRegistryReleases(datasource, config, registryUrl);
if (res) {
if (combinedRes) {
for (const existingRelease of combinedRes.releases || []) {
existingRelease.registryUrl = combinedRes.registryUrl;
}
for (const additionalRelease of res.releases || []) {
additionalRelease.registryUrl = res.registryUrl;
}
combinedRes = { ...res, ...combinedRes };
delete combinedRes.registryUrl;
combinedRes.releases = [...combinedRes.releases, ...res.releases];
} else {
combinedRes = res;
}
}
} catch (err) {
if (err instanceof ExternalHostError) {
throw err;
}
// We'll always save the last-thrown error
caughtError = err;
logger.trace({ err }, 'datasource merge failure');
}
}
// De-duplicate releases
if (combinedRes?.releases?.length) {
const seenVersions = new Set<string>();
combinedRes.releases = combinedRes.releases.filter((release) => {
if (seenVersions.has(release.version)) {
return false;
}
seenVersions.add(release.version);
return true;
});
}
if (combinedRes) {
return combinedRes;
}
if (caughtError) {
throw caughtError;
}
return null;
}
function resolveRegistryUrls(
datasource: DatasourceApi,
extractedUrls: string[]
): string[] {
const { defaultRegistryUrls = [] } = datasource;
if (!datasource.customRegistrySupport) {
if (is.nonEmptyArray(extractedUrls)) {
logger.warn(
{ datasource: datasource.id, registryUrls: extractedUrls },
'Custom datasources are not allowed for this datasource and will be ignored'
);
}
return defaultRegistryUrls;
}
const customUrls = extractedUrls?.filter(Boolean);
let registryUrls: string[];
if (is.nonEmptyArray(customUrls)) {
registryUrls = [...customUrls];
} else {
registryUrls = [...defaultRegistryUrls];
}
return registryUrls.filter(Boolean);
}
export function getDefaultVersioning(datasourceName: string): string {
const datasource = getDatasourceFor(datasourceName);
return datasource.defaultVersioning || 'semver';
}
async function fetchReleases(
config: GetReleasesInternalConfig
): Promise<ReleaseResult | null> {
const { datasource: datasourceName } = config;
if (!datasourceName || getDatasourceFor(datasourceName) === undefined) {
logger.warn('Unknown datasource: ' + datasourceName);
return null;
}
const datasource = getDatasourceFor(datasourceName);
const registryUrls = resolveRegistryUrls(datasource, config.registryUrls);
let dep: ReleaseResult = null;
const registryStrategy = datasource.registryStrategy || 'hunt';
try {
if (is.nonEmptyArray(registryUrls)) {
if (registryStrategy === 'first') {
dep = await firstRegistry(config, datasource, registryUrls);
} else if (registryStrategy === 'hunt') {
dep = await huntRegistries(config, datasource, registryUrls);
} else if (registryStrategy === 'merge') {
dep = await mergeRegistries(config, datasource, registryUrls);
}
} else {
dep = await datasource.getReleases(config);
}
} catch (err) {
if (err.message === HOST_DISABLED || err.err?.message === HOST_DISABLED) {
return null;
}
if (err instanceof ExternalHostError) {
throw err;
}
logError(datasource.id, config.lookupName, err);
}
if (!dep || dequal(dep, { releases: [] })) {
return null;
}
addMetaData(dep, datasourceName, config.lookupName);
return dep;
}
function getRawReleases(
config: GetReleasesInternalConfig
): Promise<ReleaseResult | null> {
const { datasource, lookupName, registryUrls } = config;
const cacheKey = `${cacheNamespace}${datasource}${lookupName}${String(
registryUrls
)}`;
// By returning a Promise and reusing it, we should only fetch each package at most once
const cachedResult = memCache.get<Promise<ReleaseResult | null>>(cacheKey);
// istanbul ignore if
if (cachedResult !== undefined) {
return cachedResult;
}
const promisedRes = fetchReleases(config);
memCache.set(cacheKey, promisedRes);
return promisedRes;
}
export async function getPkgReleases(
config: GetPkgReleasesConfig
): Promise<ReleaseResult | null> {
if (!config.datasource) {
logger.warn('No datasource found');
return null;
}
const lookupName = config.lookupName || config.depName;
if (!lookupName) {
logger.error({ config }, 'Datasource getReleases without lookupName');
return null;
}
let res: ReleaseResult;
try {
res = clone(
await getRawReleases({
...config,
lookupName,
})
);
} catch (e) /* istanbul ignore next */ {
if (e instanceof ExternalHostError) {
e.hostType = config.datasource;
e.lookupName = lookupName;
}
throw e;
}
if (!res) {
return res;
}
if (config.extractVersion) {
const extractVersionRegEx = regEx(config.extractVersion);
res.releases = res.releases
.map((release) => {
const version = extractVersionRegEx.exec(release.version)?.groups
?.version;
if (version) {
return { ...release, version }; // overwrite version
}
return null; // filter out any we can't extract
})
.filter(Boolean);
}
// Use the datasource's default versioning if none is configured
const versioning =
config.versioning || getDefaultVersioning(config.datasource);
const version = allVersioning.get(versioning);
// Return a sorted list of valid Versions
function sortReleases(release1: Release, release2: Release): number {
return version.sortVersions(release1.version, release2.version);
}
if (res.releases) {
res.releases = res.releases
.filter((release) => version.isVersion(release.version))
.sort(sortReleases);
}
// Filter versions for uniqueness
res.releases = res.releases.filter(
(filterRelease, filterIndex) =>
res.releases.findIndex(
(findRelease) => findRelease.version === filterRelease.version
) === filterIndex
);
// Filter releases for compatibility
for (const [constraintName, constraintValue] of Object.entries(
config.constraints || {}
)) {
// Currently we only support if the constraint is a plain version
// TODO: Support range/range compatibility filtering #8476
if (version.isVersion(constraintValue)) {
res.releases = res.releases.filter((release) => {
if (!is.nonEmptyArray(release.constraints?.[constraintName])) {
// A release with no constraints is OK
return true;
}
return release.constraints[constraintName].some(
// If any of the release's constraints match, then it's OK
(releaseConstraint) =>
!releaseConstraint ||
version.matches(constraintValue, releaseConstraint)
);
});
}
}
// Strip constraints from releases result
res.releases.forEach((release) => {
delete release.constraints; // eslint-disable-line no-param-reassign
});
return res;
}
export function supportsDigests(config: DigestConfig): boolean {
return 'getDigest' in getDatasourceFor(config.datasource);
}
export function getDigest(
config: DigestConfig,
value?: string
): Promise<string | null> {
const datasource = getDatasourceFor(config.datasource);
const lookupName = config.lookupName || config.depName;
const registryUrls = resolveRegistryUrls(datasource, config.registryUrls);
return datasource.getDigest(
{ lookupName, registryUrl: registryUrls[0] },
value
);
}
export function getDefaultConfig(
datasource: string
): Promise<Record<string, unknown>> {
const loadedDatasource = getDatasourceFor(datasource);
return Promise.resolve<Record<string, unknown>>(
loadedDatasource?.defaultConfig || Object.create({})
);
}