Files
toolkit/packages/cache/src/cache.ts
T

554 lines
16 KiB
TypeScript
Raw Normal View History

import * as core from '@actions/core'
2020-05-06 17:53:22 -04:00
import * as path from 'path'
2024-09-24 03:29:14 -07:00
import * as config from './internal/config'
2024-10-24 05:19:48 -07:00
import * as utils from './internal/cacheUtils'
import * as cacheHttpClient from './internal/cacheHttpClient'
2024-10-24 05:19:48 -07:00
import * as cacheTwirpClient from './internal/shared/cacheTwirpClient'
2024-09-24 03:17:44 -07:00
import { DownloadOptions, UploadOptions } from './options'
2024-10-24 05:19:48 -07:00
import { createTar, extractTar, listTar } from './internal/tar'
2024-06-17 01:17:10 -07:00
import {
2024-09-24 03:17:44 -07:00
CreateCacheEntryRequest,
CreateCacheEntryResponse,
FinalizeCacheEntryUploadRequest,
FinalizeCacheEntryUploadResponse,
GetCacheEntryDownloadURLRequest,
GetCacheEntryDownloadURLResponse
} from './generated/results/api/v1/cache'
import { CacheFileSizeLimit } from './internal/constants'
2024-10-24 05:19:48 -07:00
import { UploadCacheFile } from './internal/blob/upload-cache'
import { DownloadCacheFile } from './internal/blob/download-cache'
import { getBackendIdsFromToken, BackendIds } from '@actions/artifact/lib/internal/shared/util'
2020-05-12 14:47:31 -04:00
export class ValidationError extends Error {
constructor(message: string) {
super(message)
this.name = 'ValidationError'
2020-05-15 12:18:50 -04:00
Object.setPrototypeOf(this, ValidationError.prototype)
2020-05-12 14:47:31 -04:00
}
}
export class ReserveCacheError extends Error {
constructor(message: string) {
super(message)
this.name = 'ReserveCacheError'
2020-05-15 12:18:50 -04:00
Object.setPrototypeOf(this, ReserveCacheError.prototype)
2020-05-12 14:47:31 -04:00
}
}
2020-05-06 17:53:22 -04:00
function checkPaths(paths: string[]): void {
if (!paths || paths.length === 0) {
2020-05-12 14:47:31 -04:00
throw new ValidationError(
2020-05-06 17:53:22 -04:00
`Path Validation Error: At least one directory or file path is required`
)
}
}
function checkKey(key: string): void {
if (key.length > 512) {
2020-05-12 14:47:31 -04:00
throw new ValidationError(
2020-05-06 17:53:22 -04:00
`Key Validation Error: ${key} cannot be larger than 512 characters.`
)
}
const regex = /^[^,]*$/
if (!regex.test(key)) {
2020-05-12 14:47:31 -04:00
throw new ValidationError(
`Key Validation Error: ${key} cannot contain commas.`
)
2020-05-06 17:53:22 -04:00
}
}
2022-03-29 22:19:10 +00:00
/**
* isFeatureAvailable to check the presence of Actions cache service
*
* @returns boolean return true if Actions cache service feature is available, otherwise false
*/
2024-10-09 04:32:57 -07:00
export function isFeatureAvailable(): boolean {
2024-10-24 06:09:23 -07:00
return !!process.env['ACTIONS_CACHE_URL']
2024-10-09 04:32:57 -07:00
}
2022-03-29 22:19:10 +00:00
/**
* Restores cache from keys
*
2020-05-06 17:53:22 -04:00
* @param paths a list of file paths to restore from the cache
* @param primaryKey an explicit key for restoring the cache
* @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for key
* @param downloadOptions cache download options
* @param enableCrossOsArchive an optional boolean enabled to restore on windows any cache created on any platform
2020-05-15 12:18:50 -04:00
* @returns string returns the key for the cache hit, otherwise returns undefined
*/
export async function restoreCache(
2020-05-06 17:53:22 -04:00
paths: string[],
primaryKey: string,
restoreKeys?: string[],
options?: DownloadOptions,
enableCrossOsArchive = false
): Promise<string | undefined> {
2020-05-06 17:53:22 -04:00
checkPaths(paths)
2024-09-24 03:29:14 -07:00
const cacheServiceVersion: string = config.getCacheServiceVersion()
2024-10-09 04:32:57 -07:00
console.debug(`Cache service version: ${cacheServiceVersion}`)
2024-09-24 03:29:14 -07:00
switch (cacheServiceVersion) {
2024-06-17 01:17:10 -07:00
case "v2":
return await restoreCachev2(paths, primaryKey, restoreKeys, options, enableCrossOsArchive)
case "v1":
default:
return await restoreCachev1(paths, primaryKey, restoreKeys, options, enableCrossOsArchive)
}
}
/**
* Restores cache using the legacy Cache Service
*
* @param paths
* @param primaryKey
* @param restoreKeys
* @param options
* @param enableCrossOsArchive
* @returns
*/
2024-06-17 01:17:10 -07:00
async function restoreCachev1(
paths: string[],
primaryKey: string,
restoreKeys?: string[],
options?: DownloadOptions,
enableCrossOsArchive = false
) {
2020-05-06 17:53:22 -04:00
restoreKeys = restoreKeys || []
const keys = [primaryKey, ...restoreKeys]
2020-05-06 17:53:22 -04:00
core.debug('Resolved Keys:')
core.debug(JSON.stringify(keys))
2020-05-06 17:53:22 -04:00
if (keys.length > 10) {
2020-05-12 14:47:31 -04:00
throw new ValidationError(
2020-05-06 17:53:22 -04:00
`Key Validation Error: Keys are limited to a maximum of 10.`
)
}
for (const key of keys) {
checkKey(key)
}
const compressionMethod = await utils.getCompressionMethod()
let archivePath = ''
try {
// path are needed to compute version
const cacheEntry = await cacheHttpClient.getCacheEntry(keys, paths, {
compressionMethod,
enableCrossOsArchive
})
if (!cacheEntry?.archiveLocation) {
// Cache not found
return undefined
}
2020-05-06 17:53:22 -04:00
2023-01-17 17:12:42 +01:00
if (options?.lookupOnly) {
core.info('Lookup only - skipping download')
2022-12-23 12:44:35 +01:00
return cacheEntry.cacheKey
}
archivePath = path.join(
await utils.createTempDirectory(),
utils.getCacheFileName(compressionMethod)
)
core.debug(`Archive Path: ${archivePath}`)
2020-05-06 17:53:22 -04:00
// Download the cache from the cache entry
await cacheHttpClient.downloadCache(
cacheEntry.archiveLocation,
archivePath,
options
)
2020-05-06 17:53:22 -04:00
2020-11-26 01:56:57 +03:00
if (core.isDebug()) {
await listTar(archivePath, compressionMethod)
}
2021-05-03 18:09:44 +03:00
const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath)
2020-05-06 17:53:22 -04:00
core.info(
`Cache Size: ~${Math.round(
archiveFileSize / (1024 * 1024)
)} MB (${archiveFileSize} B)`
)
2020-05-06 17:53:22 -04:00
await extractTar(archivePath, compressionMethod)
2020-11-26 01:56:57 +03:00
core.info('Cache restored successfully')
return cacheEntry.cacheKey
} catch (error) {
const typedError = error as Error
if (typedError.name === ValidationError.name) {
throw error
} else {
// Supress all non-validation cache related errors because caching should be optional
core.warning(`Failed to restore: ${(error as Error).message}`)
}
2020-05-06 17:53:22 -04:00
} finally {
// Try to delete the archive to save space
try {
2020-05-06 17:53:22 -04:00
await utils.unlinkFile(archivePath)
} catch (error) {
2020-05-06 17:53:22 -04:00
core.debug(`Failed to delete archive: ${error}`)
}
}
2020-05-06 17:53:22 -04:00
return undefined
}
2024-10-09 04:32:57 -07:00
/**
* Restores cache using the new Cache Service
*
* @param paths a list of file paths to restore from the cache
* @param primaryKey an explicit key for restoring the cache
* @param restoreKeys an optional ordered list of keys to use for restoring the cache if no cache hit occurred for key
* @param downloadOptions cache download options
* @param enableCrossOsArchive an optional boolean enabled to restore on windows any cache created on any platform
* @returns string returns the key for the cache hit, otherwise returns undefined
*/
2024-06-17 01:17:10 -07:00
async function restoreCachev2(
paths: string[],
primaryKey: string,
restoreKeys?: string[],
options?: DownloadOptions,
enableCrossOsArchive = false
) {
restoreKeys = restoreKeys || []
const keys = [primaryKey, ...restoreKeys]
core.debug(`Resolved Keys: JSON.stringify(keys)`)
2024-06-17 01:17:10 -07:00
if (keys.length > 10) {
throw new ValidationError(
`Key Validation Error: Keys are limited to a maximum of 10.`
)
}
for (const key of keys) {
checkKey(key)
}
2024-10-09 04:32:57 -07:00
let archivePath = ''
2024-06-17 01:17:10 -07:00
try {
2024-10-09 04:32:57 -07:00
const twirpClient = cacheTwirpClient.internalCacheTwirpClient()
2024-06-24 01:16:11 -07:00
const backendIds: BackendIds = getBackendIdsFromToken()
2024-09-24 03:17:44 -07:00
const compressionMethod = await utils.getCompressionMethod()
2024-10-09 04:32:57 -07:00
2024-09-24 03:17:44 -07:00
const request: GetCacheEntryDownloadURLRequest = {
2024-06-24 01:16:11 -07:00
workflowRunBackendId: backendIds.workflowRunBackendId,
workflowJobRunBackendId: backendIds.workflowJobRunBackendId,
2024-09-24 03:17:44 -07:00
key: primaryKey,
restoreKeys: restoreKeys,
version: utils.getCacheVersion(
paths,
compressionMethod,
enableCrossOsArchive,
),
2024-06-17 01:17:10 -07:00
}
2024-10-09 04:32:57 -07:00
core.debug(`GetCacheEntryDownloadURLRequest: ${JSON.stringify(twirpClient)}`)
2024-09-24 03:17:44 -07:00
const response: GetCacheEntryDownloadURLResponse = await twirpClient.GetCacheEntryDownloadURL(request)
2024-10-09 04:32:57 -07:00
core.debug(`GetCacheEntryDownloadURLResponse: ${JSON.stringify(response)}`)
2024-06-17 01:17:10 -07:00
2024-09-24 03:17:44 -07:00
if (!response.ok) {
2024-06-17 01:17:10 -07:00
core.warning(`Cache not found for keys: ${keys.join(', ')}`)
return undefined
}
2024-09-24 03:17:44 -07:00
core.info(`Cache hit for: ${request.key}`)
2024-06-17 02:35:25 -07:00
2024-10-09 04:32:57 -07:00
if (options?.lookupOnly) {
core.info('Lookup only - skipping download')
return request.key
}
archivePath = path.join(
await utils.createTempDirectory(),
utils.getCacheFileName(compressionMethod)
)
core.debug(`Archive path: ${archivePath}`)
core.debug(`Starting download of artifact to: ${archivePath}`)
await DownloadCacheFile(
response.signedDownloadUrl,
archivePath
)
2024-10-09 04:32:57 -07:00
const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath)
core.info(
`Cache Size: ~${Math.round(
archiveFileSize / (1024 * 1024)
)} MB (${archiveFileSize} B)`
)
if (core.isDebug()) {
await listTar(archivePath, compressionMethod)
}
2024-10-09 04:32:57 -07:00
await extractTar(archivePath, compressionMethod)
core.info('Cache restored successfully')
return request.key
2024-06-17 01:17:10 -07:00
} catch (error) {
// TODO: handle all the possible error scenarios
2024-06-17 01:17:10 -07:00
throw new Error(`Unable to download and extract cache: ${error.message}`)
2024-10-09 04:32:57 -07:00
} finally {
try {
await utils.unlinkFile(archivePath)
} catch (error) {
core.debug(`Failed to delete archive: ${error}`)
}
2024-06-17 01:17:10 -07:00
}
return undefined
2024-06-17 01:17:10 -07:00
}
/**
2020-05-06 17:53:22 -04:00
* Saves a list of files with the specified key
*
2020-05-06 17:53:22 -04:00
* @param paths a list of file paths to be cached
* @param key an explicit key for restoring the cache
* @param enableCrossOsArchive an optional boolean enabled to save cache on windows which could be restored on any platform
* @param options cache upload options
2020-05-15 12:18:50 -04:00
* @returns number returns cacheId if the cache was saved successfully and throws an error if save fails
*/
export async function saveCache(
paths: string[],
key: string,
options?: UploadOptions,
enableCrossOsArchive = false
): Promise<number> {
2020-05-06 17:53:22 -04:00
checkPaths(paths)
checkKey(key)
2024-09-24 03:17:44 -07:00
2024-09-24 03:29:14 -07:00
const cacheServiceVersion: string = config.getCacheServiceVersion()
console.debug(`Cache Service Version: ${cacheServiceVersion}`)
switch (cacheServiceVersion) {
2024-06-13 03:16:59 -07:00
case "v2":
2024-06-17 02:39:45 -07:00
return await saveCachev2(paths, key, options, enableCrossOsArchive)
2024-06-13 03:16:59 -07:00
case "v1":
default:
2024-06-17 02:39:45 -07:00
return await saveCachev1(paths, key, options, enableCrossOsArchive)
2024-05-29 08:31:54 -07:00
}
2024-06-13 03:16:59 -07:00
}
2024-05-29 08:31:54 -07:00
/**
* Save cache using the legacy Cache Service
*
* @param paths
* @param key
* @param options
* @param enableCrossOsArchive
* @returns
*/
2024-06-13 03:16:59 -07:00
async function saveCachev1(
paths: string[],
key: string,
options?: UploadOptions,
enableCrossOsArchive = false
): Promise<number> {
2020-05-06 17:53:22 -04:00
const compressionMethod = await utils.getCompressionMethod()
let cacheId = -1
2020-05-06 17:53:22 -04:00
2020-05-12 14:47:31 -04:00
const cachePaths = await utils.resolvePaths(paths)
2020-05-06 17:53:22 -04:00
core.debug('Cache Paths:')
core.debug(`${JSON.stringify(cachePaths)}`)
2022-05-23 05:59:56 +00:00
if (cachePaths.length === 0) {
throw new Error(
`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`
2022-05-23 05:59:56 +00:00
)
2022-05-22 10:09:13 +00:00
}
2020-05-06 17:53:22 -04:00
const archiveFolder = await utils.createTempDirectory()
const archivePath = path.join(
archiveFolder,
utils.getCacheFileName(compressionMethod)
)
core.debug(`Archive Path: ${archivePath}`)
try {
await createTar(archiveFolder, cachePaths, compressionMethod)
if (core.isDebug()) {
await listTar(archivePath, compressionMethod)
}
2022-04-01 01:41:12 +05:30
const fileSizeLimit = 10 * 1024 * 1024 * 1024 // 10GB per repo limit
const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath)
core.debug(`File Size: ${archiveFileSize}`)
// For GHES, this check will take place in ReserveCache API with enterprise file size limit
if (archiveFileSize > fileSizeLimit && !utils.isGhes()) {
2022-04-01 01:41:12 +05:30
throw new Error(
`Cache size of ~${Math.round(
archiveFileSize / (1024 * 1024)
)} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`
)
}
core.debug('Reserving Cache')
const reserveCacheResponse = await cacheHttpClient.reserveCache(
key,
paths,
{
compressionMethod,
enableCrossOsArchive,
cacheSize: archiveFileSize
}
)
if (reserveCacheResponse?.result?.cacheId) {
cacheId = reserveCacheResponse?.result?.cacheId
} else if (reserveCacheResponse?.statusCode === 400) {
throw new Error(
reserveCacheResponse?.error?.message ??
2024-09-24 03:17:44 -07:00
`Cache size of ~${Math.round(
archiveFileSize / (1024 * 1024)
)} MB (${archiveFileSize} B) is over the data cap limit, not saving cache.`
)
} else {
throw new ReserveCacheError(
`Unable to reserve cache with key ${key}, another job may be creating this cache. More details: ${reserveCacheResponse?.error?.message}`
)
}
core.debug(`Saving Cache (ID: ${cacheId})`)
await cacheHttpClient.saveCache(cacheId, archivePath, options)
} catch (error) {
const typedError = error as Error
if (typedError.name === ValidationError.name) {
throw error
} else if (typedError.name === ReserveCacheError.name) {
core.info(`Failed to save: ${typedError.message}`)
} else {
core.warning(`Failed to save: ${typedError.message}`)
}
} finally {
// Try to delete the archive to save space
try {
await utils.unlinkFile(archivePath)
} catch (error) {
core.debug(`Failed to delete archive: ${error}`)
}
}
2020-05-06 17:53:22 -04:00
return cacheId
}
2024-06-13 03:16:59 -07:00
/**
* Save cache using the new Cache Service
*
* @param paths
* @param key
* @param options
* @param enableCrossOsArchive
* @returns
*/
2024-06-13 03:16:59 -07:00
async function saveCachev2(
paths: string[],
key: string,
options?: UploadOptions,
enableCrossOsArchive = false
): Promise<number> {
2024-06-24 01:16:11 -07:00
// BackendIds are retrieved form the signed JWT
const backendIds: BackendIds = getBackendIdsFromToken()
2024-09-24 03:17:44 -07:00
const compressionMethod = await utils.getCompressionMethod()
const twirpClient = cacheTwirpClient.internalCacheTwirpClient()
let cacheId = -1
const cachePaths = await utils.resolvePaths(paths)
core.debug('Cache Paths:')
core.debug(`${JSON.stringify(cachePaths)}`)
if (cachePaths.length === 0) {
2024-06-13 03:16:59 -07:00
throw new Error(
`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`
2024-06-13 03:16:59 -07:00
)
}
const archiveFolder = await utils.createTempDirectory()
const archivePath = path.join(
archiveFolder,
utils.getCacheFileName(compressionMethod)
2024-06-13 03:16:59 -07:00
)
core.debug(`Archive Path: ${archivePath}`)
try {
await createTar(archiveFolder, cachePaths, compressionMethod)
if (core.isDebug()) {
await listTar(archivePath, compressionMethod)
}
const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath)
core.debug(`File Size: ${archiveFileSize}`)
// For GHES, this check will take place in ReserveCache API with enterprise file size limit
if (archiveFileSize > CacheFileSizeLimit && !utils.isGhes()) {
throw new Error(
`Cache size of ~${Math.round(
archiveFileSize / (1024 * 1024)
)} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`
)
}
2024-09-24 03:17:44 -07:00
core.debug('Reserving Cache')
const version = utils.getCacheVersion(
paths,
compressionMethod,
enableCrossOsArchive
)
const request: CreateCacheEntryRequest = {
workflowRunBackendId: backendIds.workflowRunBackendId,
workflowJobRunBackendId: backendIds.workflowJobRunBackendId,
key: key,
version: version
}
const response: CreateCacheEntryResponse = await twirpClient.CreateCacheEntry(request)
core.info(`CreateCacheEntryResponse: ${JSON.stringify(response)}`)
// TODO: handle the error cases here
if (!response.ok) {
throw new ReserveCacheError(
`Unable to reserve cache with key ${key}, another job may be creating this cache.`
)
}
2024-06-13 03:16:59 -07:00
// TODO: mask the signed upload URL
core.debug(`Saving Cache to: ${response.signedUploadUrl}`)
await UploadCacheFile(
response.signedUploadUrl,
archivePath,
)
const finalizeRequest: FinalizeCacheEntryUploadRequest = {
workflowRunBackendId: backendIds.workflowRunBackendId,
workflowJobRunBackendId: backendIds.workflowJobRunBackendId,
key: key,
version: version,
sizeBytes: `${archiveFileSize}`,
}
const finalizeResponse: FinalizeCacheEntryUploadResponse = await twirpClient.FinalizeCacheEntryUpload(finalizeRequest)
core.debug(`FinalizeCacheEntryUploadResponse: ${JSON.stringify(finalizeResponse)}`)
if (!finalizeResponse.ok) {
throw new Error(
`Unable to finalize cache with key ${key}, another job may be finalizing this cache.`
)
}
// TODO: this is not great, we should handle the types without parsing
cacheId = parseInt(finalizeResponse.entryId)
} catch (error) {
const typedError = error as Error
core.debug(typedError.message)
} finally {
// Try to delete the archive to save space
try {
await utils.unlinkFile(archivePath)
} catch (error) {
core.debug(`Failed to delete archive: ${error}`)
}
}
return cacheId
2024-06-13 03:16:59 -07:00
}