cache/src/cacheHttpClient.ts

291 lines
8.3 KiB
TypeScript
Raw Normal View History

2019-10-30 14:48:49 -04:00
import * as core from "@actions/core";
import * as fs from "fs";
import { BearerCredentialHandler } from "typed-rest-client/Handlers";
2019-12-19 16:26:10 -05:00
import { HttpClient, HttpCodes } from "typed-rest-client/HttpClient";
2019-10-30 14:48:49 -04:00
import { IHttpClientResponse } from "typed-rest-client/Interfaces";
2019-12-13 15:19:25 -05:00
import {
IRequestOptions,
RestClient,
IRestResponse
} from "typed-rest-client/RestClient";
import {
ArtifactCacheEntry,
CommitCacheRequest,
ReserveCacheRequest,
2019-12-18 11:16:18 -05:00
ReserveCacheResponse
2019-12-13 15:19:25 -05:00
} from "./contracts";
import * as utils from "./utils/actionUtils";
function isSuccessStatusCode(statusCode: number): boolean {
return statusCode >= 200 && statusCode < 300;
}
2019-12-19 16:26:10 -05:00
function isRetryableStatusCode(statusCode: number): boolean {
const retryableStatusCodes = [
HttpCodes.BadGateway,
HttpCodes.ServiceUnavailable,
HttpCodes.GatewayTimeout
];
return retryableStatusCodes.includes(statusCode);
}
2019-12-13 15:19:25 -05:00
function getCacheApiUrl(): string {
2019-11-13 06:48:02 +09:00
// Ideally we just use ACTIONS_CACHE_URL
2019-12-13 15:19:25 -05:00
const baseUrl: string = (
2019-11-13 06:48:02 +09:00
process.env["ACTIONS_CACHE_URL"] ||
process.env["ACTIONS_RUNTIME_URL"] ||
""
).replace("pipelines", "artifactcache");
2019-12-13 15:19:25 -05:00
if (!baseUrl) {
2019-11-13 06:48:02 +09:00
throw new Error(
"Cache Service Url not found, unable to restore cache."
);
}
2019-12-13 15:19:25 -05:00
core.debug(`Cache Url: ${baseUrl}`);
return `${baseUrl}_apis/artifactcache/`;
2019-11-13 06:48:02 +09:00
}
function createAcceptHeader(type: string, apiVersion: string): string {
return `${type};api-version=${apiVersion}`;
}
function getRequestOptions(): IRequestOptions {
const requestOptions: IRequestOptions = {
2019-12-13 15:19:25 -05:00
acceptHeader: createAcceptHeader("application/json", "6.0-preview.1")
2019-11-13 06:48:02 +09:00
};
return requestOptions;
}
2019-12-18 11:02:14 -05:00
function createRestClient(): RestClient {
2019-10-30 14:48:49 -04:00
const token = process.env["ACTIONS_RUNTIME_TOKEN"] || "";
const bearerCredentialHandler = new BearerCredentialHandler(token);
2019-12-18 11:02:14 -05:00
return new RestClient("actions/cache", getCacheApiUrl(), [
2019-10-30 14:48:49 -04:00
bearerCredentialHandler
]);
2019-12-18 11:02:14 -05:00
}
export async function getCacheEntry(
keys: string[]
): Promise<ArtifactCacheEntry | null> {
const restClient = createRestClient();
const resource = `cache?keys=${encodeURIComponent(keys.join(","))}`;
2019-10-30 14:48:49 -04:00
const response = await restClient.get<ArtifactCacheEntry>(
resource,
getRequestOptions()
);
if (response.statusCode === 204) {
return null;
2019-10-30 14:48:49 -04:00
}
2019-12-13 15:19:25 -05:00
if (!isSuccessStatusCode(response.statusCode)) {
2019-10-30 14:48:49 -04:00
throw new Error(`Cache service responded with ${response.statusCode}`);
}
const cacheResult = response.result;
2019-12-13 15:19:25 -05:00
const cacheDownloadUrl = cacheResult?.archiveLocation;
if (!cacheDownloadUrl) {
2019-10-30 14:48:49 -04:00
throw new Error("Cache not found.");
}
2019-12-13 15:19:25 -05:00
core.setSecret(cacheDownloadUrl);
2019-11-21 14:37:32 -05:00
core.debug(`Cache Result:`);
core.debug(JSON.stringify(cacheResult));
2019-10-30 14:48:49 -04:00
return cacheResult;
}
async function pipeResponseToStream(
response: IHttpClientResponse,
stream: NodeJS.WritableStream
): Promise<void> {
return new Promise(resolve => {
response.message.pipe(stream).on("close", () => {
resolve();
});
});
}
2019-11-13 06:48:02 +09:00
export async function downloadCache(
2019-12-13 15:19:25 -05:00
archiveLocation: string,
2019-11-13 06:48:02 +09:00
archivePath: string
): Promise<void> {
const stream = fs.createWriteStream(archivePath);
const httpClient = new HttpClient("actions/cache");
2019-12-13 15:19:25 -05:00
const downloadResponse = await httpClient.get(archiveLocation);
2019-11-13 06:48:02 +09:00
await pipeResponseToStream(downloadResponse, stream);
}
2019-12-18 11:02:14 -05:00
// Reserve Cache
export async function reserveCache(key: string): Promise<number> {
const restClient = createRestClient();
2019-12-13 15:19:25 -05:00
const reserveCacheRequest: ReserveCacheRequest = {
key
};
2019-12-18 11:16:18 -05:00
const response = await restClient.create<ReserveCacheResponse>(
2019-12-13 15:19:25 -05:00
"caches",
2019-12-18 11:02:14 -05:00
reserveCacheRequest,
getRequestOptions()
2019-12-13 15:19:25 -05:00
);
2019-12-18 11:02:14 -05:00
return response?.result?.cacheId ?? -1;
2019-12-13 15:19:25 -05:00
}
2019-12-18 11:02:14 -05:00
function getContentRange(start: number, end: number): string {
2019-12-13 15:19:25 -05:00
// Format: `bytes start-end/filesize
// start and end are inclusive
// filesize can be *
// For a 200 byte chunk starting at byte 0:
// Content-Range: bytes 0-199/*
2019-12-18 11:02:14 -05:00
return `bytes ${start}-${end}/*`;
2019-12-13 15:19:25 -05:00
}
async function uploadChunk(
restClient: RestClient,
2019-12-18 11:02:14 -05:00
resourceUrl: string,
data: NodeJS.ReadableStream,
start: number,
end: number
2019-12-13 15:19:25 -05:00
): Promise<IRestResponse<void>> {
2019-12-18 11:02:14 -05:00
core.debug(
`Uploading chunk of size ${end -
start +
1} bytes at offset ${start} with content range: ${getContentRange(
start,
end
)}`
);
2019-12-13 15:19:25 -05:00
const requestOptions = getRequestOptions();
requestOptions.additionalHeaders = {
"Content-Type": "application/octet-stream",
2019-12-18 11:02:14 -05:00
"Content-Range": getContentRange(start, end)
2019-12-13 15:19:25 -05:00
};
2019-12-19 16:26:10 -05:00
const uploadChunkRequest = async (): Promise<IRestResponse<void>> => {
return await restClient.uploadStream<void>(
"PATCH",
resourceUrl,
data,
requestOptions
);
};
const response = await uploadChunkRequest();
if (isSuccessStatusCode(response.statusCode)) {
return response;
}
if (isRetryableStatusCode(response.statusCode)) {
const retryResponse = await uploadChunkRequest();
if (isSuccessStatusCode(retryResponse.statusCode)) {
return retryResponse;
}
}
throw new Error(
`Cache service responded with ${response.statusCode} during chunk upload.`
2019-12-13 15:19:25 -05:00
);
}
2019-12-18 11:02:14 -05:00
async function uploadFile(
2019-12-13 15:19:25 -05:00
restClient: RestClient,
cacheId: number,
archivePath: string
2019-11-13 06:48:02 +09:00
): Promise<void> {
2019-12-13 15:19:25 -05:00
// Upload Chunks
2019-12-18 11:02:14 -05:00
const fileSize = fs.statSync(archivePath).size;
const resourceUrl = getCacheApiUrl() + "caches/" + cacheId.toString();
const responses: IRestResponse<void>[] = [];
const fd = fs.openSync(archivePath, "r");
const concurrency = 4; // # of HTTP requests in parallel
const MAX_CHUNK_SIZE = 32000000; // 32 MB Chunks
core.debug(`Concurrency: ${concurrency} and Chunk Size: ${MAX_CHUNK_SIZE}`);
2019-12-13 15:19:25 -05:00
2019-12-18 11:02:14 -05:00
const parallelUploads = [...new Array(concurrency).keys()];
core.debug("Awaiting all uploads");
2019-12-13 15:19:25 -05:00
let offset = 0;
2019-12-18 11:02:14 -05:00
await Promise.all(
parallelUploads.map(async () => {
while (offset < fileSize) {
const chunkSize =
offset + MAX_CHUNK_SIZE > fileSize
? fileSize - offset
: MAX_CHUNK_SIZE;
const start = offset;
const end = offset + chunkSize - 1;
offset += MAX_CHUNK_SIZE;
const chunk = fs.createReadStream(archivePath, {
fd,
start,
end,
autoClose: false
});
responses.push(
await uploadChunk(
restClient,
resourceUrl,
chunk,
start,
end
)
);
}
})
);
2019-12-13 15:19:25 -05:00
2019-12-18 11:02:14 -05:00
fs.closeSync(fd);
2019-12-13 15:19:25 -05:00
const failedResponse = responses.find(
x => !isSuccessStatusCode(x.statusCode)
2019-10-30 14:48:49 -04:00
);
2019-12-13 15:19:25 -05:00
if (failedResponse) {
throw new Error(
`Cache service responded with ${failedResponse.statusCode} during chunk upload.`
);
}
2019-12-18 11:02:14 -05:00
return;
}
async function commitCache(
restClient: RestClient,
cacheId: number,
filesize: number
): Promise<IRestResponse<void>> {
const requestOptions = getRequestOptions();
const commitCacheRequest: CommitCacheRequest = { size: filesize };
return await restClient.create(
`caches/${cacheId.toString()}`,
commitCacheRequest,
requestOptions
);
}
export async function saveCache(
cacheId: number,
archivePath: string
): Promise<void> {
const restClient = createRestClient();
core.debug("Upload cache");
await uploadFile(restClient, cacheId, archivePath);
2019-12-13 15:19:25 -05:00
// Commit Cache
2019-12-18 11:02:14 -05:00
core.debug("Commiting cache");
2019-12-13 15:19:25 -05:00
const cacheSize = utils.getArchiveFileSize(archivePath);
const commitCacheResponse = await commitCache(
restClient,
cacheId,
cacheSize
);
if (!isSuccessStatusCode(commitCacheResponse.statusCode)) {
throw new Error(
`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`
);
2019-10-30 14:48:49 -04:00
}
core.info("Cache saved successfully");
}