@rushstack/rush-http-build-cache-plugin 5.110.0 → 5.110.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.rush/temp/operation/_phase_build/all.log +6 -6
- package/.rush/temp/operation/_phase_build/state.json +1 -1
- package/.rush/temp/operation/_phase_test/all.log +15 -15
- package/.rush/temp/operation/_phase_test/state.json +1 -1
- package/.rush/temp/{rushstack+rush-http-build-cache-plugin-_phase_build-6123140279635b4e69641307e04c82615d4a5778.tar.log → rushstack+rush-http-build-cache-plugin-_phase_build-7ded7328886512873bc98eadea233c2110896df5.tar.log} +2 -2
- package/.rush/temp/rushstack+rush-http-build-cache-plugin-_phase_build-7ded7328886512873bc98eadea233c2110896df5.untar.log +10 -0
- package/.rush/temp/{rushstack+rush-http-build-cache-plugin-_phase_test-78333a9310f75472822f70554dee637804eb3b97.tar.log → rushstack+rush-http-build-cache-plugin-_phase_test-d4e616d587d138917981fe75858bc749b9e2b9a2.tar.log} +2 -2
- package/.rush/temp/rushstack+rush-http-build-cache-plugin-_phase_test-d4e616d587d138917981fe75858bc749b9e2b9a2.untar.log +10 -0
- package/README.md +116 -116
- package/config/jest.config.json +14 -14
- package/config/rig.json +18 -18
- package/coverage/HttpBuildCacheProvider.ts.html +1 -1
- package/coverage/RushHttpBuildCachePlugin.ts.html +1 -1
- package/coverage/cobertura-coverage.xml +5 -5
- package/coverage/index.html +1 -1
- package/coverage/index.ts.html +1 -1
- package/coverage/junit.xml +4 -4
- package/lib/HttpBuildCacheProvider.js.map +1 -1
- package/lib/RushHttpBuildCachePlugin.js.map +1 -1
- package/lib/index.js.map +1 -1
- package/lib/schemas/plugin-config.schema.json +52 -52
- package/lib/test/HttpBuildCacheProvider.test.js.map +1 -1
- package/package.json +5 -5
- package/rush-logs/rush-http-build-cache-plugin._phase_build.cache.log +8 -8
- package/rush-logs/rush-http-build-cache-plugin._phase_build.log +6 -6
- package/rush-logs/rush-http-build-cache-plugin._phase_test.cache.log +17 -17
- package/rush-logs/rush-http-build-cache-plugin._phase_test.log +15 -15
- package/rush-plugin-manifest.json +11 -11
- package/src/HttpBuildCacheProvider.ts +424 -424
- package/src/RushHttpBuildCachePlugin.ts +81 -81
- package/src/index.ts +4 -4
- package/src/schemas/plugin-config.schema.json +52 -52
- package/src/test/HttpBuildCacheProvider.test.ts +115 -115
- package/temp/build/typescript/ts_l9Fw4VUO.json +1 -1
- package/tsconfig.json +3 -3
- package/.rush/temp/rushstack+rush-http-build-cache-plugin-_phase_build-6123140279635b4e69641307e04c82615d4a5778.untar.log +0 -10
- package/.rush/temp/rushstack+rush-http-build-cache-plugin-_phase_test-78333a9310f75472822f70554dee637804eb3b97.untar.log +0 -10
|
@@ -1,424 +1,424 @@
|
|
|
1
|
-
import { ITerminal, Executable, Async } from '@rushstack/node-core-library';
|
|
2
|
-
import {
|
|
3
|
-
ICloudBuildCacheProvider,
|
|
4
|
-
ICredentialCacheEntry,
|
|
5
|
-
CredentialCache,
|
|
6
|
-
RushSession,
|
|
7
|
-
EnvironmentConfiguration
|
|
8
|
-
} from '@rushstack/rush-sdk';
|
|
9
|
-
import fetch, { BodyInit, Response } from 'node-fetch';
|
|
10
|
-
|
|
11
|
-
enum CredentialsOptions {
|
|
12
|
-
Optional,
|
|
13
|
-
Required,
|
|
14
|
-
Omit
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
enum FailureType {
|
|
18
|
-
None,
|
|
19
|
-
Informational,
|
|
20
|
-
Warning,
|
|
21
|
-
Error,
|
|
22
|
-
Authentication
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export interface IHttpBuildCacheTokenHandler {
|
|
26
|
-
exec: string;
|
|
27
|
-
args?: string[];
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* @public
|
|
32
|
-
*/
|
|
33
|
-
export interface IHttpBuildCacheProviderOptions {
|
|
34
|
-
url: string;
|
|
35
|
-
tokenHandler?: IHttpBuildCacheTokenHandler;
|
|
36
|
-
uploadMethod?: string;
|
|
37
|
-
minHttpRetryDelayMs?: number;
|
|
38
|
-
headers?: Record<string, string>;
|
|
39
|
-
cacheKeyPrefix?: string;
|
|
40
|
-
isCacheWriteAllowed: boolean;
|
|
41
|
-
pluginName: string;
|
|
42
|
-
rushJsonFolder: string;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
const MAX_HTTP_CACHE_ATTEMPTS: number = 3;
|
|
46
|
-
const DEFAULT_MIN_HTTP_RETRY_DELAY_MS = 2500;
|
|
47
|
-
|
|
48
|
-
export class HttpBuildCacheProvider implements ICloudBuildCacheProvider {
|
|
49
|
-
private readonly _pluginName: string;
|
|
50
|
-
private readonly _rushProjectRoot: string;
|
|
51
|
-
private readonly _environmentCredential: string | undefined;
|
|
52
|
-
private readonly _isCacheWriteAllowedByConfiguration: boolean;
|
|
53
|
-
private readonly _url: URL;
|
|
54
|
-
private readonly _uploadMethod: string;
|
|
55
|
-
private readonly _headers: Record<string, string>;
|
|
56
|
-
private readonly _cacheKeyPrefix: string;
|
|
57
|
-
private readonly _tokenHandler: IHttpBuildCacheTokenHandler | undefined;
|
|
58
|
-
private readonly _minHttpRetryDelayMs: number;
|
|
59
|
-
private __credentialCacheId: string | undefined;
|
|
60
|
-
|
|
61
|
-
public get isCacheWriteAllowed(): boolean {
|
|
62
|
-
return EnvironmentConfiguration.buildCacheWriteAllowed ?? this._isCacheWriteAllowedByConfiguration;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
public constructor(options: IHttpBuildCacheProviderOptions, rushSession: RushSession) {
|
|
66
|
-
this._pluginName = options.pluginName;
|
|
67
|
-
this._rushProjectRoot = options.rushJsonFolder;
|
|
68
|
-
|
|
69
|
-
this._environmentCredential = EnvironmentConfiguration.buildCacheCredential;
|
|
70
|
-
this._isCacheWriteAllowedByConfiguration = options.isCacheWriteAllowed;
|
|
71
|
-
this._url = new URL(options.url.endsWith('/') ? options.url : options.url + '/');
|
|
72
|
-
this._uploadMethod = options.uploadMethod ?? 'PUT';
|
|
73
|
-
this._headers = options.headers ?? {};
|
|
74
|
-
this._tokenHandler = options.tokenHandler;
|
|
75
|
-
this._cacheKeyPrefix = options.cacheKeyPrefix ?? '';
|
|
76
|
-
this._minHttpRetryDelayMs = options.minHttpRetryDelayMs ?? DEFAULT_MIN_HTTP_RETRY_DELAY_MS;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
public async tryGetCacheEntryBufferByIdAsync(
|
|
80
|
-
terminal: ITerminal,
|
|
81
|
-
cacheId: string
|
|
82
|
-
): Promise<Buffer | undefined> {
|
|
83
|
-
try {
|
|
84
|
-
const result = await this._http({
|
|
85
|
-
terminal: terminal,
|
|
86
|
-
relUrl: `${this._cacheKeyPrefix}${cacheId}`,
|
|
87
|
-
method: 'GET',
|
|
88
|
-
body: undefined,
|
|
89
|
-
warningText: 'Could not get cache entry',
|
|
90
|
-
readBody: true,
|
|
91
|
-
maxAttempts: MAX_HTTP_CACHE_ATTEMPTS
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
return Buffer.isBuffer(result) ? result : undefined;
|
|
95
|
-
} catch (e) {
|
|
96
|
-
terminal.writeWarningLine(`Error getting cache entry: ${e}`);
|
|
97
|
-
return undefined;
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
public async trySetCacheEntryBufferAsync(
|
|
102
|
-
terminal: ITerminal,
|
|
103
|
-
cacheId: string,
|
|
104
|
-
objectBuffer: Buffer
|
|
105
|
-
): Promise<boolean> {
|
|
106
|
-
if (!this.isCacheWriteAllowed) {
|
|
107
|
-
terminal.writeErrorLine('Writing to cache is not allowed in the current configuration.');
|
|
108
|
-
return false;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
terminal.writeDebugLine('Uploading object with cacheId: ', cacheId);
|
|
112
|
-
|
|
113
|
-
try {
|
|
114
|
-
const result = await this._http({
|
|
115
|
-
terminal: terminal,
|
|
116
|
-
relUrl: `${this._cacheKeyPrefix}${cacheId}`,
|
|
117
|
-
method: this._uploadMethod,
|
|
118
|
-
body: objectBuffer,
|
|
119
|
-
warningText: 'Could not write cache entry',
|
|
120
|
-
readBody: false,
|
|
121
|
-
maxAttempts: MAX_HTTP_CACHE_ATTEMPTS
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
return result !== false;
|
|
125
|
-
} catch (e) {
|
|
126
|
-
terminal.writeWarningLine(`Error uploading cache entry: ${e}`);
|
|
127
|
-
return false;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
public async updateCachedCredentialAsync(terminal: ITerminal, credential: string): Promise<void> {
|
|
132
|
-
await CredentialCache.usingAsync(
|
|
133
|
-
{
|
|
134
|
-
supportEditing: true
|
|
135
|
-
},
|
|
136
|
-
async (credentialsCache: CredentialCache) => {
|
|
137
|
-
credentialsCache.setCacheEntry(this._credentialCacheId, {
|
|
138
|
-
credential: credential
|
|
139
|
-
});
|
|
140
|
-
await credentialsCache.saveIfModifiedAsync();
|
|
141
|
-
}
|
|
142
|
-
);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
public async updateCachedCredentialInteractiveAsync(terminal: ITerminal): Promise<void> {
|
|
146
|
-
if (!this._tokenHandler) {
|
|
147
|
-
throw new Error(
|
|
148
|
-
`The interactive cloud credentials flow is not configured.\n` +
|
|
149
|
-
`Set the 'tokenHandler' setting in 'common/config/rush-plugins/${this._pluginName}.json' to a command that writes your credentials to standard output and exits with code 0 ` +
|
|
150
|
-
`or provide your credentials to rush using the --credential flag instead. Credentials must be the ` +
|
|
151
|
-
`'Authorization' header expected by ${this._url.href}`
|
|
152
|
-
);
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
const cmd: string = `${this._tokenHandler.exec} ${(this._tokenHandler.args || []).join(' ')}`;
|
|
156
|
-
terminal.writeVerboseLine(`Running '${cmd}' to get credentials`);
|
|
157
|
-
const result = Executable.spawnSync(this._tokenHandler.exec, this._tokenHandler.args || [], {
|
|
158
|
-
currentWorkingDirectory: this._rushProjectRoot
|
|
159
|
-
});
|
|
160
|
-
|
|
161
|
-
terminal.writeErrorLine(result.stderr);
|
|
162
|
-
|
|
163
|
-
if (result.error) {
|
|
164
|
-
throw new Error(`Could not obtain credentials. The command '${cmd}' failed.`);
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
const credential = result.stdout.trim();
|
|
168
|
-
terminal.writeVerboseLine('Got credentials');
|
|
169
|
-
|
|
170
|
-
await this.updateCachedCredentialAsync(terminal, credential);
|
|
171
|
-
|
|
172
|
-
terminal.writeLine('Updated credentials cache');
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
public async deleteCachedCredentialsAsync(terminal: ITerminal): Promise<void> {
|
|
176
|
-
await CredentialCache.usingAsync(
|
|
177
|
-
{
|
|
178
|
-
supportEditing: true
|
|
179
|
-
},
|
|
180
|
-
async (credentialsCache: CredentialCache) => {
|
|
181
|
-
credentialsCache.deleteCacheEntry(this._credentialCacheId);
|
|
182
|
-
await credentialsCache.saveIfModifiedAsync();
|
|
183
|
-
}
|
|
184
|
-
);
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
private get _credentialCacheId(): string {
|
|
188
|
-
if (!this.__credentialCacheId) {
|
|
189
|
-
const cacheIdParts: string[] = [this._url.href];
|
|
190
|
-
|
|
191
|
-
if (this._isCacheWriteAllowedByConfiguration) {
|
|
192
|
-
cacheIdParts.push('cacheWriteAllowed');
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
this.__credentialCacheId = cacheIdParts.join('|');
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
return this.__credentialCacheId;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
private async _http(options: {
|
|
202
|
-
terminal: ITerminal;
|
|
203
|
-
relUrl: string;
|
|
204
|
-
method: string;
|
|
205
|
-
body: BodyInit | undefined;
|
|
206
|
-
warningText: string;
|
|
207
|
-
readBody: boolean;
|
|
208
|
-
maxAttempts: number;
|
|
209
|
-
credentialOptions?: CredentialsOptions;
|
|
210
|
-
}): Promise<Buffer | boolean> {
|
|
211
|
-
const { terminal, relUrl, method, body, warningText, readBody, credentialOptions } = options;
|
|
212
|
-
const safeCredentialOptions = credentialOptions ?? CredentialsOptions.Optional;
|
|
213
|
-
const credentials = await this._tryGetCredentials(safeCredentialOptions);
|
|
214
|
-
const url = new URL(relUrl, this._url).href;
|
|
215
|
-
|
|
216
|
-
const headers: Record<string, string> = {};
|
|
217
|
-
if (typeof credentials === 'string') {
|
|
218
|
-
headers.Authorization = credentials;
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
for (const [key, value] of Object.entries(this._headers)) {
|
|
222
|
-
if (typeof value === 'string') {
|
|
223
|
-
headers[key] = value;
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
const bodyLength = (body as { length: number })?.length || 'unknown';
|
|
228
|
-
|
|
229
|
-
terminal.writeDebugLine(`[http-build-cache] request: ${method} ${url} ${bodyLength} bytes`);
|
|
230
|
-
|
|
231
|
-
const response = await fetch(url, {
|
|
232
|
-
method: method,
|
|
233
|
-
headers: headers,
|
|
234
|
-
body: body,
|
|
235
|
-
redirect: 'follow'
|
|
236
|
-
});
|
|
237
|
-
|
|
238
|
-
if (!response.ok) {
|
|
239
|
-
const isNonCredentialResponse = response.status >= 500 && response.status < 600;
|
|
240
|
-
|
|
241
|
-
if (
|
|
242
|
-
!isNonCredentialResponse &&
|
|
243
|
-
typeof credentials !== 'string' &&
|
|
244
|
-
safeCredentialOptions === CredentialsOptions.Optional
|
|
245
|
-
) {
|
|
246
|
-
// If we don't already have credentials yet, and we got a response from the server
|
|
247
|
-
// that is a "normal" failure (4xx), then we assume that credentials are probably
|
|
248
|
-
// required. Re-attempt the request, requiring credentials this time.
|
|
249
|
-
//
|
|
250
|
-
// This counts as part of the "first attempt", so it is not included in the max attempts
|
|
251
|
-
return await this._http({ ...options, credentialOptions: CredentialsOptions.Required });
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
if (options.maxAttempts > 1) {
|
|
255
|
-
// Pause a bit before retrying in case the server is busy
|
|
256
|
-
// Add some random jitter to the retry so we can spread out load on the remote service
|
|
257
|
-
// A proper solution might add exponential back off in case the retry count is high (10 or more)
|
|
258
|
-
const factor = 1.0 + Math.random(); // A random number between 1.0 and 2.0
|
|
259
|
-
const retryDelay = Math.floor(factor * this._minHttpRetryDelayMs);
|
|
260
|
-
|
|
261
|
-
await Async.sleep(retryDelay);
|
|
262
|
-
|
|
263
|
-
return await this._http({ ...options, maxAttempts: options.maxAttempts - 1 });
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
this._reportFailure(terminal, method, response, false, warningText);
|
|
267
|
-
return false;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
const result: Buffer | boolean = readBody ? Buffer.from(await response.arrayBuffer()) : true;
|
|
271
|
-
|
|
272
|
-
terminal.writeDebugLine(
|
|
273
|
-
`[http-build-cache] actual response: ${response.status} ${url} ${
|
|
274
|
-
result === true ? 'true' : result.length
|
|
275
|
-
} bytes`
|
|
276
|
-
);
|
|
277
|
-
|
|
278
|
-
return result;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
private async _tryGetCredentials(options: CredentialsOptions.Required): Promise<string>;
|
|
282
|
-
private async _tryGetCredentials(options: CredentialsOptions.Optional): Promise<string | undefined>;
|
|
283
|
-
private async _tryGetCredentials(options: CredentialsOptions.Omit): Promise<undefined>;
|
|
284
|
-
private async _tryGetCredentials(options: CredentialsOptions): Promise<string | undefined>;
|
|
285
|
-
private async _tryGetCredentials(options: CredentialsOptions): Promise<string | undefined> {
|
|
286
|
-
if (options === CredentialsOptions.Omit) {
|
|
287
|
-
return;
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
let credentials: string | undefined = this._environmentCredential;
|
|
291
|
-
|
|
292
|
-
if (credentials === undefined) {
|
|
293
|
-
credentials = await this._tryGetCredentialsFromCache();
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
if (typeof credentials !== 'string' && options === CredentialsOptions.Required) {
|
|
297
|
-
throw new Error(
|
|
298
|
-
[
|
|
299
|
-
`Credentials for ${this._url.href} have not been provided.`,
|
|
300
|
-
`In CI, verify that RUSH_BUILD_CACHE_CREDENTIAL contains a valid Authorization header value.`,
|
|
301
|
-
``,
|
|
302
|
-
`For local developers, run:`,
|
|
303
|
-
``,
|
|
304
|
-
` rush update-cloud-credentials --interactive`,
|
|
305
|
-
``
|
|
306
|
-
].join('\n')
|
|
307
|
-
);
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
return credentials;
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
private async _tryGetCredentialsFromCache(): Promise<string | undefined> {
|
|
314
|
-
let cacheEntry: ICredentialCacheEntry | undefined;
|
|
315
|
-
|
|
316
|
-
await CredentialCache.usingAsync(
|
|
317
|
-
{
|
|
318
|
-
supportEditing: false
|
|
319
|
-
},
|
|
320
|
-
(credentialsCache: CredentialCache) => {
|
|
321
|
-
cacheEntry = credentialsCache.tryGetCacheEntry(this._credentialCacheId);
|
|
322
|
-
}
|
|
323
|
-
);
|
|
324
|
-
|
|
325
|
-
if (cacheEntry) {
|
|
326
|
-
const expirationTime: number | undefined = cacheEntry.expires?.getTime();
|
|
327
|
-
if (!expirationTime || expirationTime >= Date.now()) {
|
|
328
|
-
return cacheEntry.credential;
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
private _getFailureType(requestMethod: string, response: Response, isRedirect: boolean): FailureType {
|
|
334
|
-
if (response.ok) {
|
|
335
|
-
return FailureType.None;
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
switch (response.status) {
|
|
339
|
-
case 503: {
|
|
340
|
-
// We select 503 specifically because this represents "service unavailable" and
|
|
341
|
-
// "rate limit throttle" errors, which are transient issues.
|
|
342
|
-
//
|
|
343
|
-
// There are other 5xx errors, such as 501, that can occur if the request is
|
|
344
|
-
// malformed, so as a general rule we want to let through other 5xx errors
|
|
345
|
-
// so the user can troubleshoot.
|
|
346
|
-
|
|
347
|
-
// Don't fail production builds with warnings for transient issues
|
|
348
|
-
return FailureType.Informational;
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
case 401:
|
|
352
|
-
case 403:
|
|
353
|
-
case 407: {
|
|
354
|
-
if (requestMethod === 'GET' && (isRedirect || response.redirected)) {
|
|
355
|
-
// Cache misses for GET requests are not errors
|
|
356
|
-
// This is a workaround behavior where a server can issue a redirect and we fail to authenticate at the new location.
|
|
357
|
-
// We do not want to signal this as an authentication failure because the authorization header is not passed on to redirects.
|
|
358
|
-
// i.e The authentication header was accepted for the first request and therefore subsequent failures
|
|
359
|
-
// where it was not present should not be attributed to the header.
|
|
360
|
-
// This scenario usually comes up with services that redirect to pre-signed URLS that don't actually exist.
|
|
361
|
-
// Those services then usually treat the 404 as a 403 to prevent leaking information.
|
|
362
|
-
return FailureType.None;
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
return FailureType.Authentication;
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
case 404: {
|
|
369
|
-
if (requestMethod === 'GET') {
|
|
370
|
-
// Cache misses for GET requests are not errors
|
|
371
|
-
return FailureType.None;
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
// Let dev builds succeed, let Prod builds fail
|
|
377
|
-
return FailureType.Warning;
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
private _reportFailure(
|
|
381
|
-
terminal: ITerminal,
|
|
382
|
-
requestMethod: string,
|
|
383
|
-
response: Response,
|
|
384
|
-
isRedirect: boolean,
|
|
385
|
-
message: string
|
|
386
|
-
): void {
|
|
387
|
-
switch (this._getFailureType(requestMethod, response, isRedirect)) {
|
|
388
|
-
default: {
|
|
389
|
-
terminal.writeErrorLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
|
|
390
|
-
break;
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
case FailureType.Warning: {
|
|
394
|
-
terminal.writeWarningLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
|
|
395
|
-
break;
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
case FailureType.Informational: {
|
|
399
|
-
terminal.writeLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
|
|
400
|
-
break;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
case FailureType.None: {
|
|
404
|
-
terminal.writeDebugLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
|
|
405
|
-
break;
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
case FailureType.Authentication: {
|
|
409
|
-
throw new Error(
|
|
410
|
-
[
|
|
411
|
-
`${this._url.href} responded with ${response.status}: ${response.statusText}.`,
|
|
412
|
-
`Credentials may be misconfigured or have expired.`,
|
|
413
|
-
`In CI, verify that RUSH_BUILD_CACHE_CREDENTIAL contains a valid Authorization header value.`,
|
|
414
|
-
``,
|
|
415
|
-
`For local developers, run:`,
|
|
416
|
-
``,
|
|
417
|
-
` rush update-cloud-credentials --interactive`,
|
|
418
|
-
``
|
|
419
|
-
].join('\n')
|
|
420
|
-
);
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
}
|
|
1
|
+
import { ITerminal, Executable, Async } from '@rushstack/node-core-library';
|
|
2
|
+
import {
|
|
3
|
+
ICloudBuildCacheProvider,
|
|
4
|
+
ICredentialCacheEntry,
|
|
5
|
+
CredentialCache,
|
|
6
|
+
RushSession,
|
|
7
|
+
EnvironmentConfiguration
|
|
8
|
+
} from '@rushstack/rush-sdk';
|
|
9
|
+
import fetch, { BodyInit, Response } from 'node-fetch';
|
|
10
|
+
|
|
11
|
+
enum CredentialsOptions {
|
|
12
|
+
Optional,
|
|
13
|
+
Required,
|
|
14
|
+
Omit
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
enum FailureType {
|
|
18
|
+
None,
|
|
19
|
+
Informational,
|
|
20
|
+
Warning,
|
|
21
|
+
Error,
|
|
22
|
+
Authentication
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface IHttpBuildCacheTokenHandler {
|
|
26
|
+
exec: string;
|
|
27
|
+
args?: string[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @public
|
|
32
|
+
*/
|
|
33
|
+
export interface IHttpBuildCacheProviderOptions {
|
|
34
|
+
url: string;
|
|
35
|
+
tokenHandler?: IHttpBuildCacheTokenHandler;
|
|
36
|
+
uploadMethod?: string;
|
|
37
|
+
minHttpRetryDelayMs?: number;
|
|
38
|
+
headers?: Record<string, string>;
|
|
39
|
+
cacheKeyPrefix?: string;
|
|
40
|
+
isCacheWriteAllowed: boolean;
|
|
41
|
+
pluginName: string;
|
|
42
|
+
rushJsonFolder: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const MAX_HTTP_CACHE_ATTEMPTS: number = 3;
|
|
46
|
+
const DEFAULT_MIN_HTTP_RETRY_DELAY_MS = 2500;
|
|
47
|
+
|
|
48
|
+
export class HttpBuildCacheProvider implements ICloudBuildCacheProvider {
|
|
49
|
+
private readonly _pluginName: string;
|
|
50
|
+
private readonly _rushProjectRoot: string;
|
|
51
|
+
private readonly _environmentCredential: string | undefined;
|
|
52
|
+
private readonly _isCacheWriteAllowedByConfiguration: boolean;
|
|
53
|
+
private readonly _url: URL;
|
|
54
|
+
private readonly _uploadMethod: string;
|
|
55
|
+
private readonly _headers: Record<string, string>;
|
|
56
|
+
private readonly _cacheKeyPrefix: string;
|
|
57
|
+
private readonly _tokenHandler: IHttpBuildCacheTokenHandler | undefined;
|
|
58
|
+
private readonly _minHttpRetryDelayMs: number;
|
|
59
|
+
private __credentialCacheId: string | undefined;
|
|
60
|
+
|
|
61
|
+
public get isCacheWriteAllowed(): boolean {
|
|
62
|
+
return EnvironmentConfiguration.buildCacheWriteAllowed ?? this._isCacheWriteAllowedByConfiguration;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
public constructor(options: IHttpBuildCacheProviderOptions, rushSession: RushSession) {
|
|
66
|
+
this._pluginName = options.pluginName;
|
|
67
|
+
this._rushProjectRoot = options.rushJsonFolder;
|
|
68
|
+
|
|
69
|
+
this._environmentCredential = EnvironmentConfiguration.buildCacheCredential;
|
|
70
|
+
this._isCacheWriteAllowedByConfiguration = options.isCacheWriteAllowed;
|
|
71
|
+
this._url = new URL(options.url.endsWith('/') ? options.url : options.url + '/');
|
|
72
|
+
this._uploadMethod = options.uploadMethod ?? 'PUT';
|
|
73
|
+
this._headers = options.headers ?? {};
|
|
74
|
+
this._tokenHandler = options.tokenHandler;
|
|
75
|
+
this._cacheKeyPrefix = options.cacheKeyPrefix ?? '';
|
|
76
|
+
this._minHttpRetryDelayMs = options.minHttpRetryDelayMs ?? DEFAULT_MIN_HTTP_RETRY_DELAY_MS;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
public async tryGetCacheEntryBufferByIdAsync(
|
|
80
|
+
terminal: ITerminal,
|
|
81
|
+
cacheId: string
|
|
82
|
+
): Promise<Buffer | undefined> {
|
|
83
|
+
try {
|
|
84
|
+
const result = await this._http({
|
|
85
|
+
terminal: terminal,
|
|
86
|
+
relUrl: `${this._cacheKeyPrefix}${cacheId}`,
|
|
87
|
+
method: 'GET',
|
|
88
|
+
body: undefined,
|
|
89
|
+
warningText: 'Could not get cache entry',
|
|
90
|
+
readBody: true,
|
|
91
|
+
maxAttempts: MAX_HTTP_CACHE_ATTEMPTS
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
return Buffer.isBuffer(result) ? result : undefined;
|
|
95
|
+
} catch (e) {
|
|
96
|
+
terminal.writeWarningLine(`Error getting cache entry: ${e}`);
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
public async trySetCacheEntryBufferAsync(
|
|
102
|
+
terminal: ITerminal,
|
|
103
|
+
cacheId: string,
|
|
104
|
+
objectBuffer: Buffer
|
|
105
|
+
): Promise<boolean> {
|
|
106
|
+
if (!this.isCacheWriteAllowed) {
|
|
107
|
+
terminal.writeErrorLine('Writing to cache is not allowed in the current configuration.');
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
terminal.writeDebugLine('Uploading object with cacheId: ', cacheId);
|
|
112
|
+
|
|
113
|
+
try {
|
|
114
|
+
const result = await this._http({
|
|
115
|
+
terminal: terminal,
|
|
116
|
+
relUrl: `${this._cacheKeyPrefix}${cacheId}`,
|
|
117
|
+
method: this._uploadMethod,
|
|
118
|
+
body: objectBuffer,
|
|
119
|
+
warningText: 'Could not write cache entry',
|
|
120
|
+
readBody: false,
|
|
121
|
+
maxAttempts: MAX_HTTP_CACHE_ATTEMPTS
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
return result !== false;
|
|
125
|
+
} catch (e) {
|
|
126
|
+
terminal.writeWarningLine(`Error uploading cache entry: ${e}`);
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
public async updateCachedCredentialAsync(terminal: ITerminal, credential: string): Promise<void> {
|
|
132
|
+
await CredentialCache.usingAsync(
|
|
133
|
+
{
|
|
134
|
+
supportEditing: true
|
|
135
|
+
},
|
|
136
|
+
async (credentialsCache: CredentialCache) => {
|
|
137
|
+
credentialsCache.setCacheEntry(this._credentialCacheId, {
|
|
138
|
+
credential: credential
|
|
139
|
+
});
|
|
140
|
+
await credentialsCache.saveIfModifiedAsync();
|
|
141
|
+
}
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
public async updateCachedCredentialInteractiveAsync(terminal: ITerminal): Promise<void> {
|
|
146
|
+
if (!this._tokenHandler) {
|
|
147
|
+
throw new Error(
|
|
148
|
+
`The interactive cloud credentials flow is not configured.\n` +
|
|
149
|
+
`Set the 'tokenHandler' setting in 'common/config/rush-plugins/${this._pluginName}.json' to a command that writes your credentials to standard output and exits with code 0 ` +
|
|
150
|
+
`or provide your credentials to rush using the --credential flag instead. Credentials must be the ` +
|
|
151
|
+
`'Authorization' header expected by ${this._url.href}`
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const cmd: string = `${this._tokenHandler.exec} ${(this._tokenHandler.args || []).join(' ')}`;
|
|
156
|
+
terminal.writeVerboseLine(`Running '${cmd}' to get credentials`);
|
|
157
|
+
const result = Executable.spawnSync(this._tokenHandler.exec, this._tokenHandler.args || [], {
|
|
158
|
+
currentWorkingDirectory: this._rushProjectRoot
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
terminal.writeErrorLine(result.stderr);
|
|
162
|
+
|
|
163
|
+
if (result.error) {
|
|
164
|
+
throw new Error(`Could not obtain credentials. The command '${cmd}' failed.`);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const credential = result.stdout.trim();
|
|
168
|
+
terminal.writeVerboseLine('Got credentials');
|
|
169
|
+
|
|
170
|
+
await this.updateCachedCredentialAsync(terminal, credential);
|
|
171
|
+
|
|
172
|
+
terminal.writeLine('Updated credentials cache');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
public async deleteCachedCredentialsAsync(terminal: ITerminal): Promise<void> {
|
|
176
|
+
await CredentialCache.usingAsync(
|
|
177
|
+
{
|
|
178
|
+
supportEditing: true
|
|
179
|
+
},
|
|
180
|
+
async (credentialsCache: CredentialCache) => {
|
|
181
|
+
credentialsCache.deleteCacheEntry(this._credentialCacheId);
|
|
182
|
+
await credentialsCache.saveIfModifiedAsync();
|
|
183
|
+
}
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private get _credentialCacheId(): string {
|
|
188
|
+
if (!this.__credentialCacheId) {
|
|
189
|
+
const cacheIdParts: string[] = [this._url.href];
|
|
190
|
+
|
|
191
|
+
if (this._isCacheWriteAllowedByConfiguration) {
|
|
192
|
+
cacheIdParts.push('cacheWriteAllowed');
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
this.__credentialCacheId = cacheIdParts.join('|');
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return this.__credentialCacheId;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private async _http(options: {
|
|
202
|
+
terminal: ITerminal;
|
|
203
|
+
relUrl: string;
|
|
204
|
+
method: string;
|
|
205
|
+
body: BodyInit | undefined;
|
|
206
|
+
warningText: string;
|
|
207
|
+
readBody: boolean;
|
|
208
|
+
maxAttempts: number;
|
|
209
|
+
credentialOptions?: CredentialsOptions;
|
|
210
|
+
}): Promise<Buffer | boolean> {
|
|
211
|
+
const { terminal, relUrl, method, body, warningText, readBody, credentialOptions } = options;
|
|
212
|
+
const safeCredentialOptions = credentialOptions ?? CredentialsOptions.Optional;
|
|
213
|
+
const credentials = await this._tryGetCredentials(safeCredentialOptions);
|
|
214
|
+
const url = new URL(relUrl, this._url).href;
|
|
215
|
+
|
|
216
|
+
const headers: Record<string, string> = {};
|
|
217
|
+
if (typeof credentials === 'string') {
|
|
218
|
+
headers.Authorization = credentials;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
for (const [key, value] of Object.entries(this._headers)) {
|
|
222
|
+
if (typeof value === 'string') {
|
|
223
|
+
headers[key] = value;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const bodyLength = (body as { length: number })?.length || 'unknown';
|
|
228
|
+
|
|
229
|
+
terminal.writeDebugLine(`[http-build-cache] request: ${method} ${url} ${bodyLength} bytes`);
|
|
230
|
+
|
|
231
|
+
const response = await fetch(url, {
|
|
232
|
+
method: method,
|
|
233
|
+
headers: headers,
|
|
234
|
+
body: body,
|
|
235
|
+
redirect: 'follow'
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
if (!response.ok) {
|
|
239
|
+
const isNonCredentialResponse = response.status >= 500 && response.status < 600;
|
|
240
|
+
|
|
241
|
+
if (
|
|
242
|
+
!isNonCredentialResponse &&
|
|
243
|
+
typeof credentials !== 'string' &&
|
|
244
|
+
safeCredentialOptions === CredentialsOptions.Optional
|
|
245
|
+
) {
|
|
246
|
+
// If we don't already have credentials yet, and we got a response from the server
|
|
247
|
+
// that is a "normal" failure (4xx), then we assume that credentials are probably
|
|
248
|
+
// required. Re-attempt the request, requiring credentials this time.
|
|
249
|
+
//
|
|
250
|
+
// This counts as part of the "first attempt", so it is not included in the max attempts
|
|
251
|
+
return await this._http({ ...options, credentialOptions: CredentialsOptions.Required });
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (options.maxAttempts > 1) {
|
|
255
|
+
// Pause a bit before retrying in case the server is busy
|
|
256
|
+
// Add some random jitter to the retry so we can spread out load on the remote service
|
|
257
|
+
// A proper solution might add exponential back off in case the retry count is high (10 or more)
|
|
258
|
+
const factor = 1.0 + Math.random(); // A random number between 1.0 and 2.0
|
|
259
|
+
const retryDelay = Math.floor(factor * this._minHttpRetryDelayMs);
|
|
260
|
+
|
|
261
|
+
await Async.sleep(retryDelay);
|
|
262
|
+
|
|
263
|
+
return await this._http({ ...options, maxAttempts: options.maxAttempts - 1 });
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
this._reportFailure(terminal, method, response, false, warningText);
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const result: Buffer | boolean = readBody ? Buffer.from(await response.arrayBuffer()) : true;
|
|
271
|
+
|
|
272
|
+
terminal.writeDebugLine(
|
|
273
|
+
`[http-build-cache] actual response: ${response.status} ${url} ${
|
|
274
|
+
result === true ? 'true' : result.length
|
|
275
|
+
} bytes`
|
|
276
|
+
);
|
|
277
|
+
|
|
278
|
+
return result;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
private async _tryGetCredentials(options: CredentialsOptions.Required): Promise<string>;
|
|
282
|
+
private async _tryGetCredentials(options: CredentialsOptions.Optional): Promise<string | undefined>;
|
|
283
|
+
private async _tryGetCredentials(options: CredentialsOptions.Omit): Promise<undefined>;
|
|
284
|
+
private async _tryGetCredentials(options: CredentialsOptions): Promise<string | undefined>;
|
|
285
|
+
private async _tryGetCredentials(options: CredentialsOptions): Promise<string | undefined> {
|
|
286
|
+
if (options === CredentialsOptions.Omit) {
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
let credentials: string | undefined = this._environmentCredential;
|
|
291
|
+
|
|
292
|
+
if (credentials === undefined) {
|
|
293
|
+
credentials = await this._tryGetCredentialsFromCache();
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (typeof credentials !== 'string' && options === CredentialsOptions.Required) {
|
|
297
|
+
throw new Error(
|
|
298
|
+
[
|
|
299
|
+
`Credentials for ${this._url.href} have not been provided.`,
|
|
300
|
+
`In CI, verify that RUSH_BUILD_CACHE_CREDENTIAL contains a valid Authorization header value.`,
|
|
301
|
+
``,
|
|
302
|
+
`For local developers, run:`,
|
|
303
|
+
``,
|
|
304
|
+
` rush update-cloud-credentials --interactive`,
|
|
305
|
+
``
|
|
306
|
+
].join('\n')
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
return credentials;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
private async _tryGetCredentialsFromCache(): Promise<string | undefined> {
|
|
314
|
+
let cacheEntry: ICredentialCacheEntry | undefined;
|
|
315
|
+
|
|
316
|
+
await CredentialCache.usingAsync(
|
|
317
|
+
{
|
|
318
|
+
supportEditing: false
|
|
319
|
+
},
|
|
320
|
+
(credentialsCache: CredentialCache) => {
|
|
321
|
+
cacheEntry = credentialsCache.tryGetCacheEntry(this._credentialCacheId);
|
|
322
|
+
}
|
|
323
|
+
);
|
|
324
|
+
|
|
325
|
+
if (cacheEntry) {
|
|
326
|
+
const expirationTime: number | undefined = cacheEntry.expires?.getTime();
|
|
327
|
+
if (!expirationTime || expirationTime >= Date.now()) {
|
|
328
|
+
return cacheEntry.credential;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private _getFailureType(requestMethod: string, response: Response, isRedirect: boolean): FailureType {
|
|
334
|
+
if (response.ok) {
|
|
335
|
+
return FailureType.None;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
switch (response.status) {
|
|
339
|
+
case 503: {
|
|
340
|
+
// We select 503 specifically because this represents "service unavailable" and
|
|
341
|
+
// "rate limit throttle" errors, which are transient issues.
|
|
342
|
+
//
|
|
343
|
+
// There are other 5xx errors, such as 501, that can occur if the request is
|
|
344
|
+
// malformed, so as a general rule we want to let through other 5xx errors
|
|
345
|
+
// so the user can troubleshoot.
|
|
346
|
+
|
|
347
|
+
// Don't fail production builds with warnings for transient issues
|
|
348
|
+
return FailureType.Informational;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
case 401:
|
|
352
|
+
case 403:
|
|
353
|
+
case 407: {
|
|
354
|
+
if (requestMethod === 'GET' && (isRedirect || response.redirected)) {
|
|
355
|
+
// Cache misses for GET requests are not errors
|
|
356
|
+
// This is a workaround behavior where a server can issue a redirect and we fail to authenticate at the new location.
|
|
357
|
+
// We do not want to signal this as an authentication failure because the authorization header is not passed on to redirects.
|
|
358
|
+
// i.e The authentication header was accepted for the first request and therefore subsequent failures
|
|
359
|
+
// where it was not present should not be attributed to the header.
|
|
360
|
+
// This scenario usually comes up with services that redirect to pre-signed URLS that don't actually exist.
|
|
361
|
+
// Those services then usually treat the 404 as a 403 to prevent leaking information.
|
|
362
|
+
return FailureType.None;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
return FailureType.Authentication;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
case 404: {
|
|
369
|
+
if (requestMethod === 'GET') {
|
|
370
|
+
// Cache misses for GET requests are not errors
|
|
371
|
+
return FailureType.None;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// Let dev builds succeed, let Prod builds fail
|
|
377
|
+
return FailureType.Warning;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
private _reportFailure(
|
|
381
|
+
terminal: ITerminal,
|
|
382
|
+
requestMethod: string,
|
|
383
|
+
response: Response,
|
|
384
|
+
isRedirect: boolean,
|
|
385
|
+
message: string
|
|
386
|
+
): void {
|
|
387
|
+
switch (this._getFailureType(requestMethod, response, isRedirect)) {
|
|
388
|
+
default: {
|
|
389
|
+
terminal.writeErrorLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
|
|
390
|
+
break;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
case FailureType.Warning: {
|
|
394
|
+
terminal.writeWarningLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
|
|
395
|
+
break;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
case FailureType.Informational: {
|
|
399
|
+
terminal.writeLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
|
|
400
|
+
break;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
case FailureType.None: {
|
|
404
|
+
terminal.writeDebugLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
|
|
405
|
+
break;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
case FailureType.Authentication: {
|
|
409
|
+
throw new Error(
|
|
410
|
+
[
|
|
411
|
+
`${this._url.href} responded with ${response.status}: ${response.statusText}.`,
|
|
412
|
+
`Credentials may be misconfigured or have expired.`,
|
|
413
|
+
`In CI, verify that RUSH_BUILD_CACHE_CREDENTIAL contains a valid Authorization header value.`,
|
|
414
|
+
``,
|
|
415
|
+
`For local developers, run:`,
|
|
416
|
+
``,
|
|
417
|
+
` rush update-cloud-credentials --interactive`,
|
|
418
|
+
``
|
|
419
|
+
].join('\n')
|
|
420
|
+
);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|