Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Discussion: Is it better to remove OS from the cache key? #219

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 27 additions & 1 deletion __tests__/cache.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { mkdtempSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { restore, save } from '../src/cache';
import { computeCacheKey, findPackageManager, restore, save } from '../src/cache';
import * as fs from 'fs';
import * as os from 'os';
import * as core from '@actions/core';
Expand Down Expand Up @@ -92,6 +92,19 @@ describe('dependency cache', () => {
expect(spyWarning).not.toBeCalled();
expect(spyInfo).toBeCalledWith('maven cache is not found');
});
it('generates same cache key for every supported OS', async () => {
const packageManager = findPackageManager('maven');

process.env['RUNNER_OS'] = 'Windows';
const keyForWin = await computeCacheKey(packageManager);
process.env['RUNNER_OS'] = 'Linux';
const keyForLinux = await computeCacheKey(packageManager);
process.env['RUNNER_OS'] = 'macOS';
const keyForMacOS = await computeCacheKey(packageManager);

expect(keyForWin).toBe(keyForLinux);
expect(keyForWin).toBe(keyForMacOS);
});
});
describe('for gradle', () => {
it('throws error if no build.gradle found', async () => {
Expand All @@ -117,6 +130,19 @@ describe('dependency cache', () => {
expect(spyWarning).not.toBeCalled();
expect(spyInfo).toBeCalledWith('gradle cache is not found');
});
it('generates same cache key for every supported OS', async () => {
const packageManager = findPackageManager('gradle');

process.env['RUNNER_OS'] = 'Windows';
const keyForWin = await computeCacheKey(packageManager);
process.env['RUNNER_OS'] = 'Linux';
const keyForLinux = await computeCacheKey(packageManager);
process.env['RUNNER_OS'] = 'macOS';
const keyForMacOS = await computeCacheKey(packageManager);

expect(keyForWin).toEqual(keyForLinux);
expect(keyForWin).toEqual(keyForMacOS);
});
});
});
describe('save', () => {
Expand Down
10 changes: 6 additions & 4 deletions dist/cleanup/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -64536,7 +64536,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.save = exports.restore = void 0;
exports.save = exports.restore = exports.computeCacheKey = exports.findPackageManager = void 0;
const path_1 = __webpack_require__(622);
const os_1 = __importDefault(__webpack_require__(87));
const cache = __importStar(__webpack_require__(692));
Expand Down Expand Up @@ -64566,18 +64566,20 @@ function findPackageManager(id) {
}
return packageManager;
}
exports.findPackageManager = findPackageManager;
/**
* A function that generates a cache key to use.
* Format of the generated key will be "${{ platform }}-${{ id }}-${{ fileHash }}"".
* Format of the generated key will be "setup-java-${{ id }}-${{ fileHash }}"".
* If there is no file matched to {@link PackageManager.path}, the generated key ends with a dash (-).
* @see {@link https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows#matching-a-cache-key|spec of cache key}
*/
function computeCacheKey(packageManager) {
return __awaiter(this, void 0, void 0, function* () {
const hash = yield glob.hashFiles(packageManager.pattern.join('\n'));
return `${CACHE_KEY_PREFIX}-${process.env['RUNNER_OS']}-${packageManager.id}-${hash}`;
return `${CACHE_KEY_PREFIX}-${packageManager.id}-${hash}`;
});
}
exports.computeCacheKey = computeCacheKey;
/**
* Restore the dependency cache
* @param id ID of the package manager, should be "maven" or "gradle"
Expand All @@ -64592,7 +64594,7 @@ function restore(id) {
throw new Error(`No file in ${process.cwd()} matched to [${packageManager.pattern}], make sure you have checked out the target repository`);
}
const matchedKey = yield cache.restoreCache(packageManager.path, primaryKey, [
`${CACHE_KEY_PREFIX}-${process.env['RUNNER_OS']}-${id}`
`${CACHE_KEY_PREFIX}-${id}`
]);
if (matchedKey) {
core.saveState(CACHE_MATCHED_KEY, matchedKey);
Expand Down
10 changes: 6 additions & 4 deletions dist/setup/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18923,7 +18923,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.save = exports.restore = void 0;
exports.save = exports.restore = exports.computeCacheKey = exports.findPackageManager = void 0;
const path_1 = __webpack_require__(622);
const os_1 = __importDefault(__webpack_require__(87));
const cache = __importStar(__webpack_require__(692));
Expand Down Expand Up @@ -18953,18 +18953,20 @@ function findPackageManager(id) {
}
return packageManager;
}
exports.findPackageManager = findPackageManager;
/**
* A function that generates a cache key to use.
* Format of the generated key will be "${{ platform }}-${{ id }}-${{ fileHash }}"".
* Format of the generated key will be "setup-java-${{ id }}-${{ fileHash }}"".
* If there is no file matched to {@link PackageManager.path}, the generated key ends with a dash (-).
* @see {@link https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows#matching-a-cache-key|spec of cache key}
*/
function computeCacheKey(packageManager) {
return __awaiter(this, void 0, void 0, function* () {
const hash = yield glob.hashFiles(packageManager.pattern.join('\n'));
return `${CACHE_KEY_PREFIX}-${process.env['RUNNER_OS']}-${packageManager.id}-${hash}`;
return `${CACHE_KEY_PREFIX}-${packageManager.id}-${hash}`;
});
}
exports.computeCacheKey = computeCacheKey;
/**
* Restore the dependency cache
* @param id ID of the package manager, should be "maven" or "gradle"
Expand All @@ -18979,7 +18981,7 @@ function restore(id) {
throw new Error(`No file in ${process.cwd()} matched to [${packageManager.pattern}], make sure you have checked out the target repository`);
}
const matchedKey = yield cache.restoreCache(packageManager.path, primaryKey, [
`${CACHE_KEY_PREFIX}-${process.env['RUNNER_OS']}-${id}`
`${CACHE_KEY_PREFIX}-${id}`
]);
if (matchedKey) {
core.saveState(CACHE_MATCHED_KEY, matchedKey);
Expand Down
10 changes: 5 additions & 5 deletions src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const supportedPackageManager: PackageManager[] = [
}
];

function findPackageManager(id: string): PackageManager {
export function findPackageManager(id: string): PackageManager {
const packageManager = supportedPackageManager.find(packageManager => packageManager.id === id);
if (packageManager === undefined) {
throw new Error(`unknown package manager specified: ${id}`);
Expand All @@ -45,13 +45,13 @@ function findPackageManager(id: string): PackageManager {

/**
* A function that generates a cache key to use.
* Format of the generated key will be "${{ platform }}-${{ id }}-${{ fileHash }}"".
* Format of the generated key will be "setup-java-${{ id }}-${{ fileHash }}"".
* If there is no file matched to {@link PackageManager.path}, the generated key ends with a dash (-).
* @see {@link https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows#matching-a-cache-key|spec of cache key}
*/
async function computeCacheKey(packageManager: PackageManager) {
export async function computeCacheKey(packageManager: PackageManager) {
const hash = await glob.hashFiles(packageManager.pattern.join('\n'));
return `${CACHE_KEY_PREFIX}-${process.env['RUNNER_OS']}-${packageManager.id}-${hash}`;
return `${CACHE_KEY_PREFIX}-${packageManager.id}-${hash}`;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Guess it should be configurable.
As mentionned on twitter, it is rare but sometimes needed (native like jansi/netty/...).
Default shouldnt use it IMHO but should be possible to have it.
Alternatively, cache creation can check binary (.so) in jar presence maybe?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is rare but sometimes needed (native like jansi/netty/...).

ah I got it, Maven repo always serves same files but Maven project may use build profile to add dependencies only to specific OS. Gradle project can do similar build too.

In my current opinion, it's hard to provide a smart and high-speed feature detecting such dependency on OS. 😢
Then next consideration is how to make it configurable; but it may make the workflow file complex and nonintuitive. Here I imagine new settings like cache: os-dependent-maven and cache-key-strategy: os-dependent.

So I suggest making cache key OS independent for major use cases, and ask rare case users keep using actions/cache to make the deps cache OS dependent. Any thought?

Thanks again for making the product better with me 🙌

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as an user, I would expect the composite actions to expose the underlying composed actions and just - optionally - provide nice defaults if possible.
So overall it would be something like cache: <actions/cache configuration to merge with defaults of this action (lodash like merge)>.
If done, the key can stay OS dependent by default while the doc explicitly state that and shows how to drop the os specific part IMHO.
It will also enable to exclude or not part of the files (a common example is to exclude snapshots) quite easily.
So at the end, the feature can also be, to not have the cache by default until cache subaction is enabled by setting at least a key.
A warning can be logged if not done saying the build can be slow.
Something along those lines wouldn't shock me to be honest.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So overall it would be something like cache: <actions/cache configuration to merge with defaults of this action (lodash like merge)>.

Like below?

- uses: actions/setup-java@v2
   with:
     java-version: 11
     distribution: temurin
     cache:
       path: ~/.m2/repository
       key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
       restore-keys: |
         ${{ runner.os }}-maven-

I don't know that the Actions support nested (object type) input, though.
It's surely intuitive but brings limited benefit to shorten the workflow file, I think.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes
The benefit is to override the defaults properly (typically path including the repo but NOT *-SNAPSHOT for ex and key using pom.xml properly).
Overall point is that if the benefit is low, the benefit to include the cache should be the same - but I strongly think it is good to encourage it.
Maybe just checking the yaml has cache action defined it a good outcome instead of trying to merge them.
Will also be saner for all hybrid builds (we have more and more npm+mvn builds these days).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't have plans to add any customization of caching in scope of actions/setup-java. If you need customization, it is recomended to use actions/cache directly.
We had discussion about it when implemented caching for Node.js: https://github.com/actions/setup-node/blob/main/docs/adrs/0000-caching-dependencies.md#goals--anti-goals

We don't pursue the goal to provide wide customization of caching in scope of actions/setup-node action. The purpose of this integration is covering ~90% of basic use-cases. If user needs flexible customization, we should advice them to use actions/cache directly.

As for the removing platform from key, we will investigate it deeper

}

/**
Expand All @@ -73,7 +73,7 @@ export async function restore(id: string) {
}

const matchedKey = await cache.restoreCache(packageManager.path, primaryKey, [
`${CACHE_KEY_PREFIX}-${process.env['RUNNER_OS']}-${id}`
`${CACHE_KEY_PREFIX}-${id}`
]);
if (matchedKey) {
core.saveState(CACHE_MATCHED_KEY, matchedKey);
Expand Down