Skip to main content

Architecture

Overview​

A TypeScript library for reading rust-toolchain.toml and building rustup toolchain install commands, designed as a GitHub Action component. Inspired by dtolnay/rust-toolchain.

action.yml invokes dist/index.js twice per job — once as main, once as post — and src/index.ts is the single entry point for both, dispatching on STATE_isPost:

GitHub Actions Runner
|
┌─────┴────────┐
│ action.yml │ runs: node24, main AND post: dist/index.js
└─────┬────────┘
│
┌─────┴───────────────────────┐
│ src/index.ts │ Wiring only — dispatches on
│ STATE_isPost === "true"? │ STATE_isPost, set unconditionally
└───────┬──────────┬──────────┘ by the main phase's first line
│ no │ yes
v v
┌────────────────┐ ┌────────────────┐
│ run(deps) │ │ runPost(deps) │
│ src/action.ts │ │ src/action.ts │
└──┬───┬───┬───┬─┘ └───────┬────────┘
│ │ │ └─────┐ │
┌──┘ │ └───┐ │ v
v v v v saveLayers, then
┌──────┐┌──────┐┌───────┐┌─────────┐ writeSummarySafely
│ core ││config││builder││ outputs │ (src/cache/lifecycle.ts,
└──┬───┘└──┬───┘└───┬───┘└────┬────┘ src/cache/summary.ts)
│ │ │ │
└───┬───┘ │ │
v v v
┌────────────┐┌──────────┐┌─────────────┐
│ resolve/ ││Toolchain ││ flat keys + │
│ merge/parse││Spec ││ json output │
└────────────┘└────┬─────┘└─────────────┘
│
v
rustup install, then
resolveCacheLifecycle:
restoreLayers (src/cache/lifecycle.ts),
saveState("cache", plans+restored+budget)

run (the main phase) restores every enabled cache layer after the toolchain install and hands what it restored to the post phase through saveState; runPost (the post phase) reads that same state back through getState and saves whatever is left to save. See The Two Entrypoints And The State Handoff below.

src/lib.ts sits outside this flow: it is the library barrel for programmatic consumers, never loaded by the action itself.

Module Dependency Graph​

Two edges carry most of the design. src/index.ts is the only module that touches @actions/cache or the network: everything below it depends on the CacheClient interface in src/cache/client.ts and the RegistryClient interface in src/tools.ts, both type-only, so the tests never load the real SDK and never make an HTTP request. The two ports exist for the same reason and are wired the same way — the real @actions/cache adapter and the real crates.io fetch adapter are both built in src/index.ts, which nothing imports and the coverage gate cannot see. And src/action.ts fans out to the cache modules rather than the reverse — no cache module imports the orchestrator, which is what lets each one be tested against plain values.

The barrel src/lib.ts re-exports all twenty-two library modules; only its edge to src/action.ts is drawn, since the other twenty-one would say nothing but "the barrel exports everything". It deliberately does not re-export src/index.ts, whose import would execute the action — src/lib.test.ts asserts that exclusion.

Data Flow​

The cache lane hangs off generateSpecCacheKey: the same digest that keeps two toolchains' outputs apart is what keeps their target/ directories apart.

readCacheRequest and buildCacheOutputs are the seam: the main phase derives every layer's key and path set up front, publishes them through the cache output whether or not the lifecycle runs, and hands the same values to the post phase as CachePhaseState. A workflow that would rather drive actions/cache itself reads that output and ignores the rest.

Run Sequence​

run(deps) in src/action.ts, the main phase, in order. Everything below the dashed line happens only after the toolchain is installed.

Post-Phase Sequence​

runPost(deps), invoked by action.yml's post: when post-if is true — success() or cache-on-failure: true. It sees none of the main phase's locals; everything it needs crossed through saveState/getState.

Every rustup step is an argv array executed without a shell, bounded by a timeout, and retried up to three times with 1s/2s backoff.

Class Hierarchy​

Source File Map​

FileTypeExportsResponsibilities
src/index.tsEntry (node:child_process, node:fs)none — side-effecting scriptDependency wiring only, dispatching on STATE_isPost: for the main phase, hands real spawnSync, readFileSync, @actions/core and a synchronous sleep to run(); for the post phase, hands the real @actions/cache client and a node:fs-backed measure() to runPost(). Invisible to the coverage gate — see Cache Lifecycle
src/action.tsModulerun, runPost, ActionDeps, PostDeps, ExecResult, ExecOptionsMain phase (run) — rustup bootstrap, install, targets, components, default, RUSTUP_TOOLCHAIN, cargo env defaults, cache-lifecycle restore, outputs. Post phase (runPost) — replays the state run saved through saveState and saves whatever is left to save. Argv only, timeouts, retries
src/core.tsModule (smol-toml, node:crypto)parseRustToolchainToml, resolveChannel, generateCacheKey, generateSpecCacheKey, parseRustcVersion, typesTOML parsing, channel resolution/scaling/validation, cache key computation
src/config.tsModulemergeConfig, resolveRustupEnv, parseCommaList, typesMerge toml config with action inputs (scalars replaced by inputs; lists accumulate deduped, inputs leading) and validate identifiers; resolve RUSTUP_HOME/CARGO_HOME, honouring caller-supplied values
src/builder.tsClassesToolchainSpec, ToolchainSpecBuilderFluent builder pattern, rustup argv generation
src/outputs.tsModulebuildActionOutputs, toOutputEntries, ActionOutputs, ActionOutputsArgs, BooleanInput, CacheOutputs, CacheLayerOutput, provenance typesMaps the resolved spec plus its sources and the cache lifecycle's outcome onto the action's output surface; serialises lists as JSON arrays and the whole object as json
src/errors.tsModuledescribeErrorRenders a caught unknown as a message. Extracted because the error instanceof Error ? error.message : String(error) check was written out nine times across action.ts, cache/lifecycle.ts and core.ts
src/inputs.tsModulereadBooleanInput, InputReaderShared YAML-boolean input parsing, used by both action.ts and cache/inputs.ts — belongs to neither on its own
src/cache/layers.tsModuleCACHE_LAYER_IDS, CacheLayerId, parseCacheLayersThe canonical layer list (registry, build, bin) and the cache-layers input parser
src/cache/keys.tsModulejoinKeySegments, buildLayerKey, CacheKeyContext, CacheLayerKeyPer-layer key and restore-key ladder derivation; the build key folds in envHash
src/cache/inputs.tsModulereadCacheRequest, buildCacheOutputs, CacheRequest, CacheInputSourceValidates every cache-* input before anything installs (readCacheRequest, fails fast on a bad cache-key-hash or an oversized key); completes the validated request into per-layer keys once the spec digest exists (buildCacheOutputs)
src/cache/env.tsModule (node:crypto)hashBuildEnvDigests the CARGO_*/CC/CFLAGS/CXX/CMAKE/RUST* environment into the build key's envHash segment, so jobs differing only in RUSTFLAGS stop sharing a key
src/cache/paths.tsModule (node:path)parseWorkspaces, registryPaths, buildPaths, binPaths, RUSTUP_SHIMS, WorkspaceReads cache-workspaces into resolved <manifest-dir> -> <target-dir> mappings, refusing anything outside the checkout; the registry layer's fixed paths; the build layer's paths as a files-only glob set — <target>/** plus !<target>/**/incremental/**, !<target>/**/examples/** and the two directory negations that keep the manifest free of directories; the bin layer's paths the same way, negating each of the fourteen RUSTUP_SHIMS names and its .exe twin so a toolchain bump cannot invalidate the tool cache
src/cache/budget.tsModuleparseSize, measurePaths, StatFsReads cache-budget into a byte count (binary suffixes, 0 disables it); sums a layer's on-disk size through an injected StatFs port
src/tools.tsModule (node:crypto)parseToolSpecs, resolveToolVersions, hashToolSet, ensureTools, parseToolVersion, RegistryClient, ResolvedTool, ToolResolution, UNRESOLVED_VERSIONOwns cargo-tools end to end: parses and validates <name>[@<version>][:<binary>] entries before any command runs, resolves latest through the RegistryClient port with backoff, digests the resolved set into the bin key, and installs only what the restore did not supply. A pinned version never reaches the client, so a registry outage cannot affect it; the :<binary> suffix redirects the version probe only, and is excluded from both the key and the output
src/msrv.tsModule (smol-toml)parseVersion, compareVersions, parseMsrvPolicy, parseCargoManifest, effectiveMsrv, evaluateMsrv, describeVerdict, Version, MsrvPolicy, MsrvSource, ManifestMsrv, MsrvRequirement, MsrvVerdictPure functions, no I/O: parses a Cargo.toml's rust-version (including workspace inheritance and the rust-version.workspace = true trap), compares versions numerically, and finds the maximum requirement across cache/metadata.ts's resolved graph. evaluateMsrv never fails a build itself — it returns a verdict action.ts decides what to do with
src/cache/metadata.tsModuleparsePackageSet, parsePackageMsrv, MetadataReader, PackageSet, PackageId, PackageMsrvReads cargo metadata --format-version 1 --locked into the packages a workspace still resolves to, with its own crates separated (parsePackageSet), and separately into every package's declared rust_version (parsePackageMsrv, lenient where the former is strict — a malformed entry costs its own contribution, not the whole check). Matches workspace_members against package ids verbatim rather than parsing them, since cargo spells ids at least three ways
src/cache/prune.tsModulePrunePolicy, parsePrunePolicy, readFingerprints, computeKeepSet, Fingerprints, DirReaderDecides which files under target/ the archive carries. Recovers ownership from the <name>-<hash> fingerprint directories cargo already writes — authoritative, where rust-cache strips a trailing -$hash off a filename and guesses. Nothing here deletes; the keep-set selects what is linked into the stage
src/cache/stage.tsModuleSTAGE_DIR_NAME, buildStageRoots, registryStageRoot, stagePaths, stagedLocation, unstagedLocation, stageFiles, unstageFiles, StageRoot, StageFs, StageOutcomeKeeps a pruned layer's paths array constant. @actions/cache matches an entry on (key, sha256(paths.join("|") | compressionMethod | salt)), so narrowing the array to a keep-set writes entries no restore can ever find — the restore does not yet know the content. A staged layer archives one fixed directory per tree instead: stageFiles hard-links the keep-set in before a save, unstageFiles moves it back after a restore, and the working tree is never modified
src/cache/fs.tsModule (node:fs)walkFiles, nodeStatFs, nodeStageFsThe real node:fs implementations of StatFs and StageFs. They lived in src/index.ts until a fake that disagreed with readdirSync about a missing directory cost every pruned layer its save; nothing here vendors an SDK or touches the network, so the coverage exemption they inherited by proximity was never earned. fs.test.ts holds them to a real temp directory — the hard link's shared inode and mtime included
src/cache/client.tsModuleCacheClientThe restore/save port. The only real implementation wraps @actions/cache and lives in src/index.ts, which nothing imports and the coverage gate does not measure
src/cache/lifecycle.tsModulerestoreLayers, saveLayers, LayerPlan, RestoredLayer, SavedLayer, LayerResult, LifecycleLog, SaveArgsRestores every enabled layer concurrently, downgrading any failure to a miss; decides whether each layer is worth saving — skip on an exact hit, skip when its size can't be measured, skip over budget — and saves the rest concurrently
src/cache/summary.tsModulerenderSummaryRenders the per-layer restore/save outcome as the job summary's Markdown table
src/lib.tsBarrelre-exports action, builder, cache/budget, cache/client, cache/env, cache/fs, cache/inputs, cache/keys, cache/layers, cache/lifecycle, cache/metadata, cache/paths, cache/prune, cache/stage, cache/summary, config, core, errors, inputs, msrv, outputs, tools — never indexThe library surface under one specifier, for consumers that would rather import @rust-toolchain than twenty-two modules

src/lib.ts is the barrel; individual modules can still be imported directly and are cheaper, since the barrel loads all twenty-two.

Why the barrel excludes src/index.ts​

src/index.ts calls run() at the top level, so it is the one module in the tree whose import has a side effect — it shells out to rustup. Keeping it out of src/lib.ts is what makes that side effect unreachable to a consumer, and src/lib.test.ts asserts the exclusion in source rather than trusting a comment to survive.

Why library source imports itself as @rust-toolchain/*​

Every module under src/ imports its siblings through the package specifier (import … from "@rust-toolchain/config"), not through ./config and not through the short @/ alias. A path alias is a consumer-visible detail: when a sibling project maps @rust-toolchain/* at its own root, the library's internal imports resolve there too, because they use the very specifier the consumer mapped. An internal-only alias breaks that — a package whose source says @/config typechecks in its own repo and fails in every consumer with TS2307: Cannot find module '@/config'.

@/* is mapped as a short form but confined to tests, which are never consumed. It must not appear in library source: a consumer almost certainly has their own @/ pointing at their own src, so the import would resolve into their tree.

See README → Consuming from Another TypeScript Project.

Build Pipeline​

Testing Strategy​

All tests use Bun's built-in test runner with 100% coverage enforced by bunfig.toml.

FileTestsCoverage Target
src/action.test.tsrun against injected fakes — argv shape, timeouts, retry/backoff, spawn errors, rustup bootstrap (POSIX + Windows), cargo env defaults, tolerated rustup default, set-rustup-toolchain, outputs100%
src/core.test.tsparseRustToolchainToml, resolveChannel (release-day table, bare-minor scaling, rejected names), generateCacheKey, generateSpecCacheKey, parseRustcVersion100% lines, functions, statements
src/config.test.tsmergeConfig — toml vs input priority, target alias, default channel, identifier validation; resolveRustupEnv — env overrides, blank handling, HOME fallback, Windows paths100%
src/builder.test.tsToolchainSpecBuilder fluent chain, ToolchainSpec direct construction, argv generation and batching, install flags100%
src/outputs.test.tsbuildActionOutputs — resolved values, empty-list and absent-profile edges, inputs/toml provenance; toOutputEntries — JSON array serialisation, string booleans, json key order100%
src/cache/layers.test.tsCACHE_LAYER_IDS, parseCacheLayers — separators, dedup, unknown-layer and empty-selection rejection100%
src/cache/keys.test.tsjoinKeySegments — segment collapsing; buildLayerKey — registry vs. build key shape, restore-key ladders100%
src/cache/env.test.tshashBuildEnv — prefix matching, the exclusion deny-list, order independence, and stability across the action's own exportVariable calls100%
src/cache/paths.test.tsparseWorkspaces — mapping syntax and escape rejection; registryPaths; buildPaths — the files-only manifest shape that makes the negation globs effective100%
src/cache/budget.test.tsparseSize — binary suffixes and unparseable input; measurePaths — byte totals and the unmeasured fallback100%
src/cache/inputs.test.tsreadCacheRequest — every cache-* input, defaults and validation; buildCacheOutputs — the cache JSON object and cache-hit100%
src/cache/lifecycle.test.tsrestoreLayers — exact/partial/miss classification; saveLayers — skip-on-exact-hit, budget refusal, per-layer failure isolation100%
src/cache/metadata.test.tsparsePackageSet — the cargo metadata shape, workspace members called out separately, and rejection of malformed or truncated JSON100%
src/cache/prune.test.tsparsePrunePolicy; readFingerprints — the <name>-<hash> recovery, tolerant of an absent directory; computeKeepSet — attribution, unattributable handling per policy, and the refusal to mark an empty set usable100%
src/cache/stage.test.tsbuildStageRoots/registryStageRoot/stagePaths — the content-free paths array; stagedLocation/unstagedLocation — the stage-recursion and prefix guards; stageFiles/unstageFiles — link, move, and per-file failure counting100%
src/cache/fs.test.tsThe real node:fs adapters against a REAL temp directory: walkFiles on a missing directory, nodeStatFs throwing where walkFiles swallows, and the hard link's shared inode and mtime100%
src/cache/summary.test.tsrenderSummary — the job-summary table rendered from CachePhaseState100%
src/tools.test.tsparseToolSpecs; resolveToolVersions — registry retry, backoff growth and degradation to UNRESOLVED_VERSION; hashToolSet; ensureTools — the absent/mute/wrong-version probe split and the exact-bin-hit shortcut100%
src/msrv.test.tsparseVersion/compareVersions — the 1.9 vs 1.10 numeric case; parseMsrvPolicy; parseCargoManifest — [package], [workspace.package], the rust-version.workspace = true inheritance trap, and rejection of invalid TOML; effectiveMsrv/evaluateMsrv/describeVerdict — the cargo-binstall/vergen fixture where a dependency outruns the crate's own declaration100%
src/inputs.test.tsreadBooleanInput — defaults, casing, and rejection of non-boolean text100%
src/errors.test.tsdescribeError — Error instances and arbitrary thrown values100%
src/lib.test.tsBarrel surface pinned export by export, and the guard that src/lib.ts never re-exports src/index.ts; both path aliases resolve100%

Twenty-two test files cover twenty-two library modules. src/cache/client.ts declares the CacheClient interface and nothing else, so it compiles to no executable statements and never reaches the coverage report — the port exists precisely so the tests can drive the lifecycle without @actions/cache. src/index.ts is absent for the opposite reason: it is excluded through coveragePathIgnorePatterns because nothing imports it, which is why orchestration lives in src/action.ts behind the injected ActionDeps.

The release-cycle cases are pinned against real rust-lang.org release dates rather than against this codebase's own arithmetic, so a drifting epoch fails the suite instead of being reflected by it.

Mutation Testing​

Coverage says every line ran. It says nothing about whether an assertion would notice the line being wrong, and this codebase is dense with thresholds and equality checks where those are very different claims. Mutation testing closes that gap by changing the source and asking whether the suite fails.

mise run mutate # the configured scope
mise run mutate src/cache/keys.ts # one module, seconds instead of minutes

It is deliberately not a gate. thresholds.break is unset in stryker.config.json, so a score is reported and nothing exits non-zero on it. Several survivors are equivalent mutants — changes no test can detect because they cannot change behaviour — and under a threshold each would buy a contrived test written to satisfy the tool rather than to describe the code.

Three mechanics are easy to get wrong and are worth stating:

  • Stryker runs under Node, not Bun. Its Babel instrumenter depends on CJS default-export interop that Bun implements differently, so bunx --bun fails before the first mutant with generator is not a function. Only the command it shells out to is bun test.
  • stryker-bunfig.toml is load-bearing. The command runner judges a mutant by exit code, and bunfig.toml enforces 100% coverage. Stryker instruments each mutated file with mutant-switch branches that cannot all be reached in one run, so coverage drops, bun test exits non-zero with every test passing, and Stryker records a kill. That inflates the score silently — every mutant looks dead, including the survivors. bun test has --coverage to switch coverage on and nothing to switch it off, so a second config file is the only lever.
  • The config file is a positional argument. There is no --configFile flag.

What it is good at is auditing assertion strength for code that exists. What it cannot see is a test double that misrepresents the real thing — that failure mode lives in src/cache/fs.test.ts, which is why those adapters are exercised against a real filesystem rather than a fake.

Key Design Decisions​

TOML-First, Override by Inputs​

The action reads rust-toolchain.toml by default and merges it with action inputs. Inputs win on conflict. This mirrors the dtolnay/rust-toolchain behavior but adds explicit profile support.

Fluent Builder Pattern​

ToolchainSpecBuilder provides a fluent API with method chaining:

new ToolchainSpecBuilder()
.withChannel("stable")
.withTargets("wasm32-unknown-unknown")
.withComponents("clippy", "rustfmt")
.withProfile("minimal")
.build();

Channel Resolution​

resolveChannel supports three expressive formats beyond literal channels:

  • stable N (year|month|week|day) ago — compute minor from date arithmetic
  • stable minus N releases — subtract from current stable
  • 1.XX — passed through unchanged; rustup resolves a <major.minor> channel to the newest patch in that series

Cache Key​

generateCacheKey produces a 12-character key from date + commitHash (first 12 chars), matching dtolnay/rust-toolchain's output format for cache compatibility. It is read through RUSTUP_TOOLCHAIN, so the key describes the toolchain that was requested rather than whatever a rust-toolchain.toml would have selected.

A rustc that cannot be run is fatal rather than silently yielding an empty key: every consumer keying a cache on an empty string would share one entry, with nothing in the log to explain it.

generateSpecCacheKey publishes a second output, cachekey-full, appending a SHA-256 digest of the resolved channel, targets, components and profile. The compatible key describes the compiler build alone, so two jobs on the same rustc collide even when one installed wasm32-unknown-unknown and the other did not — and the second restores artifacts produced without its target. Targets and components are sorted before hashing, so the same set written in a different order still hits the same key. See COMPARISON.md.

Cache Layers​

cache: true derives a key and restore-key ladder per cache layer, published through the cache output. Phase A shipped the keys; Phase B (below) restores and saves against them. Three layers exist today, defined in src/cache/layers.ts and keyed in src/cache/keys.ts:

  • registry — the downloaded crate sources under ~/.cargo/registry and ~/.cargo/git. Its key is registry-<os>-<arch>-<suffix>-<lockHash>, and it deliberately omits the resolved toolchain: any rustc can compile a source archive it did not build, so tying the key to the compiler would force a re-download on every toolchain bump for no benefit.

  • build — the compiled artifacts under target/. Its key is build-<os>-<arch>-<suffix>-<specCacheKey>-<envHash>-<lockHash>, carrying the resolved spec and the digest of the build-affecting environment (hashBuildEnv, src/cache/env.ts) because those artifacts are both toolchain- and environment-specific. Its restore ladder stops one rung short of the bare registry-style prefix — the ladder is build-<os>-<arch>-<suffix>-<specCacheKey>-<envHash>- and nothing looser — because an entry built by a different toolchain or environment is not a useful restore: cargo would discard it on sight, and the run pays the download cost only to re-save it under a new key regardless.

  • bin — the cargo-installed tools named by cargo-tools, under $CARGO_HOME/bin. Its key is bin-<os>-<arch>-<toolSetHash>, and what it leaves out is the interesting part. No <lockHash>: a tool is installed from crates.io and has nothing to do with the workspace's dependency set, which is also why a bin-only cache-layers needs no cache-key-hash at all. No <specCacheKey>: the point of the layer is that a compiler bump does not reinstall tools that did not change. And no <suffix>: two jobs resolving the same tool set need byte-identical binaries, so splitting them apart would cost sharing and buy nothing. Unlike build, its ladder does fall back to the bare bin-<os>-<arch>- prefix, because a stale tool binary is still a real binary and ensureTools version-probes it before trusting it.

    A cargo-tools entry's optional :<binary> suffix is left out too, and that omission is load-bearing rather than tidy. The suffix names which executable to version-probe for a crate that does not install one named after itself (ignorefile-cli ships ign and ignorefile); it changes nothing about what is installed, so folding it into <toolSetHash> would make adding :ign to a working workflow miss the entry it already has — paying a full rebuild to stop paying full rebuilds, and splitting the cache between two spellings of one request from then on. The published cargo-tools output excludes it for the parallel reason: consumers hash that output to reproduce this key, so the two have to agree on what a tool set is.

    Dropping the toolchain from the key is only sound because rustup's own shims are excluded from the archive — otherwise the layer would carry rustc and cargo under a key that never mentions which toolchain they came from, and a restore would overwrite the installed toolchain with an older one. binPaths therefore emits a !<bin>/<shim> and !<bin>/<shim>.exe pair for each of the fourteen names in RUSTUP_SHIMS, plus the same directory negations buildPaths needs. See the warning about proving this in CLAUDE.md: a test asserting a shim is merely absent from disk after a restore proves nothing, because rustup puts every shim back itself.

The layers are split by how often each one invalidates, which is the whole point of separating them: a rustc bump invalidates build but neither registry nor bin, so splitting them stops a compiler upgrade from forcing a re-download of every crate it never touched or a recompile of every tool it does not affect.

The dependency-set hash (cache-key-hash) is a required input rather than something the action computes, because hashFiles() — the only thing that can glob a workspace's lockfiles — is a GitHub Actions workflow-expression function, unreachable from a Node action. Taking the workflow's own value also keeps these keys interoperable with a hash the workflow may already use elsewhere.

envHash was added after the key format above already shipped, which means it changed every existing build key the moment it did: a workflow upgrading across that boundary sees exactly one cold build restore, then resumes hitting normally. See the upgrade note in README → Deriving cargo cache keys yourself.

cache: true restores and saves both layers itself — see Cache Lifecycle below. A workflow can still derive the keys alone and wire its own actions/cache steps (see the README's key-only recipe). See docs/design/2026-07-31-layered-cargo-cache.md for the full design rationale, including the bin layer that a later phase adds for cargo-installed tools.

Cache Lifecycle​

resolveCacheLifecycle in src/action.ts turns the derived keys into actual restores and saves, split across the main and post phases:

  • Restore (restoreLayers, src/cache/lifecycle.ts) runs every enabled layer's client.restore concurrently, in the main phase, right after the toolchain is installed — the build key needs specCacheKey, which does not exist until rustc has run. Any failure — a service outage, a reserved-key race — becomes a warning and an ordinary miss; a cache being unavailable must not fail a job that would otherwise succeed.
  • Save (saveLayers/saveLayer, src/cache/lifecycle.ts) runs from the post phase, once the whole job has finished. Three independent reasons skip a layer: it matched its restore key exactly (unchanged, saving it again is pure budget burn); its size could not be measured (measurePaths threw — writing an entry of unknown size into a shared budget is the unsafe direction); or its measured size exceeds cache-budget (an oversized entry does not degrade its own hit rate, it evicts other workflows' caches). Each layer's save is independently caught, so one layer's failure cannot lose the results of the others in the same batch.
  • Exclusions are negation globs, never deletion — and they only work on a files-only manifest. This is the shape a layer archives under cache-prune: off; under the default safe it archives a stage instead, described below. buildPaths (src/cache/paths.ts) emits <target>/**, then !<target>/**/incremental/** and !<target>/**/examples/**, and finally !<target>/ and !<target>/**/. Those last two are not decoration. @actions/cache resolves the patterns through @actions/glob with implicitDescendants: false, writes the matches to a manifest, and runs tar --files-from <manifest> — with no --no-recursion. Any directory left in the manifest is therefore expanded wholesale by tar and re-includes everything the negations removed, so excluding directories is what makes the other exclusions reach the archive. Verified at the tar layer, not only the glob layer: the pre-fix [target, !target/*/incremental, …] form resolved to the single entry target, from which tar archived the whole tree. The cost of a files-only manifest is that empty directories and directory permissions and mtimes are not preserved, which cargo does not depend on — it decides freshness from file mtimes and recreates any directory it needs. Nothing on disk is touched, so a save failure leaves the working tree exactly as it was. registryPaths keeps naming bare directories, and that asymmetry is deliberate: it carries no exclusions, so tar's recursion is exactly what archives it. registry/src is excluded there by never being listed at all, since it is fully regenerable from the .crate files in registry/cache.
  • A cache failure never fails the build. Restore, save, size measurement and the job summary write are each wrapped so their own failure produces a core.warning and lets everything else continue — including runPost's outer try/catch around a malformed state payload, and writeSummarySafely's own inner one around a summary write that throws when GITHUB_STEP_SUMMARY is unset (slim runners, act).
  • The job summary (renderSummary, src/cache/summary.ts) is the only place a per-layer result is visible — cache-hit is a single all-layers boolean, so telling a cold run from a broken key needs the table naming each layer's actual restore result and save outcome.

Pruning Filters the Manifest, and Staging Is What Makes It Possible​

A cache entry's identity is not its key alone. getCacheVersion in @actions/cache hashes paths.join("|") together with the compression method and a salt, and an entry is matched on (key, version) — so changing the paths array changes which entry you are asking for. That is the constraint every pruning design has to answer, and answering it wrong is silent: the save succeeds, writes a real entry, and no later restore can ever find it, because the restoring job computes its version from a paths array it has not yet learned the content of.

So pruning cannot narrow the paths array. Instead:

  1. Attribution. readFingerprints (src/cache/prune.ts) reads the <name>-<hash> directories cargo already writes under target/<profile>/.fingerprint/ and recovers a hash-to-package mapping from them. This is authoritative where Swatinem/rust-cache strips a trailing -$hash off a filename and guesses.
  2. Keep-set. computeKeepSet intersects that mapping with the packages cargo metadata --format-version 1 --locked still resolves to (src/cache/metadata.ts), yielding the files worth archiving.
  3. Staging. buildStageRoots/registryStageRoot name one fixed directory per tree, and stagePaths hands that alone to the client. The array is therefore identical in every job regardless of what the keep-set contains. stageFiles hard-links the keep-set into it before a save; unstageFiles moves it back out after a restore. Hard links rather than copies, because they share an inode and therefore an mtime, and mtime is what cargo's freshness check reads — a copy would look newer than the source it was built from and invalidate everything.

Three properties follow, and each has a guard because losing it is silent:

  • Nothing is ever deleted from the working tree. The keep-set is a save-time filter, so a wrong keep-set costs a wrong-sized archive. A post step that deleted from target/ would run after the job's real work, so the same mistake would surface as a build that succeeded and a checkout now missing artifacts — and on a self-hosted runner the damage outlives the job. Both inputs are outside our control, and cargo concedes the fingerprint format has no stability guarantee.
  • An empty or unusable keep-set falls back to the coarse globs. Every failure mode converges on the same symptom — nothing resolved, therefore nothing attributable, therefore zero files — and saving that is not a small cache but a poisoned one: an entry that exists, hits its key, restores nothing, and leaves every later job rebuilding while believing it was warm. computeKeepSet refuses to mark such a set usable, filesToStage falls back to walking the whole tree when it is not, and stageLayers drops any layer that staged zero files rather than saving an empty archive.
  • Pruning is skipped when it would not pay. PRUNE_WORTH_IT in src/action.ts keeps the unpruned paths when the keep-set would drop under 5% of the bytes. Measured rather than guessed: resolution runs about 1.5 ms per kept entry, so an explicit manifest costs more the less there is to prune — a churned tree dropped 46% of 220 MB in 495 ms, an unchurned one spent 904 ms to drop 0.2%.

The Two Entrypoints And The State Handoff​

action.yml declares both main and post as dist/index.js — the same bundle, invoked twice. src/index.ts is the only place that tells the two invocations apart, by checking process.env.STATE_isPost, which GitHub Actions populates from whatever the main phase's saveState("isPost", ...) wrote.

That call is the first thing run does — unconditionally, before reading any cache input, before installing anything — specifically so a caching-disabled job's post invocation can still tell it is the post phase. Gating it on cache: true was tried and reverted: on the default configuration STATE_isPost would never be set, the post invocation would fall through to run's own branch in src/index.ts, and the whole toolchain install would run a second time — capable of turning an already-succeeded job into a failed one. runPost already no-ops correctly on empty state, which is what makes the unconditional saveState safe for every configuration.

The second piece of state, "cache", crosses the same boundary as a JSON-encoded string: { plans, restored, budget }, written by resolveCacheLifecycle only when caching is enabled, and read back by runPost through getState("cache"). An empty value there — caching was off, or the run never reached the lifecycle — is runPost's own no-op signal, independent of isPost. Because the two phases are separate process invocations, nothing else survives between them: no closures, no module-level state, only what was explicitly written to and read from these two keys.

The @actions/cache Adapter Lives In index.ts​

CacheClient (src/cache/client.ts) is a two-method port — restore/save — with no real implementation anywhere under src/. The only one wraps @actions/cache and is built inline in src/index.ts, which nothing imports and the coverage gate does not measure (see AGENTS.md → Coverage gate gotchas). That placement is deliberate, not an oversight: @actions/cache vendors the Azure Storage SDK — most of the roughly 1.4 MB this feature added to dist/index.js — plus genuinely unmockable network code. A library module importing it directly would pull that weight, and that network code, into every test process, making the 100% coverage gate unreachable for anything downstream of it. Every module that needs to restore or save takes a CacheClient as a dependency instead, so tests inject a fake and the real adapter is exercised only by the actual GitHub Actions runtime — and by CI's E2E and E2E Warm Cache jobs, the only place restore and save meet the real cache service. It takes two jobs rather than one: post: runs after every other step in its own job, so nothing a job saves is visible to that same job, and the warm restore has to happen in a dependent job (see README → Built to be trusted).

The exemption is earned adapter by adapter, not inherited by living in the file. @actions/cache earns it for its SDK and its network code, the cargo metadata reader for shelling out, the crates.io client for its fetch. The node:fs adapters earned none of those and moved to src/cache/fs.ts, where fs.test.ts holds them to a real temp directory — after a hand-written fake that disagreed with readdirSync about a missing directory cost every pruned layer its save, unnoticed by a suite at 100%.

Toolchain Pinning​

rustup resolves the active toolchain through an override chain — highest first: +toolchain shorthand, RUSTUP_TOOLCHAIN, directory override, rust-toolchain.toml, default. Three consequences shape this codebase:

  • src/action.ts exports RUSTUP_TOOLCHAIN after installing. Setting rustup default alone is not enough: a workspace rust-toolchain.toml outranks the default, so later steps would run a different toolchain than the one installed.
  • src/builder.ts pins --toolchain on every target add / component add. Without it those commands resolve through the same chain and attach targets or components to the toml's toolchain.
  • A path toolchain is rejected. path selects a local directory and is mutually exclusive with channel, so there is nothing to install; mergeConfig throws rather than silently falling back to stable.

Profiles Are Always Explicit​

Omitting --profile makes rustup fall back to the globally configured profile (rustup set profile), not to default. The rustup book says so directly about the toolchain file's profile key:

Note that if not specified, the default profile is not necessarily used, as a different default profile might have been set with rustup set profile.

Since mergeConfig resolves a profile for every run, ToolchainSpec always passes it explicitly so a runner-wide setting cannot change the result.

mergeConfig accepts only the three profiles rustup defines — minimal, default, complete — narrowing the value to a RustupProfile union rather than passing an arbitrary string through. A typo is reported with the valid options listed instead of reaching rustup.

When neither the toml nor an input names one, the resolved value is DEFAULT_PROFILE, which is default — the same profile rustup itself defaults to (minimal plus rust-docs, rustfmt and clippy).

The Profile Only Applies to a Fresh Toolchain​

rustup silently ignores --profile when the toolchain is already installed. Verified on a clean rust:trixie container:

fresh install --profile minimal → installed cargo, rust-std, rustc
re-install --profile default → unchanged cargo, rust-std, rustc
re-install --profile complete → unchanged cargo, rust-std, rustc
re-install --profile default --force
→ unchanged cargo, rust-std, rustc
remove, then fresh --profile default
→ installed cargo, clippy, rust-docs,
rust-std, rustc, rustfmt

There is no rustup flag that applies a profile to an existing toolchain — --force does not do it. Explicitly named components do still install, which is why the action adds components through separate rustup component add calls rather than relying on the install flags.

complete Is Not Installable on Release Channels​

The complete profile pulls in miri and rustc-codegen-cranelift, which rustup publishes only for nightly. On a fresh install against any release channel it fails outright — verified for both a pinned version and stable:

rustup toolchain install --profile complete 1.95
error: some components are unavailable for download for channel '1.95':
'miri' for target 'x86_64-unknown-linux-gnu',
'rustc-codegen-cranelift' for target 'x86_64-unknown-linux-gnu'

rustup component list --toolchain 1.95 # what release channels actually offer
llvm-tools, rust-analyzer, rust-src # no miri, no cranelift

The failure is deterministic, so retrying cannot help. assertProfileAvailable therefore rejects complete up front for any channel that is not nightly, before a single rustup command runs — turning a slow, opaque network failure into an immediate message naming the cause and the two ways out. The check runs on the resolved channel, so stable 2 releases ago is judged as the release it becomes.

beta is rejected along with the release channels: a fresh container lists neither component for it.

On an already-installed toolchain complete appears to succeed purely because the profile is ignored (see above) — nothing is resolved, so nothing can be missing. That is why the check is on the channel rather than on the outcome.

Because complete requests the widest set, --allow-downgrade is added for it on nightly — the same latitude explicitly named components get, letting rustup step back to the newest nightly that carries everything.

Profiles Are Expanded Into Components​

Because rustup will not apply a profile to an existing toolchain, the action adds the profile's components by name after installing. PROFILE_COMPONENTS in src/config.ts holds the mapping:

ProfileAdded explicitly
minimalnothing — rustc, cargo and rust-std are inherent to any toolchain
defaultrust-docs, rustfmt, clippy
completethe above plus rust-src, rust-analyzer, llvm-tools

complete deliberately omits miri and rustc-codegen-cranelift. rustup publishes them for nightly only, so naming them would fail the add on every release channel; they still arrive through --profile complete on a fresh nightly install.

The two component invocations carry different weight:

  • Requested components (components: input or toml) are a hard requirement. A failure fails the step.
  • Profile components are best-effort. They were implied rather than asked for, so a channel that does not publish one is logged and the run continues.

Components the caller already listed are filtered out, so nothing is requested twice.

Together with default as the default profile, this means a job on a runner with Rust pre-installed still ends up with rustfmt and clippy — which is what the profile promised and what rustup alone would not have delivered.

Bootstrapping rustup​

Self-hosted runners and slim container images frequently ship without rustup. If rustup --version does not answer, bootstrapRustup downloads rustup-init (sh.rustup.rs, or win.rustup.rs/<arch> on Windows) to $RUNNER_TEMP, runs it with --default-toolchain none, and puts $CARGO_HOME/bin on PATH. The installer is written to a file and executed directly rather than piped into a shell.

Cargo Environment Defaults​

After the toolchain is installed, applyCargoDefaults sets what a Rust CI job almost always wants, and never overwrites a value the workflow set itself:

VariableValueWhy
CARGO_INCREMENTAL0Incremental artifacts never survive to the next run; producing them only costs time and cache space
CARGO_TERM_COLORalwaysColour in the job log
CARGO_REGISTRIES_CRATES_IO_PROTOCOLsparse on 1.68–1.69, git on 1.66–1.67The sparse registry was implemented in 1.66, stabilised in 1.68 and made default in 1.70, so only the versions in between need steering
CARGO_HTTP_MULTIPLEXINGfalse on 1.70–1.71Those toolchains bundle curl 8.0, which produced spurious network errors with multiplexing on

Anchoring the Release Cycle​

stable N ago and stable minus N releases count six-week cycles from 2015-05-14 — the same day dtolnay/rust-toolchain uses. The anchor is load-bearing in both directions: a week late names a release that has been superseded, and a week early names one that has not shipped, so rustup toolchain install fails outright. stableMinorAtDate works purely in absolute epoch milliseconds and setUTC* accessors, so the result never depends on the runner's timezone.

A bare 1.N is scaled by scaleBareMinor while the scaled value names a release that already exists: 1.9 reads as 1.90, 1.62 is left alone. Without it, writing 1.9 silently pins the 2015 release.

Argv, Never a Shell​

Channel, targets, components and profile can all originate in a rust-toolchain.toml belonging to the checked-out workspace, which on pull_request_target or any untrusted checkout is attacker-controlled. Every command is therefore built as an argv array by ToolchainSpec and executed without a shell, so a value like stable; curl … | sh reaches rustup as one (invalid) toolchain name instead of a second command.

Two validation layers back this up: resolveChannel rejects anything that cannot name a toolchain, and mergeConfig rejects targets, components and profiles that are not plain rustup identifiers. Neither is load-bearing on its own — they turn a confusing rustup error into a clear one.

Timeouts and Retries​

Every rustup verb used here downloads from static.rust-lang.org. Each call is bounded by a timeout (10 minutes for rustup, 30 seconds for rustc --version) so a stalled connection cannot hold the job until the workflow's own limit, and network-bound commands are retried up to three times with 1s/2s backoff so a single dropped connection does not fail the run.

Relocatable RUSTUP_HOME​

resolveRustupEnv honours a caller-supplied RUSTUP_HOME/CARGO_HOME and only falls back to $HOME/…. This matters on overlayfs-backed container runtimes (Docker, act, container jobs): rustup renames a component's directory into $RUSTUP_HOME/tmp before replacing it, and overlayfs rejects renaming a directory that still lives in a lower image layer with EXDEV. Pointing RUSTUP_HOME at a directory created at run time keeps every rename inside one layer.

Tooling Stack​

Runtime Dependencies​

PackagePurpose
@actions/coreInputs, outputs, exportVariable, saveState/getState, failures
@actions/cacherestoreCache/saveCache behind the CacheClient port
smol-tomlrust-toolchain.toml parsing
@actions/githubDeclared for workflow context, but no module imports it today

@actions/cache is reached only through CacheClient (src/cache/client.ts), a type-only interface wired to the real SDK in src/index.ts. That indirection is why it costs nothing at test time and why it appears in exactly one import site. It is also the single largest contributor to the bundle: adding it took dist/index.js from roughly 789 KB to 2,209,190 bytes, a cost accepted deliberately in the Phase B design rather than reimplementing the cache protocol.

@actions/github is declared in package.json but imported nowhere, so the bundler drops it — it contributes zero bytes to dist/index.js. It is kept because AGENTS.md directs contributors to it rather than to raw process.env/GITHUB_* access when workflow context is eventually needed.