cache/src/cacheHttpClient.ts

225 lines
6.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";
import { HttpClient } from "typed-rest-client/HttpClient";
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,
ReserverCacheResponse
} from "./contracts";
import * as utils from "./utils/actionUtils";
const MAX_CHUNK_SIZE = 4000000; // 4 MB Chunks
function isSuccessStatusCode(statusCode: number): boolean {
return statusCode >= 200 && statusCode < 300;
}
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-10-30 14:48:49 -04:00
export async function getCacheEntry(
keys: string[]
): Promise<ArtifactCacheEntry | null> {
2019-12-13 15:19:25 -05:00
const cacheUrl = getCacheApiUrl();
2019-10-30 14:48:49 -04:00
const token = process.env["ACTIONS_RUNTIME_TOKEN"] || "";
const bearerCredentialHandler = new BearerCredentialHandler(token);
2019-12-13 15:19:25 -05:00
const resource = `cache?keys=${encodeURIComponent(keys.join(","))}`;
2019-10-30 14:48:49 -04:00
const restClient = new RestClient("actions/cache", cacheUrl, [
bearerCredentialHandler
]);
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-13 15:19:25 -05:00
// Returns Cache ID
async function reserveCache(
restClient: RestClient,
key: string
): Promise<number> {
const reserveCacheRequest: ReserveCacheRequest = {
key
};
const response = await restClient.create<ReserverCacheResponse>(
"caches",
reserveCacheRequest
);
return response?.result?.cacheId || -1;
}
function getContentRange(start: number, length: number): string {
// 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/*
return `bytes ${start}-${start + length - 1}/*`;
}
async function uploadChunk(
restClient: RestClient,
cacheId: number,
data: Buffer,
offset: number
): Promise<IRestResponse<void>> {
const requestOptions = getRequestOptions();
requestOptions.additionalHeaders = {
"Content-Type": "application/octet-stream",
"Content-Range": getContentRange(offset, data.byteLength)
};
return await restClient.update(
cacheId.toString(),
data.toString("utf8"),
requestOptions
);
}
async function commitCache(
restClient: RestClient,
cacheId: number,
filesize: number
): Promise<IRestResponse<void>> {
const requestOptions = getRequestOptions();
const commitCacheRequest: CommitCacheRequest = { size: filesize };
return await restClient.create(
cacheId.toString(),
commitCacheRequest,
requestOptions
);
}
2019-11-13 06:48:02 +09:00
export async function saveCache(
key: string,
archivePath: string
2019-11-13 06:48:02 +09:00
): Promise<void> {
2019-10-30 14:48:49 -04:00
const token = process.env["ACTIONS_RUNTIME_TOKEN"] || "";
const bearerCredentialHandler = new BearerCredentialHandler(token);
2019-12-13 15:19:25 -05:00
const restClient = new RestClient("actions/cache", getCacheApiUrl(), [
2019-10-30 14:48:49 -04:00
bearerCredentialHandler
]);
2019-12-13 15:19:25 -05:00
// Reserve Cache
const cacheId = await reserveCache(restClient, key);
if (cacheId < 0) {
throw new Error(`Unable to reserve cache.`);
}
2019-10-30 14:48:49 -04:00
2019-12-13 15:19:25 -05:00
// Upload Chunks
const stream = fs.createReadStream(archivePath);
let streamIsClosed = false;
stream.on("close", () => {
streamIsClosed = true;
});
const uploads: Promise<IRestResponse<void>>[] = [];
let offset = 0;
while (!streamIsClosed) {
const chunk: Buffer = stream.read(MAX_CHUNK_SIZE);
uploads.push(uploadChunk(restClient, cacheId, chunk, offset));
offset += MAX_CHUNK_SIZE;
}
const responses = await Promise.all(uploads);
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.`
);
}
// Commit Cache
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");
}