wireit
Version:
Upgrade your npm scripts to make them smarter and more efficient
857 lines • 36.8 kB
JavaScript
/**
* @license
* Copyright 2022 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
};
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
return function (env) {
function fail(e) {
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (r = env.stack.pop()) {
try {
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
else s |= 1;
}
catch (e) {
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
};
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
import * as pathlib from 'path';
import * as unbudgetedFs from 'fs/promises';
import * as fs from '../util/fs.js';
import * as http from 'http';
import * as https from 'https';
import { createHash } from 'crypto';
import { scriptReferenceToString } from '../config.js';
import { getScriptDataDir } from '../util/script-data-dir.js';
import '../util/dispose.js';
import { fileBudget } from '../util/fs.js';
import { execFile } from 'child_process';
import '../util/dispose.js';
import { inspect } from 'util';
/**
* Caches script output to the GitHub Actions cache service.
*/
export class GitHubActionsCache {
#baseUrl;
#authToken;
#logger;
/**
* Once we've hit a rate limit or service availability error, simply stop
* hitting the cache for the remainder of this Wireit process. Caching is not
* critical, it's just an optimization.
*
* TODO(aomarks) We could be a little smarter and do retries, but this at
* least should stop builds breaking in the short-term.
*/
#serviceIsDown = false;
constructor(logger, baseUrl, authToken) {
this.#baseUrl = baseUrl;
this.#authToken = authToken;
this.#logger = logger;
}
static async create(logger) {
const custodianPort = process.env['WIREIT_CACHE_GITHUB_CUSTODIAN_PORT'];
if (custodianPort === undefined) {
if (process.env['ACTIONS_RUNTIME_TOKEN'] !== undefined ||
process.env['ACTIONS_CACHE_URL'] !== undefined ||
process.env['ACTIONS_RESULTS_URL'] !== undefined) {
console.warn('⚠️ Please upgrade to google/wireit@setup-github-cache/v2. ' +
'In the future, Wireit caching for this project will stop working.\n');
return GitHubActionsCache.#deprecatedCreate(logger);
}
return {
ok: false,
error: {
type: 'failure',
reason: 'invalid-usage',
message: 'The WIREIT_CACHE_GITHUB_CUSTODIAN_PORT environment variable was ' +
'not set, but is required when WIREIT_CACHE=github. Use the ' +
'google/wireit@setup-github-cache/v2 action to automatically set ' +
'this environment variable.',
},
};
}
const custodianUrl = `http://localhost:${custodianPort}`;
let result;
try {
const response = await fetch(custodianUrl);
if (!response.ok) {
throw new Error(`HTTP status ${response.status}`);
}
result = (await response.json());
}
catch (error) {
return {
ok: false,
error: {
type: 'failure',
reason: 'unknown-error-thrown',
error: new Error(`Error communicating with cache token mediator service: ` +
inspect(error)),
},
};
}
if (!result.caching.github.ACTIONS_RESULTS_URL) {
return {
ok: false,
error: {
type: 'failure',
reason: 'invalid-usage',
message: 'No ACTIONS_RESULTS_URL was returned by the custodian.' +
' Ensure you are using at least version 2.0.3.',
},
};
}
return {
ok: true,
value: new GitHubActionsCache(logger, result.caching.github.ACTIONS_RESULTS_URL, result.caching.github.ACTIONS_RUNTIME_TOKEN),
};
}
static #deprecatedCreate(logger) {
// The ACTIONS_RESULTS_URL and ACTIONS_RUNTIME_TOKEN environment variables are
// automatically provided to GitHub Actions re-usable workflows. However,
// they are _not_ provided to regular "run" scripts. For this reason, we
// re-export those variables so that all "run" scripts can access them using
// the "google/wireit@setup-github-actions-caching/v1" re-usable workflow.
//
// https://github.com/actions/toolkit/blob/500d0b42fee2552ae9eeb5933091fe2fbf14e72d/packages/cache/src/internal/cacheHttpClient.ts#L38
const baseUrl = process.env['ACTIONS_RESULTS_URL'];
if (!baseUrl) {
return {
ok: false,
error: {
type: 'failure',
reason: 'invalid-usage',
message: 'The ACTIONS_RESULTS_URL variable was not set, but is required when ' +
'WIREIT_CACHE=github. Use the google/wireit@setup-github-cache/v1 ' +
'action to automatically set environment variables.',
},
};
}
if (!baseUrl.endsWith('/')) {
// Internally, the @actions/cache library expects the URL to end with a
// slash. While we could be more lenient, we want to match the behavior of
// any other calls happening inside that library which we don't control.
return {
ok: false,
error: {
type: 'failure',
reason: 'invalid-usage',
message: `The ACTIONS_RESULTS_URL must end in a forward-slash, got ${JSON.stringify(baseUrl)}.`,
},
};
}
// https://github.com/actions/toolkit/blob/500d0b42fee2552ae9eeb5933091fe2fbf14e72d/packages/cache/src/internal/cacheHttpClient.ts#L63
const authToken = process.env['ACTIONS_RUNTIME_TOKEN'];
if (!authToken) {
return {
ok: false,
error: {
type: 'failure',
reason: 'invalid-usage',
message: 'The ACTIONS_RUNTIME_TOKEN variable was not set, but is required when ' +
'WIREIT_CACHE=github. Use the google/wireit@setup-github-cache/v1 ' +
'action to automatically set environment variables.',
},
};
}
return {
ok: true,
value: new GitHubActionsCache(logger, baseUrl, authToken),
};
}
async get(script, fingerprint) {
const env_1 = { stack: [], error: void 0, hasError: false };
try {
if (this.#serviceIsDown) {
return undefined;
}
const version = this.#computeVersion(fingerprint);
const key = this.#computeCacheKey(script);
const url = new URL(
// See https://github.com/actions/toolkit/blob/930c89072712a3aac52d74b23338f00bb0cfcb24/packages/cache/src/generated/results/api/v1/cache.twirp-client.ts#L91
'twirp/github.actions.results.api.v1.CacheService/GetCacheEntryDownloadURL', this.#baseUrl);
// See https://github.com/actions/toolkit/blob/930c89072712a3aac52d74b23338f00bb0cfcb24/packages/cache/src/cache.ts#L246
// and https://github.com/actions/toolkit/blob/930c89072712a3aac52d74b23338f00bb0cfcb24/packages/cache/src/generated/results/api/v1/cache.ts#L101C1-L126C2
const requestBody = { key, version };
const bodyBuffer = Buffer.from(JSON.stringify(requestBody), 'utf8');
const requestResult = __addDisposableResource(env_1, this.#request(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': bodyBuffer.length,
},
}), false);
const { req, resPromise } = requestResult;
req.end(bodyBuffer);
const result = await resPromise;
const response = await this.#maybeHandleServiceDown(result, script);
if (response === undefined) {
return undefined;
}
if (isOk(response)) {
const { signed_download_url: archiveLocation } = JSON.parse(await readBody(response));
if (!archiveLocation) {
return undefined;
}
return new GitHubActionsCacheHit(script, archiveLocation, this.#logger);
}
throw new Error(`GitHub Cache check HTTP ${String(response.statusCode)} error: ` +
(await readBody(response)));
}
catch (e_1) {
env_1.error = e_1;
env_1.hasError = true;
}
finally {
__disposeResources(env_1);
}
}
async set(script, fingerprint, absFiles) {
const env_2 = { stack: [], error: void 0, hasError: false };
try {
if (this.#serviceIsDown) {
return false;
}
const tempDir = __addDisposableResource(env_2, await makeTempDir(script), true);
const tarballPath = await this.#makeTarball(absFiles.map((file) => file.path), tempDir.path);
return await this.#reserveUploadAndCommitTarball(script, fingerprint, tarballPath);
}
catch (e_2) {
env_2.error = e_2;
env_2.hasError = true;
}
finally {
const result_1 = __disposeResources(env_2);
if (result_1)
await result_1;
}
}
/** The service decides what to evict; recency isn't ours to report. */
markEntryRecentlyUsed() {
return Promise.resolve();
}
/** No entry of this cache lives on local disk. */
sweepTrash() {
return Promise.resolve([]);
}
/**
* @returns True if we reserved, uploaded, and committed the tarball. False if
* we gave up due to a rate limit error.
* @throws If an unexpected HTTP error occured.
*/
async #reserveUploadAndCommitTarball(script, fingerprint, tarballPath) {
const tarballStats = await fs.stat(tarballPath);
const tarballBytes = tarballStats.size;
// Reference:
// https://github.com/actions/toolkit/blob/f8a69bc473af4a204d0c03de61d5c9d1300dfb17/packages/cache/src/cache.ts#L174
const GB = 1024 * 1024 * 1024;
const maxBytes = 10 * GB;
if (tarballBytes > maxBytes) {
this.#logger.log({
script,
type: 'info',
detail: 'cache-info',
message: `Output was too big to be cached: ` +
`${Math.round(tarballBytes / GB)}GB > ` +
`${Math.round(maxBytes / GB)}GB.`,
});
return false;
}
const key = this.#computeCacheKey(script);
const version = this.#computeVersion(fingerprint);
const blobUrl = await this.#createCacheEntry(script, key, version);
// It's likely that we'll occasionally fail to reserve an entry and get
// undefined here, especially when running multiple GitHub Action jobs in
// parallel with the same scripts, because there is a window of time between
// calling "get" and "set" on the cache in which another worker could have
// reserved the entry before us. Non fatal, just don't save.
if (blobUrl === undefined) {
return false;
}
if (!(await this.#upload(script, blobUrl, tarballPath, tarballBytes))) {
return false;
}
if (!(await this.#finalize(script, key, version, tarballBytes))) {
return false;
}
return true;
}
/**
* @returns True if we uploaded, false if we gave up due to a rate limit error.
* @throws If an unexpected HTTP error occured.
*/
async #upload(script, blobUrl, tarballPath, tarballBytes) {
// Reference:
// https://github.com/actions/toolkit/blob/500d0b42fee2552ae9eeb5933091fe2fbf14e72d/packages/cache/src/options.ts#L59
const maxChunkSize = 32 * 1024 * 1024;
// TODO: update to TypeScript 5.2 and use the new `using` syntax for the
// budget object.
const reservation = await fileBudget.reserve();
const tarballHandle = await unbudgetedFs.open(tarballPath, 'r');
let offset = 0;
try {
const env_3 = { stack: [], error: void 0, hasError: false };
try {
// See https://github.com/actions/toolkit/blob/930c89072712a3aac52d74b23338f00bb0cfcb24/packages/cache/src/internal/uploadUtils.ts#L132
// TODO(aomarks) Chunks could be uploaded in parallel.
const blockIds = [];
let blockIdx = 0;
while (offset < tarballBytes) {
const env_4 = { stack: [], error: void 0, hasError: false };
try {
const chunkSize = Math.min(tarballBytes - offset, maxChunkSize);
const start = offset;
const end = offset + chunkSize - 1;
offset += maxChunkSize;
const tarballChunkStream = await fs.createReadStream(tarballPath, {
fd: tarballHandle.fd,
start,
end,
autoClose: false,
});
const opts = {
method: 'PUT',
headers: {
'content-type': 'application/octet-stream',
'content-length': `${chunkSize}`,
'x-ms-blob-type': 'BlockBlob',
authorization: undefined,
},
};
const putBlockUrl = new URL(blobUrl);
putBlockUrl.searchParams.set('comp', 'block');
// All block IDs must be the same length within a blob.
const blockId = Buffer.from(blockIdx.toString(16).padStart(4, '0')).toString('base64');
blockIdx++;
blockIds.push(blockId);
putBlockUrl.searchParams.set('blockid', blockId);
const requestResult = __addDisposableResource(env_4, this.#request(putBlockUrl, opts), false);
const { req, resPromise } = requestResult;
tarballChunkStream.pipe(req);
tarballChunkStream.on('close', () => {
req.end();
});
const result = await resPromise;
const response = await this.#maybeHandleServiceDown(result, script);
if (response === undefined) {
return false;
}
if (!isOk(response)) {
throw new Error(`GitHub Cache upload HTTP ${String(response.statusCode)} error: ${await readBody(response)}\nopts: ${JSON.stringify(opts)}`);
}
}
catch (e_3) {
env_4.error = e_3;
env_4.hasError = true;
}
finally {
__disposeResources(env_4);
}
}
const putBlockListUrl = new URL(blobUrl);
putBlockListUrl.searchParams.set('comp', 'blocklist');
const doneXmlBody = Buffer.from(`<?xml version="1.0" encoding="utf-8"?>
<BlockList>
${blockIds.map((blockId) => ` <Uncommitted>${blockId}</Uncommitted>`).join('\n')}
</BlockList>
`, 'utf8');
const requestResult = __addDisposableResource(env_3, this.#request(putBlockListUrl, {
method: 'PUT',
headers: {
'content-type': 'text/plain; charset=UTF-8',
'content-length': `${doneXmlBody.length}`,
authorization: undefined,
},
}), false);
requestResult.req.end(doneXmlBody);
const r = await requestResult.resPromise;
const response = await this.#maybeHandleServiceDown(r, script);
if (response === undefined) {
return false;
}
if (!isOk(response)) {
throw new Error(`GitHub Cache finalize HTTP ${String(response.statusCode)} error: ${await readBody(response)}`);
}
return true;
}
catch (e_4) {
env_3.error = e_4;
env_3.hasError = true;
}
finally {
__disposeResources(env_3);
}
}
finally {
await tarballHandle.close();
reservation[Symbol.dispose]();
}
}
/**
* @returns True if we committed, false if we gave up due to a rate limit error.
* @throws If an unexpected HTTP error occured.
*/
async #finalize(script, key, version, tarballBytes) {
const env_5 = { stack: [], error: void 0, hasError: false };
try {
const url = new URL(
// See
// https://github.com/actions/toolkit/blob/930c89072712a3aac52d74b23338f00bb0cfcb24/packages/cache/src/generated/results/api/v1/cache.twirp-client.ts#L132
`twirp/github.actions.results.api.v1.CacheService/FinalizeCacheEntryUpload`, this.#baseUrl);
// See
// https://github.com/actions/toolkit/blob/930c89072712a3aac52d74b23338f00bb0cfcb24/packages/cache/src/cache.ts#L555
// and https://github.com/actions/toolkit/blob/930c89072712a3aac52d74b23338f00bb0cfcb24/packages/cache/src/generated/results/api/v1/cache.ts#L57
const body = {
key,
version,
sizeBytes: tarballBytes,
};
const bodyBuffer = Buffer.from(JSON.stringify(body), 'utf8');
const requestResult = __addDisposableResource(env_5, this.#request(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
'content-length': bodyBuffer.length,
},
}), false);
const { req, resPromise } = requestResult;
req.end(bodyBuffer);
const result = await resPromise;
const response = await this.#maybeHandleServiceDown(result, script);
if (response === undefined) {
return false;
}
if (!isOk(response)) {
throw new Error(`GitHub Cache commit HTTP ${String(response.statusCode)} error: ${await readBody(response)}`);
}
return true;
}
catch (e_5) {
env_5.error = e_5;
env_5.hasError = true;
}
finally {
__disposeResources(env_5);
}
}
#request(url, options) {
return request(url, {
...options,
headers: {
accept: 'application/json',
// https://github.com/actions/toolkit/blob/500d0b42fee2552ae9eeb5933091fe2fbf14e72d/packages/http-client/src/auth.ts#L46
authorization: `Bearer ${this.#authToken}`,
...options?.headers,
},
});
}
/**
* If we received a network or HTTP error from the given HTTP request, set the
* global flag to indicate that GitHub Actions Caching is down (it's a class
* property, but this class should be a global singleton), log an error, and
* return undefined. If the request was OK, just return the response.
*/
async #maybeHandleServiceDown(res, script) {
const status = res.ok ? res.value.statusCode : null;
if (res.ok && status != null && status >= 200 && status <= 299) {
return res.value;
}
if (this.#serviceIsDown) {
// Reduce noise; just whatever the first error was is OK.
//
// Note that this cache can be accessed concurrently, so even though we
// stop making HTTP requests after setting this flag, there could be >1
// pending requests out at the same time before the first error is
// detected.
return undefined;
}
this.#serviceIsDown = true;
if (!res.ok) {
this.#logger.log({
script,
type: 'info',
detail: 'cache-info',
message: `Network error from GitHub Actions cache service.` +
` GitHub Actions caching has been temporarily disabled.` +
` Detail:\n\n${res.error}`,
});
}
else {
// Read the body before returning. The caller destroys the request as soon
// as we return, which would cut the body off.
const body = await readBody(res.value).catch(() => '');
const message = status === 429
? `Hit GitHub Actions cache service rate limit`
: status === 503
? `GitHub Actions cache service is temporarily unavailable`
: `Unexpected HTTP ${status} error from GitHub Actions cache service`;
this.#logger.log({
script,
type: 'info',
detail: 'cache-info',
message: `${message}.` +
` GitHub Actions caching has been temporarily disabled.` +
` Detail:\n\nHTTP ${status}: ${body}`,
});
}
return undefined;
}
#computeCacheKey(script) {
return `wireit-${createHash('sha256')
.update(scriptReferenceToString(script))
.digest('hex')}`;
}
#computeVersion(fingerprint) {
const parts = [
fingerprint.string,
'gzip', // e.g. zstd, gzip
// The ImageOS environment variable tells us which operating system
// version is being used for the worker VM (e.g. "ubuntu20",
// "macos11"). We already include process.platform in the fingerprint,
// but this is more specific.
//
// There is also an ImageVersion variable (e.g. "20220405.4") which we
// could consider including, but it probably changes frequently and is
// unlikely to affect output, so we prefer the higher cache hit rate.
process.env.ImageOS ?? '',
// Versioning salt:
// - <omitted>: Initial version.
// - 2: Removed empty directories manifest.
'2',
];
return createHash('sha256')
.update(parts.join('\x1E'))
.digest('hex');
}
/**
* Create a tarball file in a local temp directory containing the given paths.
*
* @returns The full path to the tarball file on disk.
*/
async #makeTarball(paths, tempDir) {
// Create a manifest file so that we can pass a large number of files to
// tar.
const manifestName = 'manifest.txt';
const manifestPath = pathlib.join(tempDir, manifestName);
// The paths are absolute, and on Windows they use the native backslash
// separator. GNU tar (e.g. the one Git for Windows puts on PATH) treats a
// backslash as an escape character in its file lists, so convert to
// forward slashes. BSD tar accepts both.
await fs.writeFile(manifestPath, paths.map((path) => path.replaceAll('\\', '/')).join('\n'), 'utf8');
const tarballPath = pathlib.join(tempDir, 'cache.tgz');
await new Promise((resolve, reject) => {
// Run tar from inside the temp directory and give it relative file names,
// rather than absolute ones. GNU tar on Windows interprets an absolute
// path with a drive letter (e.g. "D:\...") as a remote host, so it fails
// with "Cannot connect to D:" even though the file is local. See
// https://github.com/google/wireit/issues/1242.
execFile('tar', [
// Use the newer standardized tar format.
'--posix',
// Use gzip compression.
//
// TODO(aomarks) zstd is faster and has better performance, but it's
// availability is unreliable, and appears to have a bug on Windows
// (https://github.com/actions/cache/issues/301). Investigate and
// enable if easy.
'--gzip',
'--create',
'--file',
pathlib.basename(tarballPath),
// Use absolute paths (note we use the short form because the long
// form is --absolute-names on GNU tar, but --absolute-paths on BSD
// tar).
'-P',
// We have a complete list of files and directories, so we don't need
// or want tar to automatically expand directories. This also allows
// us to create empty directories, even if they aren't actually empty
// on disk.
'--no-recursion',
'--files-from',
manifestName,
], { cwd: tempDir }, (error) => {
if (error != null) {
reject(new Error(`tar error`, { cause: error }));
}
else {
resolve();
}
});
});
return tarballPath;
}
/**
* Reserve a cache entry.
*
* @returns A numeric cache id the cache entry was reserved for us, or
* undefined if the cache entry was already reserved, or a rate limit error
* occured.
*/
async #createCacheEntry(script, key, version) {
const env_6 = { stack: [], error: void 0, hasError: false };
try {
const url = new URL(
// See https://github.com/actions/toolkit/blob/930c89072712a3aac52d74b23338f00bb0cfcb24/packages/cache/src/generated/results/api/v1/cache.twirp-client.ts#L117
'twirp/github.actions.results.api.v1.CacheService/CreateCacheEntry', this.#baseUrl);
// See
// https://github.com/actions/toolkit/blob/930c89072712a3aac52d74b23338f00bb0cfcb24/packages/cache/src/cache.ts#L527
// and https://github.com/actions/toolkit/blob/930c89072712a3aac52d74b23338f00bb0cfcb24/packages/cache/src/generated/results/api/v1/cache.ts#L19
const body = {
key,
version,
};
const bodyBuffer = Buffer.from(JSON.stringify(body), 'utf8');
const requestResult = __addDisposableResource(env_6, this.#request(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
'content-length': bodyBuffer.length,
},
}), false);
const { req, resPromise } = requestResult;
req.end(bodyBuffer);
const result = await resPromise;
if (result.ok && result.value.statusCode === /* Conflict */ 409) {
// We must have been racing with another concurrent process running the
// same script.
return undefined;
}
const response = await this.#maybeHandleServiceDown(result, script);
if (response === undefined) {
return undefined;
}
if (isOk(response)) {
const resData = JSON.parse(await readBody(response));
return resData.signed_upload_url;
}
throw new Error(`GitHub Cache reserve HTTP ${String(response.statusCode)} error: ${await readBody(response)}`);
}
catch (e_6) {
env_6.error = e_6;
env_6.hasError = true;
}
finally {
__disposeResources(env_6);
}
}
}
class GitHubActionsCacheHit {
#script;
#url;
#logger;
#applied = false;
constructor(script, location, logger) {
this.#script = script;
this.#url = location;
this.#logger = logger;
}
async apply() {
const env_7 = { stack: [], error: void 0, hasError: false };
try {
if (this.#applied) {
throw new Error('GitHubActionsCacheHit.apply was called more than once');
}
this.#applied = true;
const tempDir = __addDisposableResource(env_7, await makeTempDir(this.#script), true);
const tarballPath = pathlib.join(tempDir.path, 'cache.tgz');
try {
await this.#download(tarballPath);
}
catch (e) {
this.#logger.log({
type: 'info',
detail: 'cache-info',
script: this.#script,
message: `Failed to download GitHub Actions cache tarball: ${e?.message ?? String(e)}`,
});
// This is fine, it's as though there was nothing to restore from
// the cache.
return false;
}
await this.#extract(tarballPath);
return true;
}
catch (e_7) {
env_7.error = e_7;
env_7.hasError = true;
}
finally {
const result_2 = __disposeResources(env_7);
if (result_2)
await result_2;
}
}
async release() {
// This cache hit holds no resources before apply.
}
async #download(tarballPath) {
const env_8 = { stack: [], error: void 0, hasError: false };
try {
const requestResult = __addDisposableResource(env_8, request(this.#url), false);
const { req, resPromise } = requestResult;
req.end();
const result = await resPromise;
if (!result.ok) {
throw new Error(`GitHub Cache download TCP error`);
}
const response = result.value;
if (!isOk(response)) {
throw new Error(`GitHub Cache download HTTP ${String(response.statusCode)} error`);
}
const writeTarballStream = await fs.createWriteStream(tarballPath);
await new Promise((resolve, reject) => {
writeTarballStream.on('error', (error) => reject(error));
response.on('error', (error) => reject(error));
response.pipe(writeTarballStream);
writeTarballStream.on('close', () => {
resolve();
});
});
}
catch (e_8) {
env_8.error = e_8;
env_8.hasError = true;
}
finally {
__disposeResources(env_8);
}
}
#extract(tarballPath) {
return new Promise((resolve, reject) => {
// Same rationale as in #makeTarball: give tar a relative file path so a
// drive-lettered absolute path is not mistaken for a remote host.
execFile('tar', ['--extract', '--file', pathlib.basename(tarballPath), '--gzip', '-P'], { cwd: pathlib.dirname(tarballPath) }, (error) => {
if (error != null) {
reject(new Error(`tar error`, { cause: error }));
}
else {
resolve();
}
});
});
}
}
function request(url, options) {
const opts = {
...options,
headers: {
// https://github.com/actions/toolkit/blob/500d0b42fee2552ae9eeb5933091fe2fbf14e72d/packages/cache/src/internal/cacheHttpClient.ts#L67
'user-agent': 'actions/cache',
...options?.headers,
},
};
for (const [key, val] of Object.entries(opts.headers)) {
if (!val) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete opts.headers[key];
}
}
let req;
const resPromise = new Promise((resolve) => {
const parsed = typeof url === 'string' ? new URL(url) : url;
// https.request() throws ERR_INVALID_PROTOCOL for http: URLs.
const transport = parsed.protocol === 'http:' ? http : https;
req = transport.request(url, opts, (value) => {
resolve({ ok: true, value });
});
req.on('error', (error) => {
resolve({ ok: false, error });
});
req.on('socket', (socket) => {
socket.on('error', () => {
resolve({ ok: false, error: new Error('socket error') });
});
socket.on('close', (hadError) => {
if (hadError) {
resolve({ ok: false, error: new Error('socket closed with error') });
}
});
});
});
return {
req,
resPromise,
[Symbol.dispose]() {
req.destroy();
req.socket?.destroy();
},
};
}
function isOk(res) {
return (res.statusCode !== undefined &&
res.statusCode >= 200 &&
res.statusCode < 300);
}
function readBody(res) {
const chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
return new Promise((resolve, reject) => {
res.on('error', (error) => {
reject(error);
});
res.socket.on('error', () => {
reject(new Error('socket error'));
});
res.socket.on('close', (hadError) => {
if (hadError) {
reject(new Error('socket closed with error'));
}
});
res.on('end', () => {
resolve(Buffer.concat(chunks).toString());
});
});
}
async function makeTempDir(script) {
const path = await fs.mkdtemp(pathlib.join(getScriptDataDir(script), 'temp'));
return {
path,
async [Symbol.asyncDispose]() {
await fs.rm(path, { recursive: true });
},
};
}
//# sourceMappingURL=github-actions-cache.js.map