diff --git a/.changeset/cache-options-for-build.md b/.changeset/cache-options-for-build.md new file mode 100644 index 000000000..1c99a3242 --- /dev/null +++ b/.changeset/cache-options-for-build.md @@ -0,0 +1,10 @@ +--- +"@cartesi/cli": minor +--- + +add --cache-from and --cache-to options to cartesi build + +Expose Docker Buildx cache backend options via `--cache-from ` and +`--cache-to ` CLI flags (repeatable). The same options can also be +set per-drive in `cartesi.toml` via `cache_from` and `cache_to` arrays. +CLI flags override the TOML values when provided. diff --git a/apps/cli/src/api/build.ts b/apps/cli/src/api/build.ts index c7d71185c..909d5df33 100644 --- a/apps/cli/src/api/build.ts +++ b/apps/cli/src/api/build.ts @@ -35,6 +35,20 @@ export type BuildOptions = ConfigOptions & */ debug?: boolean; + /** + * Docker Buildx cache sources (`--cache-from`) of every docker drive, + * replacing the ones of the configuration when not empty. + * @default [] + */ + cacheFrom?: string[]; + + /** + * Docker Buildx cache destinations (`--cache-to`) of every docker + * drive, replacing the ones of the configuration when not empty. + * @default [] + */ + cacheTo?: string[]; + /** * Only build the drives, do not boot the machine. * @default false @@ -65,6 +79,8 @@ export type BuildResult = { // context for Listr build tasks type BuildContext = { + cacheFrom: string[]; + cacheTo: string[]; config: Config; debug: boolean; destination: string; @@ -77,7 +93,7 @@ const buildDriveTask = ( ): ListrTask => ({ title: `Building drive ${chalk.cyan(name)}`, task: async (ctx, task) => { - const { config, debug, destination } = ctx; + const { cacheFrom, cacheTo, config, debug, destination } = ctx; const sdk = config.sdk; const reporter = (line: string) => { task.output = line; @@ -98,7 +114,12 @@ const buildDriveTask = ( case "docker": { const imageInfo = await buildDocker( name, - drive, + { + ...drive, + cacheFrom: + cacheFrom.length > 0 ? cacheFrom : drive.cacheFrom, + cacheTo: cacheTo.length > 0 ? cacheTo : drive.cacheTo, + }, sdk, destination, debug, @@ -151,7 +172,13 @@ const buildNvramTask = ( export const build = async ( options: BuildOptions = {}, ): Promise => { - const { debug = false, drivesOnly = false, progress = "silent" } = options; + const { + cacheFrom = [], + cacheTo = [], + debug = false, + drivesOnly = false, + progress = "silent", + } = options; // get application configuration, from a Config object or 'cartesi.toml' const config = resolveConfig(options.config); @@ -164,6 +191,8 @@ export const build = async ( // build context const ctx: BuildContext = { + cacheFrom, + cacheTo, config, debug, destination, diff --git a/apps/cli/src/builder/docker.ts b/apps/cli/src/builder/docker.ts index cf734bebc..9e48ae9f8 100644 --- a/apps/cli/src/builder/docker.ts +++ b/apps/cli/src/builder/docker.ts @@ -9,7 +9,13 @@ import type { BuildxMetadata } from "../types/docker.js"; type ImageBuildOptions = Pick< DockerDriveConfig, - "buildArgs" | "context" | "dockerfile" | "tags" | "target" + | "buildArgs" + | "cacheFrom" + | "cacheTo" + | "context" + | "dockerfile" + | "tags" + | "target" > & { destination: string; dockerfileContent?: string; reporter?: Reporter }; type ImageInfo = { @@ -25,6 +31,8 @@ type ImageInfo = { const buildImage = async (options: ImageBuildOptions): Promise => { const { buildArgs, + cacheFrom, + cacheTo, context, destination, dockerfile, @@ -62,6 +70,10 @@ const buildImage = async (options: ImageBuildOptions): Promise => { const metadataFile = path.join(tmpDir, "metadata.json"); args.push("--metadata-file", metadataFile); + // set cache options + args.push(...cacheFrom.flatMap((spec) => ["--cache-from", spec])); + args.push(...cacheTo.flatMap((spec) => ["--cache-to", spec])); + if (target) { args.push("--target", target); } diff --git a/apps/cli/src/commands/build.ts b/apps/cli/src/commands/build.ts index 2f4d638c2..296cd1ccd 100755 --- a/apps/cli/src/commands/build.ts +++ b/apps/cli/src/commands/build.ts @@ -36,12 +36,27 @@ export const createBuildCommand = () => { .default(false) .hideHelp(), ) + .option( + "--cache-from ", + "cache source for docker buildx build (can be repeated)", + (value: string, prev: string[]) => prev.concat([value]), + [] as string[], + ) + .option( + "--cache-to ", + "cache destination for docker buildx build (can be repeated)", + (value: string, prev: string[]) => prev.concat([value]), + [] as string[], + ) .option("-d, --drives-only", "only build drives, do not boot machine") .option("-v, --verbose", "verbose output", false) .action(async (options) => { - const { config, debug, drivesOnly, verbose } = options; + const { cacheFrom, cacheTo, config, debug, drivesOnly, verbose } = + options; const result = await build({ + cacheFrom, + cacheTo, config, debug, drivesOnly, diff --git a/apps/cli/src/config/defaults.ts b/apps/cli/src/config/defaults.ts index d227ceace..5e3b1719e 100644 --- a/apps/cli/src/config/defaults.ts +++ b/apps/cli/src/config/defaults.ts @@ -9,6 +9,8 @@ import type { Config, DriveConfig, MachineConfig } from "./types.js"; export const defaultRootDriveConfig = (): DriveConfig => ({ builder: "docker", buildArgs: [], + cacheFrom: [], + cacheTo: [], context: ".", dockerfile: "Dockerfile", // file on current working directory extraSize: 0, diff --git a/apps/cli/src/config/toml/drives.ts b/apps/cli/src/config/toml/drives.ts index 4f01199a9..4a2e16dfd 100644 --- a/apps/cli/src/config/toml/drives.ts +++ b/apps/cli/src/config/toml/drives.ts @@ -99,6 +99,8 @@ const BUILDER_KEYS: Record = { directory: ["directory", "extra_size", "format"], docker: [ "build_args", + "cache_from", + "cache_to", "context", "dockerfile", "extra_size", @@ -149,6 +151,8 @@ const parseBuilderDrive = (builder: Builder, drive: TomlTable): DriveConfig => { case "docker": { const { build_args, + cache_from, + cache_to, context, dockerfile, extra_size, @@ -163,6 +167,8 @@ const parseBuilderDrive = (builder: Builder, drive: TomlTable): DriveConfig => { return { builder: "docker", buildArgs: parseStringArray(build_args), + cacheFrom: parseStringArray(cache_from), + cacheTo: parseStringArray(cache_to), image: parseOptionalString(image), context: parseString(context, "."), dockerfile: parseString(dockerfile, "Dockerfile"), diff --git a/apps/cli/src/config/types.ts b/apps/cli/src/config/types.ts index 7575f63f2..ef414496e 100644 --- a/apps/cli/src/config/types.ts +++ b/apps/cli/src/config/types.ts @@ -25,6 +25,8 @@ export type DirectoryDriveConfig = { export type DockerDriveConfig = { builder: "docker"; buildArgs: string[]; // default is empty array + cacheFrom: string[]; // default is empty array + cacheTo: string[]; // default is empty array context: string; dockerfile: string; extraSize: number; // default is 0 (no extra size) diff --git a/apps/cli/tests/integration/builder/docker.test.ts b/apps/cli/tests/integration/builder/docker.test.ts index 3a2be20fc..801f565c2 100644 --- a/apps/cli/tests/integration/builder/docker.test.ts +++ b/apps/cli/tests/integration/builder/docker.test.ts @@ -1,4 +1,5 @@ import { + afterAll, afterEach, beforeAll, beforeEach, @@ -7,7 +8,9 @@ import { it, setDefaultTimeout, } from "bun:test"; +import { execa } from "execa"; import fs from "fs-extra"; +import crypto from "node:crypto"; import path from "node:path"; import { build } from "../../../src/builder/docker.js"; import type { DockerDriveConfig } from "../../../src/config.js"; @@ -38,6 +41,8 @@ describe("when building with the docker builder", () => { const drive: DockerDriveConfig = { buildArgs: [], builder: "docker", + cacheFrom: [], + cacheTo: [], context: ".", dockerfile: "Dockerfile", extraSize: 0, @@ -55,6 +60,8 @@ describe("when building with the docker builder", () => { const drive: DockerDriveConfig = { buildArgs: [], builder: "docker", + cacheFrom: [], + cacheTo: [], context: path.join(__dirname, "data"), dockerfile: "Dockerfile", extraSize: 0, @@ -72,6 +79,8 @@ describe("when building with the docker builder", () => { const drive: DockerDriveConfig = { buildArgs: [], builder: "docker", + cacheFrom: [], + cacheTo: [], context: path.join(__dirname, "fixtures"), dockerfile: path.join(__dirname, "fixtures", "Dockerfile"), extraSize: 0, @@ -90,6 +99,8 @@ describe("when building with the docker builder", () => { const drive: DockerDriveConfig = { buildArgs: [], builder: "docker", + cacheFrom: [], + cacheTo: [], context: path.join(__dirname, "fixtures"), dockerfile: path.join(__dirname, "fixtures", "Dockerfile"), extraSize: 0, @@ -108,6 +119,8 @@ describe("when building with the docker builder", () => { const drive: DockerDriveConfig = { buildArgs: [], builder: "docker", + cacheFrom: [], + cacheTo: [], context: path.join(__dirname, "fixtures"), dockerfile: path.join(__dirname, "fixtures", "Dockerfile"), extraSize: 0, @@ -122,3 +135,159 @@ describe("when building with the docker builder", () => { expect(stat.size).toEqual(29327360); }); }); + +describe("when using cache options", () => { + const image = TEST_SDK; + const CACHE_TEST_TAG = "cartesi-cli-integration-test-cache:latest"; + const CACHE_TEST_BUILDER = `cartesi-cli-test-${process.pid}`; + let previousBuilder: string | undefined; + let destination: string; + + // Use a disposable, test-owned builder so pruning its cache never touches + // the developer's own builders. BUILDX_BUILDER is process-scoped, so the + // builder selected by `docker buildx use` is left unchanged. + beforeAll( + async () => { + await execa("docker", [ + "buildx", + "create", + "--name", + CACHE_TEST_BUILDER, + "--driver", + "docker-container", + ]); + previousBuilder = process.env.BUILDX_BUILDER; + process.env.BUILDX_BUILDER = CACHE_TEST_BUILDER; + }, + { timeout: 60000 }, + ); + + afterAll(async () => { + if (previousBuilder === undefined) { + delete process.env.BUILDX_BUILDER; + } else { + process.env.BUILDX_BUILDER = previousBuilder; + } + await execa("docker", ["buildx", "rm", "--force", CACHE_TEST_BUILDER], { + reject: false, + }); + }); + + beforeEach(async () => { + destination = await createTempDir(); + }); + + afterEach(async () => { + await cleanupTempDir(destination); + }); + + it( + "should populate local cache when --cache-to is specified", + async () => { + const cacheDir = path.join(destination, "cache"); + const drive: DockerDriveConfig = { + buildArgs: [], + builder: "docker", + cacheFrom: [], + cacheTo: [`type=local,dest=${cacheDir}`], + context: path.join(__dirname, "fixtures"), + dockerfile: path.join( + __dirname, + "fixtures", + "Dockerfile.cache", + ), + extraSize: 0, + format: "ext2", + image: undefined, + tags: [CACHE_TEST_TAG], + target: undefined, + }; + + await build("root", drive, image, destination, false); + + // Clean up the tagged image + await execa("docker", ["image", "rm", CACHE_TEST_TAG], { + reject: false, + }); + + // Cache directory must have been written + expect(fs.existsSync(path.join(cacheDir, "index.json"))).toBe(true); + }, + { timeout: 120000 }, + ); + + it( + "should recover layers from local cache when --cache-from is specified", + async () => { + const cacheDir = path.join(destination, "cache"); + + // ── Build 1: populate local cache ──────────────────────────────── + const driveWithCacheTo: DockerDriveConfig = { + buildArgs: [], + builder: "docker", + cacheFrom: [], + cacheTo: [`type=local,dest=${cacheDir}`], + context: path.join(__dirname, "fixtures"), + dockerfile: path.join( + __dirname, + "fixtures", + "Dockerfile.cache", + ), + extraSize: 0, + format: "ext2", + image: undefined, + tags: [CACHE_TEST_TAG], + target: undefined, + }; + await build("root", driveWithCacheTo, image, destination, false); + + const hash1 = crypto + .createHash("sha256") + .update(fs.readFileSync(path.join(destination, "root.ext2"))) + .digest("hex"); + + // ── Teardown: remove image from daemon and build cache ──────────── + // Remove tagged image so BuildKit cannot reuse its layers implicitly + await execa("docker", ["image", "rm", CACHE_TEST_TAG], { + reject: false, + }); + // Remove all build-cache records (including non-dangling ones) from the + // test-owned builder selected through BUILDX_BUILDER + await execa("docker", ["buildx", "prune", "--all", "--force"]); + + // Remove build artefacts so the second build starts clean + await fs.remove(path.join(destination, "root.ext2")); + + // ── Build 2: rebuild using only the local cache ────────────────── + const driveWithCacheFrom: DockerDriveConfig = { + buildArgs: [], + builder: "docker", + cacheFrom: [`type=local,src=${cacheDir}`], + cacheTo: [], + context: path.join(__dirname, "fixtures"), + dockerfile: path.join( + __dirname, + "fixtures", + "Dockerfile.cache", + ), + extraSize: 0, + format: "ext2", + image: undefined, + tags: [], + target: undefined, + }; + await build("root", driveWithCacheFrom, image, destination, false); + + const hash2 = crypto + .createHash("sha256") + .update(fs.readFileSync(path.join(destination, "root.ext2"))) + .digest("hex"); + + // ── Attest: cache was recovered ────────────────────────────────── + // Identical hashes mean the RUN date layer was reused (not re-executed). + // A fresh build would produce a different timestamp → different content → different hash. + expect(hash2).toEqual(hash1); + }, + { timeout: 180000 }, + ); +}); diff --git a/apps/cli/tests/integration/builder/fixtures/Dockerfile.cache b/apps/cli/tests/integration/builder/fixtures/Dockerfile.cache new file mode 100644 index 000000000..09b14628c --- /dev/null +++ b/apps/cli/tests/integration/builder/fixtures/Dockerfile.cache @@ -0,0 +1,3 @@ +FROM --platform=linux/riscv64 ubuntu:24.04@sha256:3f83fb03282ef4e453bdf0060e0d83833bb3cf6e6f36f54d9b8517d311d78e03 +# Non-deterministic RUN: output changes each build unless the layer is reused from cache +RUN date +%s%N > /build-id.txt diff --git a/apps/cli/tests/integration/commands/build.test.ts b/apps/cli/tests/integration/commands/build.test.ts new file mode 100644 index 000000000..1e44bc0a9 --- /dev/null +++ b/apps/cli/tests/integration/commands/build.test.ts @@ -0,0 +1,131 @@ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + setDefaultTimeout, +} from "bun:test"; +import { execa } from "execa"; +import fs from "fs-extra"; +import crypto from "node:crypto"; +import os from "node:os"; +import path from "node:path"; +import { setupIntegrationTests, TEST_SDK } from "../config"; +import { cliPath } from "../devnet"; + +// each build is a riscv64 docker build plus the ext2 conversion +setDefaultTimeout(180000); + +// a non-deterministic RUN layer, so a reused layer is told from a rebuilt one +const dockerfile = path.join( + __dirname, + "..", + "builder", + "fixtures", + "Dockerfile.cache", +); + +// Exporting a local cache needs a docker-container builder. A disposable one +// owned by the test keeps the developer's builders untouched, and it is given +// to the CLI through its environment only. +const builder = `cartesi-cli-build-test-${process.pid}`; + +const sha256 = (file: string) => + crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); + +describe("build", () => { + let appDir: string; + + const build = (...args: string[]) => + execa("node", [cliPath, "build", "--drives-only", ...args], { + all: true, + cwd: appDir, + env: { BUILDX_BUILDER: builder }, + reject: false, + }); + + const writeConfig = (config = "") => + fs.writeFile( + path.join(appDir, "cartesi.toml"), + `sdk = "${TEST_SDK}"\n${config}`, + ); + + beforeAll(async () => { + await setupIntegrationTests(); + await execa("docker", [ + "buildx", + "create", + "--name", + builder, + "--driver", + "docker-container", + ]); + }); + + afterAll(async () => { + await execa("docker", ["buildx", "rm", "--force", builder], { + reject: false, + }); + }); + + beforeEach(async () => { + appDir = await fs.mkdtemp(path.join(os.tmpdir(), "build-cache-")); + await fs.copy(dockerfile, path.join(appDir, "Dockerfile")); + await writeConfig(); + }); + + afterEach(async () => { + await fs.remove(appDir); + }); + + it("should write and read the cache given by --cache-to and --cache-from", async () => { + const cache = path.join(appDir, "cache"); + const drive = path.join(appDir, ".cartesi", "root.ext2"); + + const first = await build("--cache-to", `type=local,dest=${cache}`); + expect(first.exitCode, first.all).toBe(0); + expect(fs.existsSync(path.join(cache, "index.json"))).toBe(true); + const hash = sha256(drive); + + // drop every layer the builder holds, so only the cache can give it back + await execa("docker", ["buildx", "prune", "--all", "--force"], { + env: { BUILDX_BUILDER: builder }, + }); + + const second = await build("--cache-from", `type=local,src=${cache}`); + expect(second.exitCode, second.all).toBe(0); + + // a rebuilt RUN layer writes another date, so another drive + expect(sha256(drive)).toEqual(hash); + }); + + it("should write the cache given by cache_to in cartesi.toml", async () => { + const cache = path.join(appDir, "toml-cache"); + await writeConfig( + `[drives.root]\ncache_to = ["type=local,dest=${cache}"]\n`, + ); + + const result = await build(); + expect(result.exitCode, result.all).toBe(0); + expect(fs.existsSync(path.join(cache, "index.json"))).toBe(true); + }); + + it("should prefer --cache-to over cache_to in cartesi.toml", async () => { + const tomlCache = path.join(appDir, "toml-cache"); + const flagCache = path.join(appDir, "flag-cache"); + await writeConfig( + `[drives.root]\ncache_to = ["type=local,dest=${tomlCache}"]\n`, + ); + + const result = await build( + "--cache-to", + `type=local,dest=${flagCache}`, + ); + expect(result.exitCode, result.all).toBe(0); + expect(fs.existsSync(path.join(flagCache, "index.json"))).toBe(true); + expect(fs.existsSync(tomlCache)).toBe(false); + }); +}); diff --git a/apps/cli/tests/unit/config.test.ts b/apps/cli/tests/unit/config.test.ts index daa42297b..9ba89ffaf 100644 --- a/apps/cli/tests/unit/config.test.ts +++ b/apps/cli/tests/unit/config.test.ts @@ -66,6 +66,8 @@ describe("when parsing the fixtures", () => { root: { builder: "docker", buildArgs: ["RELEASE=1"], + cacheFrom: ["type=gha"], + cacheTo: ["type=gha,mode=max"], context: "backend", dockerfile: "backend/Dockerfile", extraSize: 100 * 1024 * 1024, @@ -80,6 +82,8 @@ describe("when parsing the fixtures", () => { tools: { builder: "docker", buildArgs: [], + cacheFrom: [], + cacheTo: [], context: ".", dockerfile: "Dockerfile", extraSize: 0, @@ -207,6 +211,8 @@ shared = true`, root: { buildArgs: [], builder: "docker", + cacheFrom: [], + cacheTo: [], dockerfile: "backend/Dockerfile", context: ".", extraSize: 0, @@ -222,6 +228,19 @@ shared = true`, }); }); + it("should parse cache_from and cache_to for docker drive", () => { + const config = parse([ + `[drives.root] +builder = "docker" +cache_from = ["type=gha"] +cache_to = ["type=gha,mode=max"]`, + ]); + expect(config.drives.root).toMatchObject({ + cacheFrom: ["type=gha"], + cacheTo: ["type=gha,mode=max"], + }); + }); + /** * [machine] */ @@ -1451,7 +1470,7 @@ shared = true`, it("should fail for an unknown key in [drives.]", () => { expect(() => parse(['[drives.root]\nsise = "1Gi"'])).toThrowError( - "Unknown key 'sise' in [drives.root] (builder = \"docker\" by default), expected one of: accounts_drive, accounts_drive_size, build_args, builder, context, dockerfile, extra_size, format, image, mount, shared, tags, target, user", + "Unknown key 'sise' in [drives.root] (builder = \"docker\" by default), expected one of: accounts_drive, accounts_drive_size, build_args, builder, cache_from, cache_to, context, dockerfile, extra_size, format, image, mount, shared, tags, target, user", ); }); diff --git a/apps/cli/tests/unit/config/fixtures/full.toml b/apps/cli/tests/unit/config/fixtures/full.toml index 457237872..087fcd6ff 100644 --- a/apps/cli/tests/unit/config/fixtures/full.toml +++ b/apps/cli/tests/unit/config/fixtures/full.toml @@ -22,6 +22,8 @@ FOO = "bar" [drives.root] # the default builder, from a Dockerfile builder = "docker" build_args = ["RELEASE=1"] +cache_from = ["type=gha"] # docker buildx --cache-from specs, default is empty +cache_to = ["type=gha,mode=max"] # docker buildx --cache-to specs, default is empty context = "backend" # default is "." dockerfile = "backend/Dockerfile" # default is "Dockerfile" extra_size = "100Mb" # added to the size of the image contents, default is 0