Add conditional JDK caching (#1201)

* Add JDK caching

Cache resolved JDK tool-cache entries by exact platform and release identity, with a default-on cache-jdk input and explicit opt-out.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Apply batched suggestions from code review

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix JDK cache CI validation

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Update brace-expansion security fix

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Refresh brace-expansion license metadata

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Refine JDK cache semantics

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Refine JDK cache documentation

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Simplify JDK cache identity

Use one normalized runner OS dimension, reset the internal cache key schema for the unreleased feature, and align documentation, tests, and bundles.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Align JDK cache OS identity

Use the established RUNNER_OS value directly and retain process.platform only as a non-Actions fallback.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* Harden JDK cache saves and document tool-cache reuse

Bind each JDK cache key to the installation identity it was computed for,
keep post-job saves best-effort per entry, and state the real reuse and
verification guarantee in the documentation.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs: restructure README caching section

Rename '## Caching dependencies' to '## Caching' and add a what-gets-cached
overview table covering the dependency, wrapper, and JDK caches. Lead with the
common 'cache: maven' example and the dependency-cache material, and demote JDK
caching into its own subsection.

Also corrects the IMPORTANT callout, which implied JDK caching required an
explicit opt-in; it is enabled implicitly whenever 'cache' is set.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs: fix caching documentation defects

- Remove pull-request framing that compared behavior to `main`; state the
  tool-cache and `jdkfile` behavior directly and unconditionally.
- Clarify that the JDK cache is a separate cache *entry* from the dependency
  and wrapper caches, while its *enablement* is coupled to `cache`, so the
  opening paragraph agrees with the enablement matrix.
- Cite the actions/setup-java-benchmarks repository instead of an open PR and
  a self-referential PR comment, keeping the measured figures and caveats.
- Keep the `cache`/`cache-jdk` matrix only in docs/advanced-usage.md and
  summarize the rules in prose in README.md to avoid divergence.
- Describe the guarantee that a cache key is only saved with the installation
  it was computed for, instead of documenting inode/size/timestamp internals.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs: add V6 what's new entry for JDK caching

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: e2755464-4e83-47b6-ba71-731bb481b418

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Copilot-Session: e2755464-4e83-47b6-ba71-731bb481b418
This commit is contained in:
Bruno Borges
2026-08-04 21:54:10 -04:00
committed by GitHub
co-authored by Copilot App Copilot Autofix powered by AI
parent 7a9a8b1dcc
commit 955f34f16f
26 changed files with 2756 additions and 827 deletions
+19 -6
View File
@@ -1,7 +1,11 @@
import * as core from '@actions/core';
import * as gpg from './gpg.js';
import * as constants from './constants.js';
import {getBooleanInput, isJobStatusSuccess} from './util.js';
import {
getBooleanInput,
isJdkCacheEnabled,
isJobStatusSuccess
} from './util.js';
import {fileURLToPath} from 'url';
async function removePrivateKeyFromKeychain() {
@@ -24,10 +28,11 @@ async function removePrivateKeyFromKeychain() {
* Check given input and run a save process for the specified package manager
* @returns Promise that will be resolved when the save process finishes
*/
async function saveCache() {
async function saveCaches() {
const jobStatus = isJobStatusSuccess();
const cache = core.getInput(constants.INPUT_CACHE);
if (!jobStatus || !cache) {
const cacheJdk = isJdkCacheEnabled(cache);
if (!jobStatus || (!cache && !cacheJdk)) {
return;
}
@@ -36,8 +41,16 @@ async function saveCache() {
return;
}
const {save} = await import('./cache.js');
await save(cache);
const saves: Promise<void>[] = [];
if (cache) {
const {save} = await import('./cache.js');
saves.push(save(cache));
}
if (cacheJdk) {
const {saveJdkCaches} = await import('./jdk-cache.js');
saves.push(saveJdkCaches());
}
await Promise.all(saves);
}
/**
@@ -59,7 +72,7 @@ async function ignoreError(promise: Promise<void>) {
export async function run() {
await removePrivateKeyFromKeychain();
await ignoreError(saveCache());
await ignoreError(saveCaches());
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
+1
View File
@@ -37,6 +37,7 @@ export const MAVEN_GPG_PASSPHRASE_DEFAULT_ENV = 'MAVEN_GPG_PASSPHRASE';
export const GPG_PASSPHRASE_PROFILE_ID = 'setup-java-gpg';
export const INPUT_CACHE = 'cache';
export const INPUT_CACHE_JDK = 'cache-jdk';
export const INPUT_CACHE_DEPENDENCY_PATH = 'cache-dependency-path';
export const INPUT_CACHE_PATH = 'cache-path';
export const INPUT_CACHE_READ_ONLY = 'cache-read-only';
+81 -3
View File
@@ -21,6 +21,7 @@ import {RetryingHttpClient} from '../retrying-http-client.js';
import os from 'os';
import {expectedDigestLength, verifyChecksum} from '../checksum.js';
import {normalizeArchitecture} from './platform-types.js';
import type {JdkCache} from '../jdk-cache.js';
export abstract class JavaBase {
protected http: httpm.HttpClient;
@@ -31,6 +32,7 @@ export abstract class JavaBase {
protected latest: boolean;
protected checkLatest: boolean;
protected forceDownload: boolean;
protected cacheJdk: boolean;
protected setDefault: boolean;
protected verifySignature: boolean;
protected verifySignaturePublicKey: string | undefined;
@@ -52,6 +54,7 @@ export abstract class JavaBase {
this.packageType = installerOptions.packageType;
this.checkLatest = installerOptions.checkLatest;
this.forceDownload = installerOptions.forceDownload ?? false;
this.cacheJdk = installerOptions.cacheJdk ?? false;
this.setDefault =
installerOptions.setDefault !== undefined
? installerOptions.setDefault
@@ -180,9 +183,48 @@ export abstract class JavaBase {
if (!this.forceDownload && foundJava?.version === javaRelease.version) {
core.info(`Resolved Java ${foundJava.version} from tool-cache`);
} else {
core.info('Trying to download...');
foundJava = await this.downloadTool(javaRelease);
core.info(`Java ${foundJava.version} was downloaded`);
let jdkCache: JdkCache | undefined;
if (this.cacheJdk) {
const {getJdkVerificationIdentity} =
await import('../jdk-cache.js');
jdkCache = {
distribution: this.distribution,
packageType: this.packageType,
architecture: this.architecture,
version: javaRelease.version,
source: this.getJdkReleaseIdentity(javaRelease),
verification: getJdkVerificationIdentity(
this.verifySignature,
this.verifySignaturePublicKey
),
path: this.getJdkCachePath(javaRelease.version)
};
}
if (!this.forceDownload && jdkCache) {
const {restoreJdk} = await import('../jdk-cache.js');
const restored = await restoreJdk(jdkCache);
if (restored) {
const restoredPath = this.getRestoredJdkPath(javaRelease.version);
if (restoredPath) {
foundJava = {
version: javaRelease.version,
path: restoredPath
};
}
}
}
if (!foundJava || foundJava.version !== javaRelease.version) {
core.info('Trying to download...');
foundJava = await this.downloadTool(javaRelease);
core.info(`Java ${foundJava.version} was downloaded`);
if (jdkCache) {
// Register after the installation exists so its identity is
// captured; the post-job save refuses to upload a path whose
// installation was replaced afterwards.
const {registerJdk} = await import('../jdk-cache.js');
registerJdk(jdkCache);
}
}
}
} catch (error: any) {
this.logSetupError(error);
@@ -299,6 +341,42 @@ export abstract class JavaBase {
return version.replace('+', '-');
}
protected getJdkCachePath(version: string): string {
const toolCache = process.env['RUNNER_TOOL_CACHE'];
if (!toolCache) {
return '';
}
return path.join(
toolCache,
this.toolcacheFolderName,
this.getToolcacheVersionName(version)
);
}
protected getRestoredJdkPath(version: string): string | null {
const basePath = this.getJdkCachePath(version);
if (!basePath) {
return null;
}
const architecturePath = path.join(basePath, this.architecture);
return fs.existsSync(architecturePath) &&
fs.existsSync(`${architecturePath}.complete`)
? architecturePath
: null;
}
private getJdkReleaseIdentity(javaRelease: JavaDownloadRelease): string {
if (javaRelease.checksum) {
return `${javaRelease.checksum.algorithm}:${javaRelease.checksum.value}`;
}
try {
const url = new URL(javaRelease.url);
return `${url.origin}${url.pathname}`;
} catch {
return javaRelease.url;
}
}
protected findInToolcache(): JavaInstallerResults | null {
// we can't use tc.find directly because firstly, we need to filter versions by stability flag
// if *-ea is provided, take only ea versions from toolcache, otherwise - only stable versions
+1
View File
@@ -4,6 +4,7 @@ export interface JavaInstallerOptions {
packageType: string;
checkLatest: boolean;
forceDownload?: boolean;
cacheJdk?: boolean;
setDefault?: boolean;
verifySignature?: boolean;
verifySignaturePublicKey?: string;
+67 -15
View File
@@ -12,6 +12,9 @@ import {
} from '../base-models.js';
import {extractJdkFile} from '../../util.js';
import {MACOS_JAVA_CONTENT_POSTFIX} from '../../constants.js';
import {createReadStream} from 'fs';
import {createHash} from 'crypto';
import type {JdkCache} from '../../jdk-cache.js';
export class LocalDistribution extends JavaBase {
constructor(
@@ -27,6 +30,11 @@ export class LocalDistribution extends JavaBase {
"The 'latest' version alias is not supported for the 'jdkfile' distribution. Please specify a concrete version."
);
}
if (this.verifySignature) {
throw new Error(
`Input 'verify-signature' is not supported for distribution '${this.distribution}'.`
);
}
let foundJava = this.forceDownload ? null : this.findInToolcache();
@@ -46,24 +54,60 @@ export class LocalDistribution extends JavaBase {
throw new Error(`JDK file was not found in path '${jdkFilePath}'`);
}
core.info(`Extracting Java from '${jdkFilePath}'`);
let jdkCache: JdkCache | undefined;
if (this.cacheJdk) {
const [{getJdkVerificationIdentity}, source] = await Promise.all([
import('../../jdk-cache.js'),
hashFile(jdkFilePath)
]);
jdkCache = {
distribution: this.distribution,
packageType: this.packageType,
architecture: this.architecture,
version: this.version,
source,
verification: getJdkVerificationIdentity(false),
path: this.getJdkCachePath(this.version)
};
}
if (!this.forceDownload && jdkCache) {
const {restoreJdk} = await import('../../jdk-cache.js');
const restored = await restoreJdk(jdkCache);
const restoredPath = restored
? this.getRestoredJdkPath(this.version)
: undefined;
if (restoredPath) {
foundJava = {
version: this.version,
path: restoredPath
};
}
}
const extractedJavaPath = await extractJdkFile(jdkFilePath);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const javaVersion = this.version;
if (!foundJava) {
core.info(`Extracting Java from '${jdkFilePath}'`);
const javaPath = await tc.cacheDir(
archivePath,
this.toolcacheFolderName,
this.getToolcacheVersionName(javaVersion),
this.architecture
);
const extractedJavaPath = await extractJdkFile(jdkFilePath);
const archiveName = fs.readdirSync(extractedJavaPath)[0];
const archivePath = path.join(extractedJavaPath, archiveName);
const javaVersion = this.version;
foundJava = {
version: javaVersion,
path: javaPath
};
const javaPath = await tc.cacheDir(
archivePath,
this.toolcacheFolderName,
this.getToolcacheVersionName(javaVersion),
this.architecture
);
foundJava = {
version: javaVersion,
path: javaPath
};
if (jdkCache) {
const {registerJdk} = await import('../../jdk-cache.js');
registerJdk(jdkCache);
}
}
}
// JDK folder may contain postfix "Contents/Home" on macOS
@@ -103,3 +147,11 @@ export class LocalDistribution extends JavaBase {
);
}
}
async function hashFile(file: string): Promise<string> {
const hash = createHash('sha256');
for await (const chunk of createReadStream(file)) {
hash.update(chunk);
}
return hash.digest('hex');
}
+239
View File
@@ -0,0 +1,239 @@
import {createHash} from 'crypto';
import fs from 'fs';
import path from 'path';
import * as cache from '@actions/cache';
import * as core from '@actions/core';
import {isCacheFeatureAvailable} from './cache-feature.js';
const STATE_JDK_CACHES = 'jdk-caches';
const JDK_CACHE_KEY_VERSION = 1;
export interface JdkCache {
distribution: string;
packageType: string;
architecture: string;
version: string;
source: string;
verification: string;
path: string;
}
interface JdkCacheState {
key: string;
path: string;
architecture: string;
matchedKey?: string;
// Cheap identity of the installation that occupied `path` when the entry was
// registered. The tool-cache path is shared per version/architecture, so a
// later step (e.g. one using `force-download`) can replace those bytes; the
// post-job save must not upload content that does not match the identity the
// key was computed for.
installation?: string;
}
const restoredCaches: JdkCacheState[] = [];
export async function restoreJdk(jdk: JdkCache): Promise<boolean> {
if (!jdk.path || !isCacheFeatureAvailable()) {
return false;
}
const key = buildJdkCacheKey(jdk);
let matchedKey: string | undefined;
try {
matchedKey = await cache.restoreCache([jdk.path], key);
} catch (error) {
core.warning(`Failed to restore JDK cache: ${(error as Error).message}`);
}
const architecturePath = path.join(jdk.path, jdk.architecture);
if (
matchedKey &&
(!fs.existsSync(architecturePath) ||
!fs.existsSync(`${architecturePath}.complete`))
) {
core.warning(
`JDK cache key ${matchedKey} was restored without the expected tool-cache path; downloading the JDK instead.`
);
matchedKey = undefined;
}
recordJdkCache({
key,
path: jdk.path,
architecture: jdk.architecture,
matchedKey
});
if (matchedKey) {
core.info(`JDK cache restored from key: ${matchedKey}`);
return true;
}
core.info(`JDK cache is not found for ${jdk.distribution} ${jdk.version}`);
return false;
}
export function registerJdk(jdk: JdkCache): void {
if (!jdk.path) {
return;
}
recordJdkCache({
key: buildJdkCacheKey(jdk),
path: jdk.path,
architecture: jdk.architecture,
installation: getInstallationIdentity(jdk.path, jdk.architecture)
});
}
/**
* Cheap fingerprint of the installation stored at a tool-cache path. The
* `<architecture>.complete` marker is (re)created by `tc.cacheDir` every time an
* installation is written, so its inode and timestamps change whenever the
* installation is replaced. This avoids rehashing a multi-hundred-megabyte JDK
* directory while still detecting that the bytes behind a key were swapped.
*/
function getInstallationIdentity(
jdkPath: string,
architecture: string
): string | undefined {
const architecturePath = path.join(jdkPath, architecture);
try {
const marker = fs.statSync(`${architecturePath}.complete`);
const installation = fs.statSync(architecturePath);
return [
marker.ino,
marker.mtimeMs,
marker.ctimeMs,
marker.size,
installation.ino,
installation.mtimeMs,
installation.ctimeMs
].join(':');
} catch {
return undefined;
}
}
export function getJdkVerificationIdentity(
verifySignature: boolean,
publicKey?: string
): string {
if (!verifySignature) {
return 'unverified';
}
if (!publicKey) {
return 'verified:bundled';
}
const normalizedKey = publicKey.replace(/\r\n?/g, '\n').trim();
const fingerprint = createHash('sha256').update(normalizedKey).digest('hex');
return `verified:custom:sha256:${fingerprint}`;
}
export async function saveJdkCaches(): Promise<void> {
const state = core.getState(STATE_JDK_CACHES);
if (!state) {
return;
}
const caches = parseJdkCacheState(state);
for (const jdk of caches) {
if (jdk.matchedKey === jdk.key) {
core.info(
`Cache hit occurred on the JDK primary key ${jdk.key}, not saving cache.`
);
continue;
}
if (!fs.existsSync(jdk.path)) {
core.debug(`JDK cache path does not exist, not saving: ${jdk.path}`);
continue;
}
if (!jdk.installation) {
core.debug(
`No JDK installation was registered for the key ${jdk.key}, not saving cache.`
);
continue;
}
if (
getInstallationIdentity(jdk.path, jdk.architecture) !== jdk.installation
) {
core.warning(
`The JDK installation in ${jdk.path} was replaced after it was registered for the key ${jdk.key}; not saving cache.`
);
continue;
}
try {
const cacheId = await cache.saveCache([jdk.path], jdk.key);
if (cacheId !== -1) {
core.info(`JDK cache saved with the key: ${jdk.key}`);
}
} catch (error) {
const err = error as Error;
if (err.name === cache.ReserveCacheError.name) {
core.info(err.message);
} else {
// Saving is best-effort and per entry: one failure must not suppress
// the remaining JDK caches.
core.warning(
`Failed to save the JDK cache with the key ${jdk.key}: ${err.message}`
);
}
}
}
}
export function buildJdkCacheKey(jdk: JdkCache): string {
const runnerOs = process.env['RUNNER_OS'] ?? process.platform;
const normalizedArchitecture = jdk.architecture.toLowerCase();
const identity = JSON.stringify({
keyVersion: JDK_CACHE_KEY_VERSION,
runnerOs,
distribution: jdk.distribution.toLowerCase(),
packageType: jdk.packageType.toLowerCase(),
architecture: normalizedArchitecture,
version: jdk.version,
source: jdk.source,
verification: jdk.verification
});
const digest = createHash('sha256').update(identity).digest('hex');
return `setup-java-jdk-v${JDK_CACHE_KEY_VERSION}-${runnerOs}-${normalizedArchitecture}-${digest}`;
}
function recordJdkCache(jdk: JdkCacheState): void {
const existing = restoredCaches.findIndex(
item => item.key === jdk.key && item.path === jdk.path
);
if (existing === -1) {
restoredCaches.push(jdk);
} else {
restoredCaches[existing] = {...restoredCaches[existing], ...jdk};
}
core.saveState(STATE_JDK_CACHES, JSON.stringify(restoredCaches));
}
function parseJdkCacheState(state: string): JdkCacheState[] {
const value: unknown = JSON.parse(state);
if (
!Array.isArray(value) ||
!value.every(
item =>
typeof item === 'object' &&
item !== null &&
typeof (item as JdkCacheState).key === 'string' &&
typeof (item as JdkCacheState).path === 'string' &&
typeof (item as JdkCacheState).architecture === 'string' &&
((item as JdkCacheState).matchedKey === undefined ||
typeof (item as JdkCacheState).matchedKey === 'string') &&
((item as JdkCacheState).installation === undefined ||
typeof (item as JdkCacheState).installation === 'string')
)
) {
throw new Error('Invalid JDK cache information retrieved from state.');
}
return value as JdkCacheState[];
}
+11 -1
View File
@@ -1,6 +1,10 @@
import fs from 'fs';
import * as core from '@actions/core';
import {getBooleanInput, getVersionFromFileContent} from './util.js';
import {
getBooleanInput,
getVersionFromFileContent,
isJdkCacheEnabled
} from './util.js';
import * as constants from './constants.js';
import * as path from 'path';
import {fileURLToPath} from 'url';
@@ -17,6 +21,7 @@ export async function run() {
const packageType = core.getInput(constants.INPUT_JAVA_PACKAGE);
const jdkFile = getJdkFileInput();
const cache = core.getInput(constants.INPUT_CACHE);
const cacheJdk = isJdkCacheEnabled(cache);
const cacheDependencyPath = core.getInput(
constants.INPUT_CACHE_DEPENDENCY_PATH
);
@@ -80,6 +85,7 @@ export async function run() {
packageType,
checkLatest,
forceDownload,
cacheJdk,
setDefault,
verifySignature,
verifySignaturePublicKey,
@@ -105,6 +111,7 @@ export async function run() {
packageType,
checkLatest,
forceDownload,
cacheJdk,
setDefault,
verifySignature,
verifySignaturePublicKey,
@@ -183,6 +190,7 @@ async function installVersion(
packageType,
checkLatest,
forceDownload,
cacheJdk,
setDefault,
verifySignature,
verifySignaturePublicKey,
@@ -194,6 +202,7 @@ async function installVersion(
packageType,
checkLatest,
forceDownload,
cacheJdk,
setDefault,
verifySignature,
verifySignaturePublicKey,
@@ -238,6 +247,7 @@ interface installerInputsOptions {
packageType: string;
checkLatest: boolean;
forceDownload: boolean;
cacheJdk: boolean;
setDefault: boolean;
verifySignature: boolean;
verifySignaturePublicKey: string | undefined;
+8 -1
View File
@@ -8,7 +8,8 @@ import * as tc from '@actions/tool-cache';
import * as httpm from '@actions/http-client';
import {
INPUT_JOB_STATUS,
DISTRIBUTIONS_ONLY_MAJOR_VERSION
DISTRIBUTIONS_ONLY_MAJOR_VERSION,
INPUT_CACHE_JDK
} from './constants.js';
import {OutgoingHttpHeaders} from 'http';
@@ -37,6 +38,12 @@ export function getBooleanInput(inputName: string, defaultValue = false) {
);
}
export function isJdkCacheEnabled(cache: string): boolean {
return core.getInput(INPUT_CACHE_JDK).trim()
? getBooleanInput(INPUT_CACHE_JDK)
: Boolean(cache.trim());
}
export function getVersionFromToolcachePath(toolPath: string) {
if (toolPath) {
return path.basename(path.dirname(toolPath));