@rushstack/rush-http-build-cache-plugin 5.167.0 → 5.169.0

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.
@@ -0,0 +1,295 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2
+ // See LICENSE in the project root for license information.
3
+ import { CredentialCache } from '@rushstack/credential-cache';
4
+ import { Executable, Async } from '@rushstack/node-core-library';
5
+ import { EnvironmentConfiguration } from '@rushstack/rush-sdk';
6
+ import { WebClient } from '@rushstack/rush-sdk/lib/utilities/WebClient';
7
+ var CredentialsOptions;
8
+ (function (CredentialsOptions) {
9
+ CredentialsOptions[CredentialsOptions["Optional"] = 0] = "Optional";
10
+ CredentialsOptions[CredentialsOptions["Required"] = 1] = "Required";
11
+ CredentialsOptions[CredentialsOptions["Omit"] = 2] = "Omit";
12
+ })(CredentialsOptions || (CredentialsOptions = {}));
13
+ var FailureType;
14
+ (function (FailureType) {
15
+ FailureType[FailureType["None"] = 0] = "None";
16
+ FailureType[FailureType["Informational"] = 1] = "Informational";
17
+ FailureType[FailureType["Warning"] = 2] = "Warning";
18
+ FailureType[FailureType["Error"] = 3] = "Error";
19
+ FailureType[FailureType["Authentication"] = 4] = "Authentication";
20
+ })(FailureType || (FailureType = {}));
21
+ const MAX_HTTP_CACHE_ATTEMPTS = 3;
22
+ const DEFAULT_MIN_HTTP_RETRY_DELAY_MS = 2500;
23
+ export class HttpBuildCacheProvider {
24
+ get isCacheWriteAllowed() {
25
+ var _a;
26
+ return (_a = EnvironmentConfiguration.buildCacheWriteAllowed) !== null && _a !== void 0 ? _a : this._isCacheWriteAllowedByConfiguration;
27
+ }
28
+ constructor(options, rushSession) {
29
+ var _a, _b, _c, _d;
30
+ this._pluginName = options.pluginName;
31
+ this._rushProjectRoot = options.rushJsonFolder;
32
+ this._environmentCredential = EnvironmentConfiguration.buildCacheCredential;
33
+ this._isCacheWriteAllowedByConfiguration = options.isCacheWriteAllowed;
34
+ this._url = new URL(options.url.endsWith('/') ? options.url : options.url + '/');
35
+ this._uploadMethod = (_a = options.uploadMethod) !== null && _a !== void 0 ? _a : 'PUT';
36
+ this._headers = (_b = options.headers) !== null && _b !== void 0 ? _b : {};
37
+ this._tokenHandler = options.tokenHandler;
38
+ this._cacheKeyPrefix = (_c = options.cacheKeyPrefix) !== null && _c !== void 0 ? _c : '';
39
+ this._minHttpRetryDelayMs = (_d = options.minHttpRetryDelayMs) !== null && _d !== void 0 ? _d : DEFAULT_MIN_HTTP_RETRY_DELAY_MS;
40
+ }
41
+ async tryGetCacheEntryBufferByIdAsync(terminal, cacheId) {
42
+ try {
43
+ const result = await this._makeHttpRequestAsync({
44
+ terminal: terminal,
45
+ relUrl: `${this._cacheKeyPrefix}${cacheId}`,
46
+ method: 'GET',
47
+ body: undefined,
48
+ warningText: 'Could not get cache entry',
49
+ readBody: true,
50
+ maxAttempts: MAX_HTTP_CACHE_ATTEMPTS
51
+ });
52
+ return Buffer.isBuffer(result) ? result : undefined;
53
+ }
54
+ catch (e) {
55
+ terminal.writeWarningLine(`Error getting cache entry: ${e}`);
56
+ return undefined;
57
+ }
58
+ }
59
+ async trySetCacheEntryBufferAsync(terminal, cacheId, objectBuffer) {
60
+ if (!this.isCacheWriteAllowed) {
61
+ terminal.writeErrorLine('Writing to cache is not allowed in the current configuration.');
62
+ return false;
63
+ }
64
+ terminal.writeDebugLine('Uploading object with cacheId: ', cacheId);
65
+ try {
66
+ const result = await this._makeHttpRequestAsync({
67
+ terminal: terminal,
68
+ relUrl: `${this._cacheKeyPrefix}${cacheId}`,
69
+ method: this._uploadMethod,
70
+ body: objectBuffer,
71
+ warningText: 'Could not write cache entry',
72
+ readBody: false,
73
+ maxAttempts: MAX_HTTP_CACHE_ATTEMPTS
74
+ });
75
+ return result !== false;
76
+ }
77
+ catch (e) {
78
+ terminal.writeWarningLine(`Error uploading cache entry: ${e}`);
79
+ return false;
80
+ }
81
+ }
82
+ async updateCachedCredentialAsync(terminal, credential) {
83
+ await CredentialCache.usingAsync({
84
+ supportEditing: true
85
+ }, async (credentialsCache) => {
86
+ credentialsCache.setCacheEntry(this._credentialCacheId, {
87
+ credential: credential
88
+ });
89
+ await credentialsCache.saveIfModifiedAsync();
90
+ });
91
+ }
92
+ async updateCachedCredentialInteractiveAsync(terminal) {
93
+ if (!this._tokenHandler) {
94
+ throw new Error(`The interactive cloud credentials flow is not configured.\n` +
95
+ `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 ` +
96
+ `or provide your credentials to rush using the --credential flag instead. Credentials must be the ` +
97
+ `'Authorization' header expected by ${this._url.href}`);
98
+ }
99
+ const cmd = `${this._tokenHandler.exec} ${(this._tokenHandler.args || []).join(' ')}`;
100
+ terminal.writeVerboseLine(`Running '${cmd}' to get credentials`);
101
+ const result = Executable.spawnSync(this._tokenHandler.exec, this._tokenHandler.args || [], {
102
+ currentWorkingDirectory: this._rushProjectRoot
103
+ });
104
+ terminal.writeErrorLine(result.stderr);
105
+ if (result.error) {
106
+ throw new Error(`Could not obtain credentials. The command '${cmd}' failed.`);
107
+ }
108
+ const credential = result.stdout.trim();
109
+ terminal.writeVerboseLine('Got credentials');
110
+ await this.updateCachedCredentialAsync(terminal, credential);
111
+ terminal.writeLine('Updated credentials cache');
112
+ }
113
+ async deleteCachedCredentialsAsync(terminal) {
114
+ await CredentialCache.usingAsync({
115
+ supportEditing: true
116
+ }, async (credentialsCache) => {
117
+ credentialsCache.deleteCacheEntry(this._credentialCacheId);
118
+ await credentialsCache.saveIfModifiedAsync();
119
+ });
120
+ }
121
+ get _credentialCacheId() {
122
+ if (!this.__credentialCacheId) {
123
+ const cacheIdParts = [this._url.href];
124
+ if (this._isCacheWriteAllowedByConfiguration) {
125
+ cacheIdParts.push('cacheWriteAllowed');
126
+ }
127
+ this.__credentialCacheId = cacheIdParts.join('|');
128
+ }
129
+ return this.__credentialCacheId;
130
+ }
131
+ async _makeHttpRequestAsync(options) {
132
+ const { terminal, relUrl, method, body, warningText, readBody, credentialOptions } = options;
133
+ const safeCredentialOptions = credentialOptions !== null && credentialOptions !== void 0 ? credentialOptions : CredentialsOptions.Optional;
134
+ const credentials = await this._tryGetCredentialsAsync(safeCredentialOptions);
135
+ const url = new URL(relUrl, this._url).href;
136
+ const headers = {};
137
+ if (typeof credentials === 'string') {
138
+ headers.Authorization = credentials;
139
+ }
140
+ for (const [key, value] of Object.entries(this._headers)) {
141
+ if (typeof value === 'string') {
142
+ headers[key] = value;
143
+ }
144
+ }
145
+ const bodyLength = (body === null || body === void 0 ? void 0 : body.length) || 'unknown';
146
+ terminal.writeDebugLine(`[http-build-cache] request: ${method} ${url} ${bodyLength} bytes`);
147
+ const webClient = new WebClient();
148
+ const response = await webClient.fetchAsync(url, {
149
+ verb: method,
150
+ headers: headers,
151
+ body: body,
152
+ redirect: 'follow',
153
+ timeoutMs: 0 // Use the default timeout
154
+ });
155
+ if (!response.ok) {
156
+ const isNonCredentialResponse = response.status >= 500 && response.status < 600;
157
+ if (!isNonCredentialResponse &&
158
+ typeof credentials !== 'string' &&
159
+ safeCredentialOptions === CredentialsOptions.Optional) {
160
+ // If we don't already have credentials yet, and we got a response from the server
161
+ // that is a "normal" failure (4xx), then we assume that credentials are probably
162
+ // required. Re-attempt the request, requiring credentials this time.
163
+ //
164
+ // This counts as part of the "first attempt", so it is not included in the max attempts
165
+ return await this._makeHttpRequestAsync({
166
+ ...options,
167
+ credentialOptions: CredentialsOptions.Required
168
+ });
169
+ }
170
+ if (options.maxAttempts > 1) {
171
+ // Pause a bit before retrying in case the server is busy
172
+ // Add some random jitter to the retry so we can spread out load on the remote service
173
+ // A proper solution might add exponential back off in case the retry count is high (10 or more)
174
+ const factor = 1.0 + Math.random(); // A random number between 1.0 and 2.0
175
+ const retryDelay = Math.floor(factor * this._minHttpRetryDelayMs);
176
+ await Async.sleepAsync(retryDelay);
177
+ return await this._makeHttpRequestAsync({ ...options, maxAttempts: options.maxAttempts - 1 });
178
+ }
179
+ this._reportFailure(terminal, method, response, false, warningText);
180
+ return false;
181
+ }
182
+ const result = readBody ? await response.getBufferAsync() : true;
183
+ terminal.writeDebugLine(`[http-build-cache] actual response: ${response.status} ${url} ${result === true ? 'true' : result.length} bytes`);
184
+ return result;
185
+ }
186
+ async _tryGetCredentialsAsync(options) {
187
+ if (options === CredentialsOptions.Omit) {
188
+ return;
189
+ }
190
+ let credentials = this._environmentCredential;
191
+ if (credentials === undefined) {
192
+ credentials = await this._tryGetCredentialsFromCacheAsync();
193
+ }
194
+ if (typeof credentials !== 'string' && options === CredentialsOptions.Required) {
195
+ throw new Error([
196
+ `Credentials for ${this._url.href} have not been provided.`,
197
+ `In CI, verify that RUSH_BUILD_CACHE_CREDENTIAL contains a valid Authorization header value.`,
198
+ ``,
199
+ `For local developers, run:`,
200
+ ``,
201
+ ` rush update-cloud-credentials --interactive`,
202
+ ``
203
+ ].join('\n'));
204
+ }
205
+ return credentials;
206
+ }
207
+ async _tryGetCredentialsFromCacheAsync() {
208
+ var _a;
209
+ let cacheEntry;
210
+ await CredentialCache.usingAsync({
211
+ supportEditing: false
212
+ }, (credentialsCache) => {
213
+ cacheEntry = credentialsCache.tryGetCacheEntry(this._credentialCacheId);
214
+ });
215
+ if (cacheEntry) {
216
+ const expirationTime = (_a = cacheEntry.expires) === null || _a === void 0 ? void 0 : _a.getTime();
217
+ if (!expirationTime || expirationTime >= Date.now()) {
218
+ return cacheEntry.credential;
219
+ }
220
+ }
221
+ }
222
+ _getFailureType(requestMethod, response, isRedirect) {
223
+ if (response.ok) {
224
+ return FailureType.None;
225
+ }
226
+ switch (response.status) {
227
+ case 503: {
228
+ // We select 503 specifically because this represents "service unavailable" and
229
+ // "rate limit throttle" errors, which are transient issues.
230
+ //
231
+ // There are other 5xx errors, such as 501, that can occur if the request is
232
+ // malformed, so as a general rule we want to let through other 5xx errors
233
+ // so the user can troubleshoot.
234
+ // Don't fail production builds with warnings for transient issues
235
+ return FailureType.Informational;
236
+ }
237
+ case 401:
238
+ case 403:
239
+ case 407: {
240
+ if (requestMethod === 'GET' && (isRedirect || response.redirected)) {
241
+ // Cache misses for GET requests are not errors
242
+ // This is a workaround behavior where a server can issue a redirect and we fail to authenticate at the new location.
243
+ // We do not want to signal this as an authentication failure because the authorization header is not passed on to redirects.
244
+ // i.e The authentication header was accepted for the first request and therefore subsequent failures
245
+ // where it was not present should not be attributed to the header.
246
+ // This scenario usually comes up with services that redirect to pre-signed URLS that don't actually exist.
247
+ // Those services then usually treat the 404 as a 403 to prevent leaking information.
248
+ return FailureType.None;
249
+ }
250
+ return FailureType.Authentication;
251
+ }
252
+ case 404: {
253
+ if (requestMethod === 'GET') {
254
+ // Cache misses for GET requests are not errors
255
+ return FailureType.None;
256
+ }
257
+ }
258
+ }
259
+ // Let dev builds succeed, let Prod builds fail
260
+ return FailureType.Warning;
261
+ }
262
+ _reportFailure(terminal, requestMethod, response, isRedirect, message) {
263
+ switch (this._getFailureType(requestMethod, response, isRedirect)) {
264
+ default: {
265
+ terminal.writeErrorLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
266
+ break;
267
+ }
268
+ case FailureType.Warning: {
269
+ terminal.writeWarningLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
270
+ break;
271
+ }
272
+ case FailureType.Informational: {
273
+ terminal.writeLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
274
+ break;
275
+ }
276
+ case FailureType.None: {
277
+ terminal.writeDebugLine(`${message}: HTTP ${response.status}: ${response.statusText}`);
278
+ break;
279
+ }
280
+ case FailureType.Authentication: {
281
+ throw new Error([
282
+ `${this._url.href} responded with ${response.status}: ${response.statusText}.`,
283
+ `Credentials may be misconfigured or have expired.`,
284
+ `In CI, verify that RUSH_BUILD_CACHE_CREDENTIAL contains a valid Authorization header value.`,
285
+ ``,
286
+ `For local developers, run:`,
287
+ ``,
288
+ ` rush update-cloud-credentials --interactive`,
289
+ ``
290
+ ].join('\n'));
291
+ }
292
+ }
293
+ }
294
+ }
295
+ //# sourceMappingURL=HttpBuildCacheProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HttpBuildCacheProvider.js","sourceRoot":"","sources":["../src/HttpBuildCacheProvider.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,2DAA2D;AAI3D,OAAO,EAA8B,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC1F,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAEjE,OAAO,EAGL,wBAAwB,EACzB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,SAAS,EAA2B,MAAM,6CAA6C,CAAC;AAEjG,IAAK,kBAIJ;AAJD,WAAK,kBAAkB;IACrB,mEAAQ,CAAA;IACR,mEAAQ,CAAA;IACR,2DAAI,CAAA;AACN,CAAC,EAJI,kBAAkB,KAAlB,kBAAkB,QAItB;AAED,IAAK,WAMJ;AAND,WAAK,WAAW;IACd,6CAAI,CAAA;IACJ,+DAAa,CAAA;IACb,mDAAO,CAAA;IACP,+CAAK,CAAA;IACL,iEAAc,CAAA;AAChB,CAAC,EANI,WAAW,KAAX,WAAW,QAMf;AA2BD,MAAM,uBAAuB,GAAW,CAAC,CAAC;AAC1C,MAAM,+BAA+B,GAAW,IAAI,CAAC;AAErD,MAAM,OAAO,sBAAsB;IAajC,IAAW,mBAAmB;;QAC5B,OAAO,MAAA,wBAAwB,CAAC,sBAAsB,mCAAI,IAAI,CAAC,mCAAmC,CAAC;IACrG,CAAC;IAED,YAAmB,OAAuC,EAAE,WAAwB;;QAClF,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;QACtC,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC,cAAc,CAAC;QAE/C,IAAI,CAAC,sBAAsB,GAAG,wBAAwB,CAAC,oBAAoB,CAAC;QAC5E,IAAI,CAAC,mCAAmC,GAAG,OAAO,CAAC,mBAAmB,CAAC;QACvE,IAAI,CAAC,IAAI,G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AC,CAAC;gBAChC,MAAM,IAAI,KAAK,CACb;oBACE,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,mBAAmB,QAAQ,CAAC,MAAM,KAAK,QAAQ,CAAC,UAAU,GAAG;oBAC9E,mDAAmD;oBACnD,6FAA6F;oBAC7F,EAAE;oBACF,4BAA4B;oBAC5B,EAAE;oBACF,iDAAiD;oBACjD,EAAE;iBACH,CAAC,IAAI,CAAC,IAAI,CAAC,CACb,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport type { SpawnSyncReturns } from 'node:child_process';\n\nimport { type ICredentialCacheEntry, CredentialCache } from '@rushstack/credential-cache';\nimport { Executable, Async } from '@rushstack/node-core-library';\nimport type { ITerminal } from '@rushstack/terminal';\nimport {\n type ICloudBuildCacheProvider,\n type RushSession,\n EnvironmentConfiguration\n} from '@rushstack/rush-sdk';\nimport { WebClient, type IWebClientResponse } from '@rushstack/rush-sdk/lib/utilities/WebClient';\n\nenum CredentialsOptions {\n Optional,\n Required,\n Omit\n}\n\nenum FailureType {\n None,\n Informational,\n Warning,\n Error,\n Authentication\n}\n\nexport interface IHttpBuildCacheTokenHandler {\n exec: string;\n args?: string[];\n}\n\n/**\n * @public\n */\nexport type UploadMethod = 'PUT' | 'POST' | 'PATCH';\n\n/**\n * @public\n */\nexport interface IHttpBuildCacheProviderOptions {\n url: string;\n tokenHandler?: IHttpBuildCacheTokenHandler;\n uploadMethod?: UploadMethod;\n minHttpRetryDelayMs?: number;\n headers?: Record<string, string>;\n cacheKeyPrefix?: string;\n isCacheWriteAllowed: boolean;\n pluginName: string;\n rushJsonFolder: string;\n}\n\nconst MAX_HTTP_CACHE_ATTEMPTS: number = 3;\nconst DEFAULT_MIN_HTTP_RETRY_DELAY_MS: number = 2500;\n\nexport class HttpBuildCacheProvider implements ICloudBuildCacheProvider {\n private readonly _pluginName: string;\n private readonly _rushProjectRoot: string;\n private readonly _environmentCredential: string | undefined;\n private readonly _isCacheWriteAllowedByConfiguration: boolean;\n private readonly _url: URL;\n private readonly _uploadMethod: UploadMethod;\n private readonly _headers: Record<string, string>;\n private readonly _cacheKeyPrefix: string;\n private readonly _tokenHandler: IHttpBuildCacheTokenHandler | undefined;\n private readonly _minHttpRetryDelayMs: number;\n private __credentialCacheId: string | undefined;\n\n public get isCacheWriteAllowed(): boolean {\n return EnvironmentConfiguration.buildCacheWriteAllowed ?? this._isCacheWriteAllowedByConfiguration;\n }\n\n public constructor(options: IHttpBuildCacheProviderOptions, rushSession: RushSession) {\n this._pluginName = options.pluginName;\n this._rushProjectRoot = options.rushJsonFolder;\n\n this._environmentCredential = EnvironmentConfiguration.buildCacheCredential;\n this._isCacheWriteAllowedByConfiguration = options.isCacheWriteAllowed;\n this._url = new URL(options.url.endsWith('/') ? options.url : options.url + '/');\n this._uploadMethod = options.uploadMethod ?? 'PUT';\n this._headers = options.headers ?? {};\n this._tokenHandler = options.tokenHandler;\n this._cacheKeyPrefix = options.cacheKeyPrefix ?? '';\n this._minHttpRetryDelayMs = options.minHttpRetryDelayMs ?? DEFAULT_MIN_HTTP_RETRY_DELAY_MS;\n }\n\n public async tryGetCacheEntryBufferByIdAsync(\n terminal: ITerminal,\n cacheId: string\n ): Promise<Buffer | undefined> {\n try {\n const result: boolean | Buffer = await this._makeHttpRequestAsync({\n terminal: terminal,\n relUrl: `${this._cacheKeyPrefix}${cacheId}`,\n method: 'GET',\n body: undefined,\n warningText: 'Could not get cache entry',\n readBody: true,\n maxAttempts: MAX_HTTP_CACHE_ATTEMPTS\n });\n\n return Buffer.isBuffer(result) ? result : undefined;\n } catch (e) {\n terminal.writeWarningLine(`Error getting cache entry: ${e}`);\n return undefined;\n }\n }\n\n public async trySetCacheEntryBufferAsync(\n terminal: ITerminal,\n cacheId: string,\n objectBuffer: Buffer\n ): Promise<boolean> {\n if (!this.isCacheWriteAllowed) {\n terminal.writeErrorLine('Writing to cache is not allowed in the current configuration.');\n return false;\n }\n\n terminal.writeDebugLine('Uploading object with cacheId: ', cacheId);\n\n try {\n const result: boolean | Buffer = await this._makeHttpRequestAsync({\n terminal: terminal,\n relUrl: `${this._cacheKeyPrefix}${cacheId}`,\n method: this._uploadMethod,\n body: objectBuffer,\n warningText: 'Could not write cache entry',\n readBody: false,\n maxAttempts: MAX_HTTP_CACHE_ATTEMPTS\n });\n\n return result !== false;\n } catch (e) {\n terminal.writeWarningLine(`Error uploading cache entry: ${e}`);\n return false;\n }\n }\n\n public async updateCachedCredentialAsync(terminal: ITerminal, credential: string): Promise<void> {\n await CredentialCache.usingAsync(\n {\n supportEditing: true\n },\n async (credentialsCache: CredentialCache) => {\n credentialsCache.setCacheEntry(this._credentialCacheId, {\n credential: credential\n });\n await credentialsCache.saveIfModifiedAsync();\n }\n );\n }\n\n public async updateCachedCredentialInteractiveAsync(terminal: ITerminal): Promise<void> {\n if (!this._tokenHandler) {\n throw new Error(\n `The interactive cloud credentials flow is not configured.\\n` +\n `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 ` +\n `or provide your credentials to rush using the --credential flag instead. Credentials must be the ` +\n `'Authorization' header expected by ${this._url.href}`\n );\n }\n\n const cmd: string = `${this._tokenHandler.exec} ${(this._tokenHandler.args || []).join(' ')}`;\n terminal.writeVerboseLine(`Running '${cmd}' to get credentials`);\n const result: SpawnSyncReturns<string> = Executable.spawnSync(\n this._tokenHandler.exec,\n this._tokenHandler.args || [],\n {\n currentWorkingDirectory: this._rushProjectRoot\n }\n );\n\n terminal.writeErrorLine(result.stderr);\n\n if (result.error) {\n throw new Error(`Could not obtain credentials. The command '${cmd}' failed.`);\n }\n\n const credential: string = result.stdout.trim();\n terminal.writeVerboseLine('Got credentials');\n\n await this.updateCachedCredentialAsync(terminal, credential);\n\n terminal.writeLine('Updated credentials cache');\n }\n\n public async deleteCachedCredentialsAsync(terminal: ITerminal): Promise<void> {\n await CredentialCache.usingAsync(\n {\n supportEditing: true\n },\n async (credentialsCache: CredentialCache) => {\n credentialsCache.deleteCacheEntry(this._credentialCacheId);\n await credentialsCache.saveIfModifiedAsync();\n }\n );\n }\n\n private get _credentialCacheId(): string {\n if (!this.__credentialCacheId) {\n const cacheIdParts: string[] = [this._url.href];\n\n if (this._isCacheWriteAllowedByConfiguration) {\n cacheIdParts.push('cacheWriteAllowed');\n }\n\n this.__credentialCacheId = cacheIdParts.join('|');\n }\n\n return this.__credentialCacheId;\n }\n\n private async _makeHttpRequestAsync(options: {\n terminal: ITerminal;\n relUrl: string;\n method: 'GET' | UploadMethod;\n body: Buffer | undefined;\n warningText: string;\n readBody: boolean;\n maxAttempts: number;\n credentialOptions?: CredentialsOptions;\n }): Promise<Buffer | boolean> {\n const { terminal, relUrl, method, body, warningText, readBody, credentialOptions } = options;\n const safeCredentialOptions: CredentialsOptions = credentialOptions ?? CredentialsOptions.Optional;\n const credentials: string | undefined = await this._tryGetCredentialsAsync(safeCredentialOptions);\n const url: string = new URL(relUrl, this._url).href;\n\n const headers: Record<string, string> = {};\n if (typeof credentials === 'string') {\n headers.Authorization = credentials;\n }\n\n for (const [key, value] of Object.entries(this._headers)) {\n if (typeof value === 'string') {\n headers[key] = value;\n }\n }\n\n const bodyLength: number | 'unknown' = (body as { length: number })?.length || 'unknown';\n\n terminal.writeDebugLine(`[http-build-cache] request: ${method} ${url} ${bodyLength} bytes`);\n\n const webClient: WebClient = new WebClient();\n const response: IWebClientResponse = await webClient.fetchAsync(url, {\n verb: method,\n headers: headers,\n body: body,\n redirect: 'follow',\n timeoutMs: 0 // Use the default timeout\n });\n\n if (!response.ok) {\n const isNonCredentialResponse: boolean = response.status >= 500 && response.status < 600;\n\n if (\n !isNonCredentialResponse &&\n typeof credentials !== 'string' &&\n safeCredentialOptions === CredentialsOptions.Optional\n ) {\n // If we don't already have credentials yet, and we got a response from the server\n // that is a \"normal\" failure (4xx), then we assume that credentials are probably\n // required. Re-attempt the request, requiring credentials this time.\n //\n // This counts as part of the \"first attempt\", so it is not included in the max attempts\n return await this._makeHttpRequestAsync({\n ...options,\n credentialOptions: CredentialsOptions.Required\n });\n }\n\n if (options.maxAttempts > 1) {\n // Pause a bit before retrying in case the server is busy\n // Add some random jitter to the retry so we can spread out load on the remote service\n // A proper solution might add exponential back off in case the retry count is high (10 or more)\n const factor: number = 1.0 + Math.random(); // A random number between 1.0 and 2.0\n const retryDelay: number = Math.floor(factor * this._minHttpRetryDelayMs);\n\n await Async.sleepAsync(retryDelay);\n\n return await this._makeHttpRequestAsync({ ...options, maxAttempts: options.maxAttempts - 1 });\n }\n\n this._reportFailure(terminal, method, response, false, warningText);\n return false;\n }\n\n const result: Buffer | boolean = readBody ? await response.getBufferAsync() : true;\n\n terminal.writeDebugLine(\n `[http-build-cache] actual response: ${response.status} ${url} ${\n result === true ? 'true' : result.length\n } bytes`\n );\n\n return result;\n }\n\n private async _tryGetCredentialsAsync(options: CredentialsOptions.Required): Promise<string>;\n private async _tryGetCredentialsAsync(options: CredentialsOptions.Optional): Promise<string | undefined>;\n private async _tryGetCredentialsAsync(options: CredentialsOptions.Omit): Promise<undefined>;\n private async _tryGetCredentialsAsync(options: CredentialsOptions): Promise<string | undefined>;\n private async _tryGetCredentialsAsync(options: CredentialsOptions): Promise<string | undefined> {\n if (options === CredentialsOptions.Omit) {\n return;\n }\n\n let credentials: string | undefined = this._environmentCredential;\n\n if (credentials === undefined) {\n credentials = await this._tryGetCredentialsFromCacheAsync();\n }\n\n if (typeof credentials !== 'string' && options === CredentialsOptions.Required) {\n throw new Error(\n [\n `Credentials for ${this._url.href} have not been provided.`,\n `In CI, verify that RUSH_BUILD_CACHE_CREDENTIAL contains a valid Authorization header value.`,\n ``,\n `For local developers, run:`,\n ``,\n ` rush update-cloud-credentials --interactive`,\n ``\n ].join('\\n')\n );\n }\n\n return credentials;\n }\n\n private async _tryGetCredentialsFromCacheAsync(): Promise<string | undefined> {\n let cacheEntry: ICredentialCacheEntry | undefined;\n\n await CredentialCache.usingAsync(\n {\n supportEditing: false\n },\n (credentialsCache: CredentialCache) => {\n cacheEntry = credentialsCache.tryGetCacheEntry(this._credentialCacheId);\n }\n );\n\n if (cacheEntry) {\n const expirationTime: number | undefined = cacheEntry.expires?.getTime();\n if (!expirationTime || expirationTime >= Date.now()) {\n return cacheEntry.credential;\n }\n }\n }\n\n private _getFailureType(\n requestMethod: string,\n response: IWebClientResponse,\n isRedirect: boolean\n ): FailureType {\n if (response.ok) {\n return FailureType.None;\n }\n\n switch (response.status) {\n case 503: {\n // We select 503 specifically because this represents \"service unavailable\" and\n // \"rate limit throttle\" errors, which are transient issues.\n //\n // There are other 5xx errors, such as 501, that can occur if the request is\n // malformed, so as a general rule we want to let through other 5xx errors\n // so the user can troubleshoot.\n\n // Don't fail production builds with warnings for transient issues\n return FailureType.Informational;\n }\n\n case 401:\n case 403:\n case 407: {\n if (requestMethod === 'GET' && (isRedirect || response.redirected)) {\n // Cache misses for GET requests are not errors\n // This is a workaround behavior where a server can issue a redirect and we fail to authenticate at the new location.\n // We do not want to signal this as an authentication failure because the authorization header is not passed on to redirects.\n // i.e The authentication header was accepted for the first request and therefore subsequent failures\n // where it was not present should not be attributed to the header.\n // This scenario usually comes up with services that redirect to pre-signed URLS that don't actually exist.\n // Those services then usually treat the 404 as a 403 to prevent leaking information.\n return FailureType.None;\n }\n\n return FailureType.Authentication;\n }\n\n case 404: {\n if (requestMethod === 'GET') {\n // Cache misses for GET requests are not errors\n return FailureType.None;\n }\n }\n }\n\n // Let dev builds succeed, let Prod builds fail\n return FailureType.Warning;\n }\n\n private _reportFailure(\n terminal: ITerminal,\n requestMethod: string,\n response: IWebClientResponse,\n isRedirect: boolean,\n message: string\n ): void {\n switch (this._getFailureType(requestMethod, response, isRedirect)) {\n default: {\n terminal.writeErrorLine(`${message}: HTTP ${response.status}: ${response.statusText}`);\n break;\n }\n\n case FailureType.Warning: {\n terminal.writeWarningLine(`${message}: HTTP ${response.status}: ${response.statusText}`);\n break;\n }\n\n case FailureType.Informational: {\n terminal.writeLine(`${message}: HTTP ${response.status}: ${response.statusText}`);\n break;\n }\n\n case FailureType.None: {\n terminal.writeDebugLine(`${message}: HTTP ${response.status}: ${response.statusText}`);\n break;\n }\n\n case FailureType.Authentication: {\n throw new Error(\n [\n `${this._url.href} responded with ${response.status}: ${response.statusText}.`,\n `Credentials may be misconfigured or have expired.`,\n `In CI, verify that RUSH_BUILD_CACHE_CREDENTIAL contains a valid Authorization header value.`,\n ``,\n `For local developers, run:`,\n ``,\n ` rush update-cloud-credentials --interactive`,\n ``\n ].join('\\n')\n );\n }\n }\n }\n}\n"]}
@@ -0,0 +1,32 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2
+ // See LICENSE in the project root for license information.
3
+ const PLUGIN_NAME = 'HttpBuildCachePlugin';
4
+ /**
5
+ * @public
6
+ */
7
+ export class RushHttpBuildCachePlugin {
8
+ constructor() {
9
+ this.pluginName = PLUGIN_NAME;
10
+ }
11
+ apply(rushSession, rushConfig) {
12
+ rushSession.hooks.initialize.tap(this.pluginName, () => {
13
+ rushSession.registerCloudBuildCacheProviderFactory('http', async (buildCacheConfig) => {
14
+ const config = buildCacheConfig.httpConfiguration;
15
+ const { url, uploadMethod, headers, tokenHandler, cacheKeyPrefix, isCacheWriteAllowed } = config;
16
+ const options = {
17
+ pluginName: this.pluginName,
18
+ rushJsonFolder: rushConfig.rushJsonFolder,
19
+ url: url,
20
+ uploadMethod: uploadMethod,
21
+ headers: headers,
22
+ tokenHandler: tokenHandler,
23
+ cacheKeyPrefix: cacheKeyPrefix,
24
+ isCacheWriteAllowed: !!isCacheWriteAllowed
25
+ };
26
+ const { HttpBuildCacheProvider } = await import('./HttpBuildCacheProvider');
27
+ return new HttpBuildCacheProvider(options, rushSession);
28
+ });
29
+ });
30
+ }
31
+ }
32
+ //# sourceMappingURL=RushHttpBuildCachePlugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RushHttpBuildCachePlugin.js","sourceRoot":"","sources":["../src/RushHttpBuildCachePlugin.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,2DAA2D;AAM3D,MAAM,WAAW,GAAW,sBAAsB,CAAC;AAyCnD;;GAEG;AACH,MAAM,OAAO,wBAAwB;IAArC;QACkB,eAAU,GAAW,WAAW,CAAC;IA6BnD,CAAC;IA3BQ,KAAK,CAAC,WAAwB,EAAE,UAA6B;QAClE,WAAW,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,EAAE,GAAG,EAAE;YACrD,WAAW,CAAC,sCAAsC,CAAC,MAAM,EAAE,KAAK,EAAE,gBAAgB,EAAE,EAAE;gBACpF,MAAM,MAAM,GACV,gBAGD,CAAC,iBAAiB,CAAC;gBAEpB,MAAM,EAAE,GAAG,EAAE,YAAY,EAAE,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,GAAG,MAAM,CAAC;gBAEjG,MAAM,OAAO,GAAmC;oBAC9C,UAAU,EAAE,IAAI,CAAC,UAAU;oBAC3B,cAAc,EAAE,UAAU,CAAC,cAAc;oBACzC,GAAG,EAAE,GAAG;oBACR,YAAY,EAAE,YAAY;oBAC1B,OAAO,EAAE,OAAO;oBAChB,YAAY,EAAE,YAAY;oBAC1B,cAAc,EAAE,cAAc;oBAC9B,mBAAmB,EAAE,CAAC,CAAC,mBAAmB;iBAC3C,CAAC;gBAEF,MAAM,EAAE,sBAAsB,EAAE,GAAG,MAAM,MAAM,CAAC,0BAA0B,CAAC,CAAC;gBAC5E,OAAO,IAAI,sBAAsB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;YAC1D,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport type { IRushPlugin, RushSession, RushConfiguration } from '@rushstack/rush-sdk';\n\nimport type { IHttpBuildCacheProviderOptions, UploadMethod } from './HttpBuildCacheProvider';\n\nconst PLUGIN_NAME: string = 'HttpBuildCachePlugin';\n\n/**\n * @public\n */\nexport interface IRushHttpBuildCachePluginConfig {\n /**\n * The URL of the server that stores the caches (e.g. \"https://build-caches.example.com\").\n */\n url: string;\n\n /**\n * The HTTP method to use when writing to the cache (defaults to PUT).\n */\n uploadMethod?: UploadMethod;\n\n /**\n * An optional set of HTTP headers to pass to the cache server.\n */\n headers?: Record<string, string>;\n\n /**\n * An optional command that prints the endpoint's credentials to stdout. Provide the\n * command or script to execute and, optionally, any arguments to pass to the script.\n */\n tokenHandler?: {\n exec: string;\n args?: string[];\n };\n\n /**\n * Prefix for cache keys.\n */\n cacheKeyPrefix?: string;\n\n /**\n * If set to true, allow writing to the cache. Defaults to false.\n */\n isCacheWriteAllowed?: boolean;\n}\n\n/**\n * @public\n */\nexport class RushHttpBuildCachePlugin implements IRushPlugin {\n public readonly pluginName: string = PLUGIN_NAME;\n\n public apply(rushSession: RushSession, rushConfig: RushConfiguration): void {\n rushSession.hooks.initialize.tap(this.pluginName, () => {\n rushSession.registerCloudBuildCacheProviderFactory('http', async (buildCacheConfig) => {\n const config: IRushHttpBuildCachePluginConfig = (\n buildCacheConfig as typeof buildCacheConfig & {\n httpConfiguration: IRushHttpBuildCachePluginConfig;\n }\n ).httpConfiguration;\n\n const { url, uploadMethod, headers, tokenHandler, cacheKeyPrefix, isCacheWriteAllowed } = config;\n\n const options: IHttpBuildCacheProviderOptions = {\n pluginName: this.pluginName,\n rushJsonFolder: rushConfig.rushJsonFolder,\n url: url,\n uploadMethod: uploadMethod,\n headers: headers,\n tokenHandler: tokenHandler,\n cacheKeyPrefix: cacheKeyPrefix,\n isCacheWriteAllowed: !!isCacheWriteAllowed\n };\n\n const { HttpBuildCacheProvider } = await import('./HttpBuildCacheProvider');\n return new HttpBuildCacheProvider(options, rushSession);\n });\n });\n }\n}\n"]}
@@ -0,0 +1,5 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
2
+ // See LICENSE in the project root for license information.
3
+ import { RushHttpBuildCachePlugin } from './RushHttpBuildCachePlugin';
4
+ export default RushHttpBuildCachePlugin;
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,4FAA4F;AAC5F,2DAA2D;AAE3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAEtE,eAAe,wBAAwB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport { RushHttpBuildCachePlugin } from './RushHttpBuildCachePlugin';\n\nexport default RushHttpBuildCachePlugin;\nexport type { IHttpBuildCacheProviderOptions, UploadMethod } from './HttpBuildCacheProvider';\n"]}
@@ -0,0 +1,52 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-04/schema#",
3
+ "title": "Configuration for build cache with HTTPS server",
4
+ "type": "object",
5
+ "required": ["url"],
6
+ "properties": {
7
+ "url": {
8
+ "type": "string",
9
+ "description": "(Required) The URL of the server that stores the caches (e.g. \"https://build-caches.example.com\").",
10
+ "format": "uri"
11
+ },
12
+ "uploadMethod": {
13
+ "type": "string",
14
+ "description": "(Optional) The HTTP method to use when writing to the cache (defaults to PUT).",
15
+ "enum": ["PUT", "POST", "PATCH"],
16
+ "default": "PUT"
17
+ },
18
+ "headers": {
19
+ "type": "object",
20
+ "description": "(Optional) HTTP headers to pass to the cache server",
21
+ "properties": {},
22
+ "additionalProperties": {
23
+ "type": "string"
24
+ }
25
+ },
26
+ "tokenHandler": {
27
+ "type": "object",
28
+ "description": "(Optional) Shell command that prints the authorization token needed to communicate with the HTTPS server and exits with code 0. This command will be executed from the root of the monorepo.",
29
+ "properties": {
30
+ "exec": {
31
+ "type": "string",
32
+ "description": "(Required) The command or script to execute."
33
+ },
34
+ "args": {
35
+ "type": "array",
36
+ "description": "(Optional) Arguments to pass to the command or script.",
37
+ "items": {
38
+ "type": "string"
39
+ }
40
+ }
41
+ }
42
+ },
43
+ "cacheKeyPrefix": {
44
+ "type": "string",
45
+ "description": "(Optional) prefix for cache keys."
46
+ },
47
+ "isCacheWriteAllowed": {
48
+ "type": "boolean",
49
+ "description": "(Optional) If set to true, allow writing to the cache. Defaults to false."
50
+ }
51
+ }
52
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rushstack/rush-http-build-cache-plugin",
3
- "version": "5.167.0",
3
+ "version": "5.169.0",
4
4
  "description": "Rush plugin for generic HTTP cloud build cache",
5
5
  "repository": {
6
6
  "type": "git",
@@ -8,22 +8,46 @@
8
8
  "directory": "rush-plugins/rush-http-build-cache-plugin"
9
9
  },
10
10
  "homepage": "https://rushjs.io",
11
- "main": "lib/index.js",
12
- "types": "lib/index.d.ts",
11
+ "main": "./lib-commonjs/index.js",
12
+ "module": "./lib-esm/index.js",
13
+ "types": "./lib-dts/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./lib-dts/index.d.ts",
17
+ "import": "./lib-esm/index.js",
18
+ "require": "./lib-commonjs/index.js"
19
+ },
20
+ "./lib/*.schema.json": "./lib-commonjs/*.schema.json",
21
+ "./lib/*": {
22
+ "types": "./lib-dts/*.d.ts",
23
+ "import": "./lib-esm/*.js",
24
+ "require": "./lib-commonjs/*.js"
25
+ },
26
+ "./rush-plugin-manifest.json": "./rush-plugin-manifest.json",
27
+ "./package.json": "./package.json"
28
+ },
29
+ "typesVersions": {
30
+ "*": {
31
+ "lib/*": [
32
+ "lib-dts/*"
33
+ ]
34
+ }
35
+ },
13
36
  "license": "MIT",
14
37
  "dependencies": {
15
38
  "https-proxy-agent": "~5.0.0",
16
- "@rushstack/credential-cache": "0.1.10",
17
- "@rushstack/rush-sdk": "5.167.0",
18
- "@rushstack/node-core-library": "5.19.1"
39
+ "@rushstack/credential-cache": "0.2.0",
40
+ "@rushstack/node-core-library": "5.20.0",
41
+ "@rushstack/rush-sdk": "5.169.0"
19
42
  },
20
43
  "devDependencies": {
21
44
  "eslint": "~9.37.0",
22
- "@microsoft/rush-lib": "5.167.0",
23
- "@rushstack/heft": "1.1.13",
24
- "@rushstack/terminal": "0.21.0",
45
+ "@microsoft/rush-lib": "5.169.0",
46
+ "@rushstack/heft": "1.2.0",
47
+ "@rushstack/terminal": "0.22.0",
25
48
  "local-node-rig": "1.0.0"
26
49
  },
50
+ "sideEffects": false,
27
51
  "scripts": {
28
52
  "build": "heft build --clean",
29
53
  "start": "heft test-watch",
@@ -4,8 +4,8 @@
4
4
  {
5
5
  "pluginName": "rush-http-build-cache-plugin",
6
6
  "description": "Rush plugin for generic HTTP build cache",
7
- "entryPoint": "lib/index.js",
8
- "optionsSchema": "lib/schemas/http-config.schema.json"
7
+ "entryPoint": "./lib-commonjs/index.js",
8
+ "optionsSchema": "./lib-commonjs/schemas/http-config.schema.json"
9
9
  }
10
10
  ]
11
11
  }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes