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

cache: move gha cache save to post state #280

Merged
merged 1 commit into from
Mar 15, 2024
Merged
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
40 changes: 40 additions & 0 deletions __tests__/cache.test.itg.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Copyright 2024 actions-toolkit authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import path from 'path';
import {describe, expect, it} from '@jest/globals';

import {Cache} from '../src/cache';

// prettier-ignore
const tmpDir = path.join(process.env.TEMP || '/tmp', 'cache-jest');

const fixturesDir = path.join(__dirname, 'fixtures');

describe('cache', () => {
Copy link

Choose a reason for hiding this comment

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

for my own education - what does itg in the filename cache.test.itg.ts stand for?

Copy link
Member Author

@crazy-max crazy-max Mar 15, 2024

Choose a reason for hiding this comment

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

this is using a dedicated jest config for integration tests

testMatch: ['**/*.test.itg.ts'],

this way we can run each them on dedicated runners on ci:

test-itg:
runs-on: ${{ matrix.os }}
needs:
- prepare-itg
strategy:
fail-fast: false
matrix:
test: ${{ fromJson(needs.prepare-itg.outputs.matrix) }}
os:
- ubuntu-latest
#- macos-13 # https://github.com/docker/actions-toolkit/issues/279
- macos-latest
- windows-latest

https://github.com/docker/actions-toolkit/blob/main/jest.config.ts is for unit tests only.

it('github-repo', async () => {
const r = (Math.random() + 1).toString(36).substring(7);
const htcName = `cache-test-github-repo-${r}`;
const c = new Cache({
htcName: htcName,
htcVersion: `v1.0.0+${r}`,
baseCacheDir: path.join(tmpDir, '.cache-test'),
cacheFile: 'github-repo.json'
});
expect(await c.save(path.join(fixturesDir, 'github-repo.json'))).not.toEqual('');
expect(await c.find()).not.toEqual('');
});
});
39 changes: 36 additions & 3 deletions src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,20 @@ export interface CacheOpts {
ghaNoCache?: boolean;
}

export interface CachePostState {
dir: string;
key: string;
}

export class Cache {
private readonly opts: CacheOpts;
private readonly ghaCacheKey: string;
private readonly ghaNoCache?: boolean;
private readonly cacheDir: string;
private readonly cachePath: string;

private static readonly POST_CACHE_KEY = 'postCache';

constructor(opts: CacheOpts) {
this.opts = opts;
this.ghaCacheKey = util.format('%s-%s-%s', this.opts.htcName, this.opts.htcVersion, this.platform());
Expand All @@ -56,8 +63,14 @@ export class Cache {
core.debug(`Cache.save cached to hosted tool cache ${htcPath}`);

if (!this.ghaNoCache && cache.isFeatureAvailable()) {
core.debug(`Cache.save caching ${this.ghaCacheKey} to GitHub Actions cache`);
await cache.saveCache([this.cacheDir], this.ghaCacheKey);
core.debug(`Cache.save sending ${this.ghaCacheKey} to post state`);
core.saveState(
Cache.POST_CACHE_KEY,
JSON.stringify({
dir: this.cacheDir,
key: this.ghaCacheKey
} as CachePostState)
);
}

return cachePath;
Expand All @@ -75,7 +88,7 @@ export class Cache {
if (await cache.restoreCache([this.cacheDir], this.ghaCacheKey)) {
core.info(`Restored ${this.ghaCacheKey} from GitHub Actions cache`);
htcPath = await tc.cacheDir(this.cacheDir, this.opts.htcName, this.opts.htcVersion, this.platform());
core.info(`Restored to hosted tool cache ${htcPath}`);
core.info(`Cached to hosted tool cache ${htcPath}`);
return this.copyToCache(`${htcPath}/${this.opts.cacheFile}`);
}
} else if (this.ghaNoCache) {
Expand All @@ -87,6 +100,26 @@ export class Cache {
return '';
}

public static async post(): Promise<CachePostState | undefined> {
const state = core.getState(Cache.POST_CACHE_KEY);
if (!state) {
core.debug(`Cache.post no state`);
return Promise.resolve(undefined);
}
let cacheState: CachePostState;
try {
cacheState = <CachePostState>JSON.parse(state);
} catch (e) {
throw new Error(`Failed to parse cache post state: ${e}`);
}
if (!cacheState.dir || !cacheState.key) {
throw new Error(`Invalid cache post state: ${state}`);
}
core.info(`Caching ${cacheState.key} to GitHub Actions cache`);
await cache.saveCache([cacheState.dir], cacheState.key);
return cacheState;
}

private copyToCache(file: string): string {
core.debug(`Copying ${file} to ${this.cachePath}`);
fs.copyFileSync(file, this.cachePath);
Expand Down
9 changes: 7 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

import * as core from '@actions/core';

import {Cache} from './cache';

const isPost = !!process.env['STATE_isPost'];
if (!isPost) {
core.saveState('isPost', 'true');
Expand All @@ -36,7 +38,10 @@ export async function run(main: () => Promise<void>, post?: () => Promise<void>)
} catch (e) {
core.setFailed(e.message);
}
} else if (post) {
await post();
} else {
if (post) {
await post();
}
await Cache.post();
}
}