From 59ed15d52726b2947d0e638485c60b9ff4a80441 Mon Sep 17 00:00:00 2001 From: Sami Dalouche Date: Tue, 24 Nov 2026 12:20:12 -0500 Subject: [PATCH] feat(build-dependency-cache): share the S3 cache actions for sbt, mise and uv (SC-88184) narrative-marketplace-backend, narrative-connectors and narrative-snowflake-data-plane each carry an identical copy of the action that keeps sbt's dependency caches in S3 instead of GitHub's cache, which the runners reach through a NAT gateway that bills every byte (SC-87124). narrative-marketplace-backend#3556 replaces it with .github/actions/build-dependency-cache: an engine and one action per tool, adding mise's tools, the bulk of the NAT traffic left, and uv's packages, which nothing cached in narrative-marketplace-backend and GitHub's cache held in narrative-snowflake-data-plane. This puts that folder here, file for file, for the three repositories to pin; only the path its pyproject.toml extends ruff's rules from differs. - build-dependency-cache/s3_cache.py: the archive logic, with kinds sbt, mise and uv: folders, key files, S3 layout, latest, runner markers, saving only on a push to main, and stats in the log. - build-dependency-cache/cache-sbt and cache-uv: JavaScript actions only to get a post step, which saves when the job ends with every step passed, in the job that passes save: true. Their scripts start s3_cache.py through build-dependency-cache/s3-cache.js. - build-dependency-cache/setup-mise: a composite action around jdx/mise-action, with its cache off, that restores before it and prunes and saves right after it. It runs s3_cache.py itself: an action here can only reach a sibling with `uses: narrative-io/common-github/@`, and a commit can't name itself. - All three require url, the base S3 URL, which callers pass from the organization variable COMMON_GITHUB_BUILD_DEPENDENCY_CACHE, so the bucket stays out of this public repository. An empty url fails the step, so a repository can't run without its cache unnoticed; trouble reaching S3 still only warns. Callers keep their kill switches. - build-dependency-cache is a uv project with tests: pytest checks s3_cache.py's decisions with plain values, and its restores and saves against an S3 kept in memory; node's test runner checks s3-cache.js. The build-dependency-cache workflow runs them, with ruff and ty, on pull requests that change the folder. ruff.toml copies narrative-marketplace-backend's rules, and mise.toml pins the uv and node the tests run with. - build-dependency-cache/README.md explains the archives, how to use the actions, and what's trusted. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build-dependency-cache.yml | 55 ++ .gitignore | 6 + README.md | 8 +- build-dependency-cache/.vscode/settings.json | 20 + build-dependency-cache/README.md | 124 ++++ build-dependency-cache/cache-sbt/action.yml | 40 ++ build-dependency-cache/cache-sbt/restore.js | 5 + build-dependency-cache/cache-sbt/save.js | 5 + build-dependency-cache/cache-uv/action.yml | 36 ++ build-dependency-cache/cache-uv/restore.js | 5 + build-dependency-cache/cache-uv/save.js | 5 + build-dependency-cache/mise.lock | 43 ++ build-dependency-cache/mise.toml | 22 + build-dependency-cache/pyproject.toml | 24 + build-dependency-cache/s3-cache.js | 55 ++ build-dependency-cache/s3_cache.py | 582 ++++++++++++++++++ build-dependency-cache/setup-mise/action.yml | 83 +++ build-dependency-cache/tests/s3-cache.test.js | 74 +++ build-dependency-cache/tests/test_s3_cache.py | 461 ++++++++++++++ build-dependency-cache/uv.lock | 149 +++++ mise.lock | 83 +++ mise.toml | 8 + ruff.toml | 27 + 23 files changed, 1919 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/build-dependency-cache.yml create mode 100644 .gitignore create mode 100644 build-dependency-cache/.vscode/settings.json create mode 100644 build-dependency-cache/README.md create mode 100644 build-dependency-cache/cache-sbt/action.yml create mode 100644 build-dependency-cache/cache-sbt/restore.js create mode 100644 build-dependency-cache/cache-sbt/save.js create mode 100644 build-dependency-cache/cache-uv/action.yml create mode 100644 build-dependency-cache/cache-uv/restore.js create mode 100644 build-dependency-cache/cache-uv/save.js create mode 100644 build-dependency-cache/mise.lock create mode 100644 build-dependency-cache/mise.toml create mode 100644 build-dependency-cache/pyproject.toml create mode 100644 build-dependency-cache/s3-cache.js create mode 100644 build-dependency-cache/s3_cache.py create mode 100644 build-dependency-cache/setup-mise/action.yml create mode 100644 build-dependency-cache/tests/s3-cache.test.js create mode 100644 build-dependency-cache/tests/test_s3_cache.py create mode 100644 build-dependency-cache/uv.lock create mode 100644 mise.lock create mode 100644 mise.toml create mode 100644 ruff.toml diff --git a/.github/workflows/build-dependency-cache.yml b/.github/workflows/build-dependency-cache.yml new file mode 100644 index 0000000..a86a016 --- /dev/null +++ b/.github/workflows/build-dependency-cache.yml @@ -0,0 +1,55 @@ +name: build-dependency-cache + +# Tests build-dependency-cache, so a change can be tested before consumers pin it: s3_cache.py with pytest, ruff and +# ty, and s3-cache.js, which its JavaScript actions run, with node's test runner. ubuntu-latest has GNU tar and zstd, +# as the self-hosted runners do, so the one test a laptop skips runs here. +on: + pull_request: + paths: + - build-dependency-cache/** + - ruff.toml + - mise.toml + - .github/workflows/build-dependency-cache.yml + push: + branches: [main] + paths: + - build-dependency-cache/** + - ruff.toml + - mise.toml + - .github/workflows/build-dependency-cache.yml + +permissions: {} + +defaults: + run: + working-directory: build-dependency-cache + +jobs: + test: + name: Test build-dependency-cache + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # python from the folder's mise.toml, uv and node from the root's. Not setup-mise, which needs the S3 bucket + # that only the self-hosted runners reach. + - uses: jdx/mise-action@8418fedb1110381a0d3ba51a7a415d7c1b884550 # v5.2.2 + with: + version: 2026.11.10 + working_directory: build-dependency-cache + - name: Install dependencies + run: uv sync --locked + - name: Run the Python tests + run: uv run --frozen pytest -rs + - name: Run the JavaScript tests + run: node --test tests/s3-cache.test.js + - name: Lint + run: uv run --frozen ruff check . + - name: Check formatting + run: uv run --frozen ruff format --check . + - name: Type-check + run: uv run --frozen ty check diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3520821 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.venv/ +__pycache__/ +.pytest_cache/ +.ruff_cache/ +# Where the VS Code mise extension links the tools a folder's mise.toml pins. +.vscode/mise-tools/ diff --git a/README.md b/README.md index 773c482..ce11ed9 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,17 @@ Every repository is now backed up centrally by [`narrative-security`'s `github-backup.yml`](https://github.com/narrative-io/narrative-security/blob/main/.github/workflows/github-backup.yml) (sc-73208), so repositories no longer need a backup workflow of their own. +## Contents + +- [`build-dependency-cache/`](build-dependency-cache/README.md): actions that keep CI's sbt dependencies, mise tools + and uv packages in S3 instead of GitHub's cache: `cache-sbt`, `setup-mise` and `cache-uv`. + ## Releases -Consumers pin the reusable workflows here to a full commit SHA with the version in a trailing comment: +Consumers pin the actions and reusable workflows here to a full commit SHA with the version in a trailing comment: ```yaml +uses: narrative-io/common-github/build-dependency-cache/cache-sbt@ # v1.2.0 uses: narrative-io/common-github/.github/workflows/.yml@ # v1.0.0 ``` diff --git a/build-dependency-cache/.vscode/settings.json b/build-dependency-cache/.vscode/settings.json new file mode 100644 index 0000000..3357dd1 --- /dev/null +++ b/build-dependency-cache/.vscode/settings.json @@ -0,0 +1,20 @@ +{ + // The mise extension links the tools this folder's mise.toml (and the repository root's) pins into + // .vscode/mise-tools/: ty and ruff at the versions CI runs. [deps.uv] in mise.toml keeps .venv in sync, and ty + // finds it there, so imports resolve when this folder is opened on its own or through python.code-workspace. + "mise.configureExtensionsAutomatically": true, + "mise.configureExtensionsUseSymLinks": true, + "mise.configureExtensionsIncludeGlobalTools": false, + "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python", + // ty is the language server: Pylance would report the same code again, by other rules. + "python.languageServer": "None", + "ty.path": [ + "${workspaceFolder}/.vscode/mise-tools/ty" + ], + "ruff.path": [ + "${workspaceFolder}/.vscode/mise-tools/ruff" + ], + "[python]": { + "editor.defaultFormatter": "charliermarsh.ruff" + } +} diff --git a/build-dependency-cache/README.md b/build-dependency-cache/README.md new file mode 100644 index 0000000..1b5dd5f --- /dev/null +++ b/build-dependency-cache/README.md @@ -0,0 +1,124 @@ +# build-dependency-cache + +Actions that keep CI's dependency and tool caches in S3 instead of GitHub's cache. Our self-hosted runners sit in a +private subnet: they reach GitHub's cache, which is Azure storage, and package registries through a NAT gateway that +bills every byte, and S3 in their own region through a gateway endpoint that's free. Moving sbt's caches to S3 removed +most of the NAT's traffic (SC-87124); mise's tools were most of what was left (SC-88184). + +- [`cache-sbt`](cache-sbt/action.yml): sbt's dependency caches (coursier, ivy, the sbt launcher). +- [`setup-mise`](setup-mise/action.yml): `jdx/mise-action`, with mise and the tools it installs kept in S3. +- [`cache-uv`](cache-uv/action.yml): uv's cache, the packages a project's `uv sync` downloads. +- [`s3_cache.py`](s3_cache.py): the archive logic all three share, and [`s3-cache.js`](s3-cache.js), which the + JavaScript actions start it with. Callers never run either directly. + +## Configure + +The actions need the base S3 URL of the cache, `s3:///`, as their `url` input. It's kept out of this +public repository, in an organization variable: + +1. In the organization's settings, under **Secrets and variables → Actions → Variables**, create the variable + `COMMON_GITHUB_BUILD_DEPENDENCY_CACHE` with that URL. +2. Under **Repository access**, give it to every repository that uses these actions. A repository the variable isn't + shared with gets an empty `url`, and each cache step fails, so no job runs without its cache unnoticed. Make sure + it's a variable, not a secret: the steps read `vars`, and a secret of the same name leaves `url` empty. +3. Give the runners read and write on that prefix, and an expiry rule for it. + +An action can't read the variable itself (its `action.yml` can't refer to `vars`), so every step passes it, as below. +The bucket, its expiry rule and the runners' access to it are in narrative-devtools (`var/shared/` and +`github-runner/terraform/iam.tf`). + +## Use + +Pin a released version by its full commit SHA, as for everything in this repository: + +```yaml +- name: Restore the sbt dependency cache + # Repository variable: "off" turns the cache off. + if: vars.SBT_DEPENDENCY_CACHE != 'off' + uses: narrative-io/common-github/build-dependency-cache/cache-sbt@ # vX.Y.Z + with: + url: ${{ vars.COMMON_GITHUB_BUILD_DEPENDENCY_CACHE }} + save: true # only in the job whose dependencies the archive should hold, such as sbt test + +- name: Set up mise + uses: narrative-io/common-github/build-dependency-cache/setup-mise@ # vX.Y.Z + with: + url: ${{ vars.COMMON_GITHUB_BUILD_DEPENDENCY_CACHE }} + version: 2026.11.10 + install_args: java asdf:mise-plugins/mise-sbt + s3_cache: ${{ vars.MISE_TOOLS_CACHE != 'off' }} + +- name: Restore the uv cache + if: vars.UV_CACHE != 'off' + uses: narrative-io/common-github/build-dependency-cache/cache-uv@ # vX.Y.Z + with: + url: ${{ vars.COMMON_GITHUB_BUILD_DEPENDENCY_CACHE }} + working_directory: my-project # the folder holding its uv.lock + save: true # only in the job that syncs everything the project locks, such as its tests +``` + +## How an archive works + +Each call archives one kind of cache, as `zstd`-compressed tar, at `///.tar.zst`, with a +`latest` file beside it naming the key `main` saved last. + +| | sbt (`cache-sbt`) | mise (`setup-mise`) | uv (`cache-uv`) | +| ---------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------- | +| Folders, under `HOME` | `.cache/coursier`, `.ivy2/cache`, `.sbt/boot`, `.sbt/1.0/zinc` | `.local/share/mise`, without `downloads/` | `.cache/uv` (or `UV_CACHE_DIR`), without `builds-v0/` | +| Prefix | the optional `scope` input | `mise-tools/` | `uv/` | +| Key: a hash of these tracked files | every `*.sbt`; `*.scala` and `build.properties` under `project/`; `mise.toml` | every `mise.toml`, `.mise.toml`, `mise.lock` and `.tool-versions` | the project's `uv.lock` | +| Saves | from its post step, when the job ends with every step passed, if `save: true` | right after `mise-action` installs, after `mise prune --yes --tools` | from its post step, as `cache-sbt`, if `save: true` | + +- **The key** hashes each key file's object ID in git's index, not the file on disk, so a job that edits build files + between restore and save, as `sbt-dependency-submission` does in `project/`, still saves under the key it restored. +- **Restore** takes the archive for the exact key, else the one `latest` names, and the tool fetches whatever changed + since. A runner that already restored or saved the key skips the download: runners take several jobs before they're + replaced. A half-extracted archive is deleted, folders and all, rather than left looking complete. +- **Save** only acts on a push to `main`, and only for a key that has no archive yet; `latest` moves only after the + upload. Archives expire with the bucket's lifecycle rule, and the next push to `main` saves the key again. +- **Failures only warn, except a missing URL.** A restore or save that fails, because S3 can't be reached or an archive + is broken, logs a warning and the job carries on; the tool then downloads what it needs. An empty `url`, or a + JavaScript action that can't start Python, fails the step instead, since every job would otherwise quietly run + without its cache. +- **Each restore and save reports** a notice with the archive's compressed size and how long the transfer and the tar + took, then what the folders hold on disk. The step's log breaks it down per folder in a collapsed group and, for + mise, lists the installed versions. Compare `main`'s saves over time to see whether an archive grows. + +### Why `cache-sbt` and `cache-uv` are JavaScript and `setup-mise` is composite + +`cache-sbt` and `cache-uv` are JavaScript actions only to get a post step, which saves when the job ends, after the +build or `uv sync` has fetched everything, as `actions/cache` does. Composite actions can't have one, and without it +every workflow would need a second step, placed last, to save. Their scripts only start `s3_cache.py`, through +`s3-cache.js`. + +`setup-mise` has to be composite to call `jdx/mise-action`, and saves right after the install instead: mise's folder is +complete then, a job that fails later still saves it, and later steps can't add to it. Saving at the end would let the +job's real work start a few seconds sooner on the pushes that save; its save step's comment explains the trade-off. + +None calls a sibling action: an action here can only reach another one with +`uses: narrative-io/common-github/@`, and a commit can't name itself. They run `s3_cache.py` from the +checkout of this repository the runner made for the action. + +### What's trusted + +`mise-action` checks the restored mise binary against mise's signed checksums before running it. Nothing checks the +tools, the jars or the packages. Only a push to `main` saves, but that's the actions' own check, not a permission: +every job on the runner fleet can write the prefix, so an archive is only as trusted as everything that runs on the +runners, pull requests included. GitHub's cache, by contrast, is scoped by branch. + +## Test + +The folder is a uv project, set up with mise: its `mise.toml` pins Python 3.11, the oldest a runner has, and the +repository's pins uv and node. From the folder: + +```sh +uv run pytest # s3_cache.py +node --test tests/s3-cache.test.js # s3-cache.js, which cache-sbt and cache-uv run +uv run ruff check . && uv run ruff format --check . && uv run ty check +``` + +`s3_cache.py` keeps what it decides in pure functions, which the tests check with plain values, and takes S3, tar, git +and the clock as parameters, so its restores and saves are tested against an S3 kept in memory and a throwaway `HOME`. +The actions still run it with the runner's own `python3`: it needs nothing beyond the standard library. One test packs +and unpacks with the real tar and zstd, and skips where tar isn't GNU tar, as on macOS. The `build-dependency-cache` +workflow runs all of it on every pull request that changes this folder. diff --git a/build-dependency-cache/cache-sbt/action.yml b/build-dependency-cache/cache-sbt/action.yml new file mode 100644 index 0000000..503b15f --- /dev/null +++ b/build-dependency-cache/cache-sbt/action.yml @@ -0,0 +1,40 @@ +name: Cache sbt's dependencies +description: > + Restore the coursier, ivy and sbt launcher caches from S3 when the step runs, and save them when the job + ends, through ../s3_cache.py. + + Put the step before anything that runs sbt, or writes into sbt's global directory. It saves from its post + step, after every other step of the job has passed, only in a job that passes save as true, and only on a + push to main. + + If a restore or save fails, the step logs a warning and the job carries on; sbt then downloads what it + needs. Callers keep a kill switch of their own, as a repository variable checked in the step's if; a + skipped step skips the save too, since a post step only runs when its main step ran. + +inputs: + scope: + description: > + Optional path under the repository, for jobs that resolve different dependencies (an aggregate, a + separate build) and should keep separate archives. Jobs with the same scope share one. + default: "" + save: + description: > + "true" in the job whose dependencies the archive should hold, such as `sbt test`, which resolves + everything a build needs. Other jobs only restore: one that resolves less, such as scalafmt, could + otherwise finish first and save a thin archive under the key every job shares. + default: "false" + url: + description: > + Base S3 URL, s3:///; callers pass the organization variable + COMMON_GITHUB_BUILD_DEPENDENCY_CACHE. The repository name, scope and key go under it. The runners need + read and write there. Empty fails the step. + required: true + +# A JavaScript action rather than a composite one: only JavaScript and Docker actions get a post step, which +# saves when the job ends, as actions/cache does, so a workflow needs one step instead of a restore and a save. +# Both scripts start ../s3_cache.py through ../s3-cache.js, so the archive logic stays in one place. +runs: + using: node24 + main: restore.js + post: save.js + post-if: success() diff --git a/build-dependency-cache/cache-sbt/restore.js b/build-dependency-cache/cache-sbt/restore.js new file mode 100644 index 0000000..f4e313c --- /dev/null +++ b/build-dependency-cache/cache-sbt/restore.js @@ -0,0 +1,5 @@ +// cache-sbt's step: restores the archive. The action is JavaScript only so that save.js can run as its post step; +// ../s3-cache.js explains. +const { input, run } = require("../s3-cache.js"); + +process.exitCode = run("sbt", "restore", input("scope")); diff --git a/build-dependency-cache/cache-sbt/save.js b/build-dependency-cache/cache-sbt/save.js new file mode 100644 index 0000000..45cee52 --- /dev/null +++ b/build-dependency-cache/cache-sbt/save.js @@ -0,0 +1,5 @@ +// cache-sbt's post step, the reason the action is JavaScript (../s3-cache.js explains): it runs when the job ends, +// and only if every step passed (post-if: success() in action.yml). +const { input, saveIfAsked } = require("../s3-cache.js"); + +process.exitCode = saveIfAsked("sbt", input("scope")); diff --git a/build-dependency-cache/cache-uv/action.yml b/build-dependency-cache/cache-uv/action.yml new file mode 100644 index 0000000..1ef5ec3 --- /dev/null +++ b/build-dependency-cache/cache-uv/action.yml @@ -0,0 +1,36 @@ +name: Cache uv's packages +description: > + Restore uv's cache, the packages a project's `uv sync` downloads, from S3 when the step runs, and save it + when the job ends, through ../s3_cache.py. Each project keeps its own archive, keyed on its uv.lock. + + Put the step before the project's first `uv sync`. It saves from its post step, after every other step of + the job has passed, only in a job that passes save as true, and only on a push to main. + + If a restore or save fails, the step logs a warning and the job carries on; uv then downloads what it + needs. Callers keep a kill switch of their own, as a repository variable checked in the step's if; a + skipped step skips the save too, since a post step only runs when its main step ran. + +inputs: + working_directory: + description: > + The project's folder, the one holding its uv.lock, relative to the repository root. Empty for a project + at the root. + default: "" + save: + description: > + "true" in the job that syncs everything the project locks, such as its tests. A job that syncs less, + with --no-dev say, could otherwise finish first and save a thin archive under the project's key. + default: "false" + url: + description: > + Base S3 URL, s3:///; callers pass the organization variable + COMMON_GITHUB_BUILD_DEPENDENCY_CACHE. The repository name, project and key go under it. The runners need + read and write there. Empty fails the step. + required: true + +# A JavaScript action rather than a composite one, for the post step, as cache-sbt; ../s3-cache.js explains. +runs: + using: node24 + main: restore.js + post: save.js + post-if: success() diff --git a/build-dependency-cache/cache-uv/restore.js b/build-dependency-cache/cache-uv/restore.js new file mode 100644 index 0000000..125fa66 --- /dev/null +++ b/build-dependency-cache/cache-uv/restore.js @@ -0,0 +1,5 @@ +// cache-uv's step: restores the project's archive. The action is JavaScript only so that save.js can run as its +// post step; ../s3-cache.js explains. +const { input, run } = require("../s3-cache.js"); + +process.exitCode = run("uv", "restore", input("working_directory")); diff --git a/build-dependency-cache/cache-uv/save.js b/build-dependency-cache/cache-uv/save.js new file mode 100644 index 0000000..1a4cc95 --- /dev/null +++ b/build-dependency-cache/cache-uv/save.js @@ -0,0 +1,5 @@ +// cache-uv's post step, the reason the action is JavaScript (../s3-cache.js explains): it runs when the job ends, +// after uv has synced the project, and only if every step passed (post-if: success() in action.yml). +const { input, saveIfAsked } = require("../s3-cache.js"); + +process.exitCode = saveIfAsked("uv", input("working_directory")); diff --git a/build-dependency-cache/mise.lock b/build-dependency-cache/mise.lock new file mode 100644 index 0000000..41a4f51 --- /dev/null +++ b/build-dependency-cache/mise.lock @@ -0,0 +1,43 @@ +# @generated - this file is auto-generated by `mise lock` https://mise.jdx.dev/dev-tools/mise-lock.html + +lockfile_version = 4 + +[[tools.python]] +version = "3.11.18" +backend = "core:python" +specifiers = ["3.11.18"] + +[tools.python."platforms.linux-arm64"] +checksum = "sha256:cc55f9298334bfd87f932368368dc33f88d608dacc01bd6602a05e01dc9e376f" +url = "https://github.com/astral-sh/python-build-standalone/releases/download/20261123/cpython-3.11.18+20261123-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz" +provenance = "github-attestations" + +[tools.python."platforms.linux-arm64-musl"] +checksum = "sha256:355814710f71623e96556e1daf0012d6729b9db56cba87497468c355c198d268" +url = "https://github.com/astral-sh/python-build-standalone/releases/download/20261123/cpython-3.11.18+20261123-aarch64-unknown-linux-musl-install_only_stripped.tar.gz" +provenance = "github-attestations" + +[tools.python."platforms.linux-x64"] +checksum = "sha256:75b92c55bc6a5f58fe4d08fc5261c983b2b17930192d62946fe7c9cf6fd66316" +url = "https://github.com/astral-sh/python-build-standalone/releases/download/20261123/cpython-3.11.18+20261123-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz" +provenance = "github-attestations" + +[tools.python."platforms.linux-x64-musl"] +checksum = "sha256:be20e02684eb5556e334af1e85b07222229c448eceb3ba96b762ef810f961e91" +url = "https://github.com/astral-sh/python-build-standalone/releases/download/20261123/cpython-3.11.18+20261123-x86_64-unknown-linux-musl-install_only_stripped.tar.gz" +provenance = "github-attestations" + +[tools.python."platforms.macos-arm64"] +checksum = "sha256:2192f4345a5175d8c82f8580122e8ab2a6378437718fa013c243475d95894884" +url = "https://github.com/astral-sh/python-build-standalone/releases/download/20261123/cpython-3.11.18+20261123-aarch64-apple-darwin-install_only_stripped.tar.gz" +provenance = "github-attestations" + +[tools.python."platforms.macos-x64"] +checksum = "sha256:98ed21b0fcf29b10103a77d32b2864a7fa162c1ea8f32cd411f227426814c738" +url = "https://github.com/astral-sh/python-build-standalone/releases/download/20261123/cpython-3.11.18+20261123-x86_64-apple-darwin-install_only_stripped.tar.gz" +provenance = "github-attestations" + +[tools.python."platforms.windows-x64"] +checksum = "sha256:b7822833fc5f6f317b79f189c15f923c4321773c087b50e535b39ee2472832b4" +url = "https://github.com/astral-sh/python-build-standalone/releases/download/20261123/cpython-3.11.18+20261123-x86_64-pc-windows-msvc-install_only_stripped.tar.gz" +provenance = "github-attestations" diff --git a/build-dependency-cache/mise.toml b/build-dependency-cache/mise.toml new file mode 100644 index 0000000..de0e5ab --- /dev/null +++ b/build-dependency-cache/mise.toml @@ -0,0 +1,22 @@ +[tools] +# The actions start s3_cache.py with the runner's own python3: 3.11 or newer, by runner. This pins the oldest, so ty +# and the tests check the script against what every runner has. Keep equal to `requires-python` in pyproject.toml; uv +# resolves against that, mise installs this, and nothing checks that the two agree. +python = "3.11.18" + +[env] +# Same uv integration as narrative-marketplace-backend's marketplace-api; its mise.toml explains each setting. +UV_PYTHON = { value = "{{ tools.python.path }}", tools = true } +UV_PYTHON_DOWNLOADS = "never" +UV_PYTHON_PREFERENCE = "only-system" + +[deps.uv] +# Runs `uv sync` before `mise run` and `mise x` whenever pyproject.toml or uv.lock has moved. +auto = true + +[settings] +# Required by [deps.uv] above. +experimental = true +lockfile = true +# [deps.uv] creates .venv; mise only activates it. +python.uv_venv_auto = "source" diff --git a/build-dependency-cache/pyproject.toml b/build-dependency-cache/pyproject.toml new file mode 100644 index 0000000..8f959a4 --- /dev/null +++ b/build-dependency-cache/pyproject.toml @@ -0,0 +1,24 @@ +[project] +name = "build-dependency-cache" +version = "0.1.0" +description = "s3_cache.py, the engine of the cache-sbt, setup-mise and cache-uv actions, and its tests." +# The actions start s3_cache.py with the runner's own python3, so it uses only the standard library of the oldest +# Python a runner has. Keep equal to the python mise.toml pins. +requires-python = ">=3.11" +dependencies = [] + +[dependency-groups] +dev = [ + "pytest>=9.1.1,<10.0.0", + "pytest-randomly>=4.1.0,<5.0.0", + "ruff==0.17.4", + "ty==0.0.107", +] + +[tool.pytest.ini_options] +pythonpath = ["."] +testpaths = ["tests"] + +[tool.ruff] +extend = "../ruff.toml" +line-length = 120 diff --git a/build-dependency-cache/s3-cache.js b/build-dependency-cache/s3-cache.js new file mode 100644 index 0000000..d1dd0d5 --- /dev/null +++ b/build-dependency-cache/s3-cache.js @@ -0,0 +1,55 @@ +// What the JavaScript actions in this folder run. They're JavaScript actions for one reason: to get a post step +// (their save.js), which saves when the job ends, as actions/cache does. Composite actions can't have one, and +// without it every workflow would need a second step, placed last, to save. So the JavaScript only starts +// s3_cache.py, beside this file, where the archive logic lives. The script logs its own notices and warnings, and +// only fails when it has no URL; the step fails with it, or when Python can't start, so a job can't run without +// its cache unnoticed. +// +// The process's environment, spawnSync and console.log are parameters, so tests/s3-cache.test.js can pass fakes. +const { spawnSync } = require("node:child_process"); +const path = require("node:path"); + +const SCRIPT = path.join(__dirname, "s3_cache.py"); + +// The runner passes each input as INPUT_ to both the main and the post step, defaults included. +function input(name, env = process.env) { + return (env[`INPUT_${name.toUpperCase()}`] || "").trim(); +} + +// Saves only in a job that passes save as true, and only on a push to main. It's this check that keeps pull +// requests from saving, not IAM, since every job on the runner fleet can write the prefix. +function shouldSave(env = process.env) { + return ( + input("save", env) === "true" && + env.GITHUB_EVENT_NAME === "push" && + env.GITHUB_REF === "refs/heads/main" + ); +} + +// Runs s3_cache.py and returns the step's exit status. scope is the folder that keeps the job's archives apart: an +// aggregate for sbt, the project for uv. +function run( + kind, + mode, + scope, + { env = process.env, spawn = spawnSync, log = console.log } = {}, +) { + const result = spawn("python3", [SCRIPT, mode, "--kind", kind], { + stdio: "inherit", + env: { ...env, S3_CACHE_URL: input("url", env), S3_CACHE_SCOPE: scope }, + }); + const failed = Boolean(result.error) || result.status !== 0; + if (failed) { + const why = result.error + ? result.error.message + : `exit status ${result.status}`; + log(`::error::${kind} cache: couldn't ${mode}, ${SCRIPT} failed: ${why}`); + } + return failed ? 1 : 0; +} + +function saveIfAsked(kind, scope, effects = {}) { + return shouldSave(effects.env) ? run(kind, "save", scope, effects) : 0; +} + +module.exports = { input, shouldSave, run, saveIfAsked }; diff --git a/build-dependency-cache/s3_cache.py b/build-dependency-cache/s3_cache.py new file mode 100644 index 0000000..d7afbd6 --- /dev/null +++ b/build-dependency-cache/s3_cache.py @@ -0,0 +1,582 @@ +"""Restore or save a CI cache from S3. --kind picks what the archive holds: sbt is sbt's dependency caches (coursier, +ivy, the sbt launcher), mise is mise's data directory (the mise binary, and the tools and plugins it installed), uv is +uv's cache (the packages a project's `uv sync` downloaded). + +The archive for a build lives at $S3_CACHE_URL/[/]/.tar.zst for sbt, at +$S3_CACHE_URL//mise-tools//.tar.zst for mise, and at +$S3_CACHE_URL//uv//.tar.zst for uv, where the key hashes the files the kind names, and +latest beside it names the key main saved last. A scope gives a set of jobs, such as one aggregate's, archives of +their own. Archives expire with the bucket's lifecycle rule; the first push to main after that saves the key again. +The callers are the per-tool actions beside this script: cache-sbt, setup-mise and cache-uv. + +The runners start it with their own python3, so it uses only the standard library of the oldest Python they have, +3.11. What it decides is in pure functions; what it does to S3, tar, git and the clock goes through Effects, which +main builds and the tests replace. +""" + +import argparse +import hashlib +import os +import shutil +import subprocess +import sys +import tempfile +import time +from collections.abc import Callable, Iterator, Mapping, Sequence +from dataclasses import dataclass +from fnmatch import fnmatch +from pathlib import Path +from typing import Final, Protocol, TypeAlias + +TIMEOUT_SECONDS: Final = 900 + +Env: TypeAlias = Mapping[str, str] + + +def no_details(home: Path) -> tuple[str, ...]: + return () + + +@dataclass(frozen=True) +class Contents: + """What an archive holds, and which tracked files decide its key. + + Paths are relative to HOME, so an archive extracts in place on any runner. details lists what the log should + show about the folders beyond their size, such as the tool versions installed. + """ + + paths: tuple[Path, ...] + excludes: tuple[str, ...] + is_key_file: Callable[[Path], bool] + details: Callable[[Path], tuple[str, ...]] = no_details + + +# --- Each kind's key files and folders ------------------------------------------------------------------------------- + + +def is_sbt_build_file(path: Path) -> bool: + return ( + path.name.endswith(".sbt") + or path == Path("mise.toml") + or ("project" in path.parts[:-1] and (path.name.endswith(".scala") or path.name == "build.properties")) + ) + + +def is_mise_config_file(path: Path) -> bool: + """Every mise config in the repository, not only the root's: a job that sets working_directory installs what its + folder's config pins, on top of the root's.""" + return path.name in ("mise.toml", ".mise.toml", "mise.lock", ".tool-versions") + + +def mise_data_dir(env: Env, home: Path) -> Path: + """Where mise keeps its binary, installs and plugins, resolved as jdx/mise-action resolves it when its mise_dir + input is unset.""" + data_dir = env.get("MISE_DATA_DIR") + xdg_data_home = env.get("XDG_DATA_HOME") + return ( + Path(data_dir) + if data_dir + else Path(xdg_data_home) / "mise" + if xdg_data_home + else home / ".local" / "share" / "mise" + ) + + +def uv_cache_dir(env: Env, home: Path) -> Path: + """Where uv keeps its cache, resolved as uv resolves it on Linux.""" + cache_dir = env.get("UV_CACHE_DIR") + xdg_cache_home = env.get("XDG_CACHE_HOME") + return Path(cache_dir) if cache_dir else Path(xdg_cache_home) / "uv" if xdg_cache_home else home / ".cache" / "uv" + + +def uv_project(env: Env) -> Path: + """The project whose uv.lock keys the archive: the scope, else the repository root.""" + return Path(env.get("S3_CACHE_SCOPE", "").strip("/") or ".") + + +def sbt_dependencies(env: Env, home: Path) -> Contents: + # Only caches: ~/.sbt/1.0 also holds global settings and plugins, which sbt compiles and runs in every build, so + # an archive of all of ~/.sbt would carry code from the saving runner into every job that restores it. + return Contents( + paths=(Path(".cache/coursier"), Path(".ivy2/cache"), Path(".sbt/boot"), Path(".sbt/1.0/zinc")), + excludes=("*.lock",), + is_key_file=is_sbt_build_file, + ) + + +def mise_tools(env: Env, home: Path) -> Contents: + # relative_to raises when MISE_DATA_DIR points outside HOME: an archive of an absolute path wouldn't extract in + # place. + data_dir = mise_data_dir(env, home).relative_to(home) + # downloads/ holds the tarballs mise installed from, which are useless once installed and would double the + # archive. + return Contents( + paths=(data_dir,), + excludes=(str(data_dir / "downloads"), "*.lock"), + is_key_file=is_mise_config_file, + details=lambda root: installed_versions(root / data_dir / "installs"), + ) + + +def uv_packages(env: Env, home: Path) -> Contents: + # relative_to raises when UV_CACHE_DIR points outside HOME, as for mise. + cache_dir = uv_cache_dir(env, home).relative_to(home) + lock = uv_project(env) / "uv.lock" + # builds-v0/ holds the throwaway environments uv builds source distributions in. + return Contents( + paths=(cache_dir,), + excludes=(str(cache_dir / "builds-v0"), "*.lock"), + is_key_file=lambda path: path == lock, + ) + + +def installed_versions(installs: Path) -> tuple[str, ...]: + """Each installed tool version, as " ". mise also links partial versions (java/21) to full ones; + the links are left out, so a version a pin no longer names, and that prune should have deleted, stands out.""" + return tuple( + sorted( + f"{tool.name} {version.name}" + for tool in installs.iterdir() + if tool.is_dir() + for version in tool.iterdir() + if version.is_dir() and not version.is_symlink() + ) + if installs.is_dir() + else () + ) + + +# --- The key --------------------------------------------------------------------------------------------------------- + + +def key_files(index: bytes, is_key_file: Callable[[Path], bool]) -> Iterator[tuple[Path, str]]: + """The key files in `git ls-files --stage -z`'s output, each with the object ID of its content in the index. + + Taken from the index rather than the disk, so that the restore and the save of one job compute the same key: a + job can add or edit build files between them, as sbt-dependency-submission does when it drops a plugin into + project/. + """ + # Each entry is " \t". + for entry in filter(None, index.split(b"\0")): + meta, _, name = entry.partition(b"\t") + path = Path(os.fsdecode(name)) + if is_key_file(path): + yield path, meta.split()[1].decode() + + +def cache_key(index: bytes, contents: Contents) -> str: + digest = hashlib.sha256() + for path, object_id in sorted(key_files(index, contents.is_key_file)): + digest.update(os.fsencode(path) + b"\0" + object_id.encode() + b"\0") + return digest.hexdigest()[:32] + + +# --- Where an archive lives ------------------------------------------------------------------------------------------ + + +def location(url: str, repository: str, kind: str, env: Env) -> str: + """The S3 prefix an archive and its latest live under. + + mise archives go under a hash of the mise version, the directory mise runs in and the tools a job installs, so + jobs that install different tools keep separate archives, and latest only falls back to an archive of the same + tools. uv archives go under the project, so each project's packages keep an archive of their own. + """ + match kind: + case "mise": + tools_hash = hashlib.sha256(env["S3_CACHE_TOOLS"].encode()).hexdigest()[:16] + parts = [url, repository, "mise-tools", tools_hash] + case "uv": + parts = [url, repository, "uv", str(uv_project(env))] + case _: + parts = [url, repository, env.get("S3_CACHE_SCOPE", "")] + return "/".join(part.strip("/") for part in parts if part.strip("/") and part.strip("/") != ".") + + +def archive_url(base: str, key: str) -> str: + return f"{base}/{key}.tar.zst" + + +# --- Which archive a restore takes ----------------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class OnRunner: + """The runner restored or saved this key last, so its folders already hold it.""" + + key: str + + +@dataclass(frozen=True) +class InS3: + key: str + + +@dataclass(frozen=True) +class Nowhere: + pass + + +Source: TypeAlias = OnRunner | InS3 | Nowhere + + +def source(key: str, marked: str | None, latest: str | None, saved: Callable[[str], bool]) -> Source: + """Where to restore from: the job's own key, else the key main saved last, each from the runner when its marker + names it, else from S3 when saved there. saved is only asked about keys the runner doesn't have.""" + candidates = (key,) if latest in (None, "", key) else (key, latest) + found = next((candidate for candidate in candidates if candidate == marked or saved(candidate)), None) + return Nowhere() if found is None else OnRunner(found) if found == marked else InS3(found) + + +# --- What the log shows ---------------------------------------------------------------------------------------------- + + +def human(size: int) -> str: + return f"{size / 2**30:.2f} GiB" if size >= 2**30 else f"{size / 2**20:.1f} MiB" + + +@dataclass(frozen=True) +class FolderStats: + path: Path + size: int + files: int + + +def is_excluded(path: Path, excludes: Sequence[str]) -> bool: + """Whether tar leaves path, relative to HOME, out: a pattern with a slash names a path from HOME, any other + pattern matches a file or folder name, as tar's --exclude does.""" + return any(path == Path(pattern) if "/" in pattern else fnmatch(path.name, pattern) for pattern in excludes) + + +def folder_stats(home: Path, path: Path, excludes: Sequence[str]) -> FolderStats: + """The size and file count of what an archive of path holds. Links count as themselves, not as what they point + to, as tar stores them.""" + size = 0 + files = 0 + for root, dirs, names in os.walk(home / path): + relative = Path(root).relative_to(home) + # os.walk descends into what's left in dirs, so excluded folders are skipped. + dirs[:] = [d for d in dirs if not is_excluded(relative / d, excludes)] + for name in names: + if is_excluded(relative / name, excludes): + continue + try: + size += os.lstat(Path(root) / name).st_size + files += 1 + except OSError: + pass + return FolderStats(path, size, files) + + +def stats_lines(label: str, home: Path, contents: Contents) -> tuple[str, ...]: + """What the cache folders hold after a restore or at a save, so runs can be compared: a line in the notices, and + the breakdown in a collapsed group of the step's log.""" + stats = [folder_stats(home, path, contents.excludes) for path in contents.paths] + size = sum(s.size for s in stats) + files = sum(s.files for s in stats) + return ( + f"::notice::{label}: on disk, {human(size)} in {files:,} files", + f"::group::{label}: what's on disk", + *(f"~/{s.path}: {human(s.size)} in {s.files:,} files" for s in stats), + *contents.details(home), + "::endgroup::", + ) + + +# --- The effects ----------------------------------------------------------------------------------------------------- + + +class S3(Protocol): + def exists(self, url: str) -> bool: ... + + def read_text(self, url: str) -> str | None: + """The object's text, or None when it can't be read, as when there's none.""" + ... + + def download(self, url: str, path: Path) -> None: ... + + def upload(self, path: Path, url: str) -> None: ... + + def write_text(self, url: str, text: str) -> None: ... + + +class Archiver(Protocol): + def pack(self, archive: Path, root: Path, paths: Sequence[Path], excludes: Sequence[str]) -> None: ... + + def unpack(self, archive: Path, root: Path) -> None: ... + + +@dataclass(frozen=True) +class Effects: + s3: S3 + archiver: Archiver + # `git ls-files --stage -z` in a workspace. + index: Callable[[Path], bytes] + clock: Callable[[], float] + + +def head_object_found(url: str, returncode: int, stderr: str) -> bool: + """What `aws s3api head-object` says about an object: there, missing, or a failure to check.""" + if returncode != 0 and "Not Found" not in stderr and "404" not in stderr: + raise RuntimeError(f"couldn't check {url}: {stderr.strip()}") + return returncode == 0 + + +class AwsCli: + """S3 through the aws CLI the runners have.""" + + def exists(self, url: str) -> bool: + bucket, _, key = url.removeprefix("s3://").partition("/") + result = subprocess.run( + ["aws", "s3api", "head-object", "--bucket", bucket, "--key", key], + check=False, + capture_output=True, + text=True, + timeout=TIMEOUT_SECONDS, + ) + return head_object_found(url, result.returncode, result.stderr) + + def read_text(self, url: str) -> str | None: + result = subprocess.run( + ["aws", "s3", "cp", "--no-progress", url, "-"], + check=False, + capture_output=True, + text=True, + timeout=TIMEOUT_SECONDS, + ) + return result.stdout if result.returncode == 0 else None + + def download(self, url: str, path: Path) -> None: + subprocess.run(["aws", "s3", "cp", "--no-progress", url, str(path)], check=True, timeout=TIMEOUT_SECONDS) + + def upload(self, path: Path, url: str) -> None: + subprocess.run(["aws", "s3", "cp", "--no-progress", str(path), url], check=True, timeout=TIMEOUT_SECONDS) + + def write_text(self, url: str, text: str) -> None: + with tempfile.NamedTemporaryFile("w", suffix=".txt") as file: + file.write(text) + file.flush() + self.upload(Path(file.name), url) + + +def pack_command(archive: Path, root: Path, paths: Sequence[Path], excludes: Sequence[str]) -> list[str]: + return [ + "tar", + "-I", + "zstd -T0 -3", + "-cf", + str(archive), + *(f"--exclude={pattern}" for pattern in excludes), + "-C", + str(root), + *map(str, paths), + ] + + +def unpack_command(archive: Path, root: Path) -> list[str]: + return ["tar", "-I", "zstd", "-xf", str(archive), "-C", str(root)] + + +class Tar: + """zstd tar archives, through the runners' GNU tar and zstd.""" + + def pack(self, archive: Path, root: Path, paths: Sequence[Path], excludes: Sequence[str]) -> None: + subprocess.run(pack_command(archive, root, paths, excludes), check=True, timeout=TIMEOUT_SECONDS) + + def unpack(self, archive: Path, root: Path) -> None: + subprocess.run(unpack_command(archive, root), check=True, timeout=TIMEOUT_SECONDS) + + +def git_index(workspace: Path) -> bytes: + listed = subprocess.run( + ["git", "-C", str(workspace), "ls-files", "--stage", "-z"], + check=False, + capture_output=True, + timeout=TIMEOUT_SECONDS, + ) + if listed.returncode != 0: + raise RuntimeError(f"git ls-files failed: {listed.stderr.decode(errors='replace').strip()}") + return listed.stdout + + +# --- Restore and save ------------------------------------------------------------------------------------------------ + + +@dataclass(frozen=True) +class Cache: + """One archive location, the key the job wants there, and the folders under home it holds.""" + + home: Path + base: str + key: str + contents: Contents + # Where the archive is packed or downloaded on the runner. + archive: Path + + +def markers(home: Path) -> Path: + """One file per archive location, naming the key this runner last restored or saved for it. Runners take several + jobs before they are replaced, so the next job of the same scope on the same runner usually needs no download.""" + return home / ".cache" / "sbt-dependency-cache" + + +def marker(home: Path, base: str) -> Path: + return markers(home) / hashlib.sha256(base.encode()).hexdigest()[:16] + + +def marked_key(home: Path, base: str) -> str | None: + try: + return marker(home, base).read_text().strip() + except FileNotFoundError: + return None + + +def mark(home: Path, base: str, key: str) -> None: + markers(home).mkdir(parents=True, exist_ok=True) + marker(home, base).write_text(key) + + +def discard(home: Path, contents: Contents) -> None: + # Several locations can extract into the same folders (every sbt scope shares the coursier cache), so a broken + # extraction invalidates every marker. + shutil.rmtree(markers(home), ignore_errors=True) + for path in contents.paths: + shutil.rmtree(home / path, ignore_errors=True) + + +def download(cache: Cache, effects: Effects, key: str) -> str: + started = effects.clock() + effects.s3.download(archive_url(cache.base, key), cache.archive) + downloaded = effects.clock() + # Drop the marker first, so a failed extraction can't leave a runner claiming a key it doesn't have. + marker(cache.home, cache.base).unlink(missing_ok=True) + try: + effects.archiver.unpack(cache.archive, cache.home) + except Exception: + # A half-extracted jar looks present to coursier, and a half-extracted JDK looks installed to mise, so start + # from nothing rather than from that. + discard(cache.home, cache.contents) + raise + mark(cache.home, cache.base, key) + wanted = "" if key == cache.key else f" (newest from main; wanted {cache.key})" + return ( + f"restored {key}{wanted}: {human(cache.archive.stat().st_size)} downloaded in {downloaded - started:.0f}s," + f" unpacked in {effects.clock() - downloaded:.0f}s" + ) + + +def restore(cache: Cache, effects: Effects) -> str: + marked = marked_key(cache.home, cache.base) + latest = None if marked == cache.key else effects.s3.read_text(f"{cache.base}/latest") + found = source( + cache.key, marked, latest and latest.strip(), lambda key: effects.s3.exists(archive_url(cache.base, key)) + ) + match found: + case OnRunner(key) if key == cache.key: + return f"runner already has {key}" + case OnRunner(key): + return f"runner already has {key}, the newest from main" + case InS3(key): + return download(cache, effects, key) + case Nowhere(): + return f"no archive for {cache.key} or from main yet, so everything is downloaded" + + +def save(cache: Cache, effects: Effects) -> str: + url = archive_url(cache.base, cache.key) + if effects.s3.exists(url): + mark(cache.home, cache.base, cache.key) + outcome = f"{cache.key} is already saved" + else: + paths = [path for path in cache.contents.paths if (cache.home / path).is_dir()] + if not paths: + raise RuntimeError(f"none of {', '.join(map(str, cache.contents.paths))} exist under {cache.home}") + started = effects.clock() + effects.archiver.pack(cache.archive, cache.home, paths, cache.contents.excludes) + packed = effects.clock() + effects.s3.upload(cache.archive, url) + uploaded = effects.clock() + # Only after an upload: an older commit's job that finishes last must not point latest back at its key. + effects.s3.write_text(f"{cache.base}/latest", cache.key) + mark(cache.home, cache.base, cache.key) + outcome = ( + f"saved {cache.key}: {human(cache.archive.stat().st_size)} packed in {packed - started:.0f}s," + f" uploaded in {uploaded - packed:.0f}s" + ) + return outcome + + +# --- The kinds, and the command line --------------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Kind: + """One --kind: how to build its Contents, and how its notices read.""" + + contents: Callable[[Env, Path], Contents] + label: str + without_it: str + + +KINDS: Final = { + "sbt": Kind(sbt_dependencies, "sbt dependency cache", "sbt resolves everything"), + "mise": Kind(mise_tools, "mise tools cache", "mise downloads its tools"), + "uv": Kind(uv_packages, "uv cache", "uv downloads every package"), +} + + +def run(argv: Sequence[str], env: Env, home: Path, effects: Effects, out: Callable[[str], None]) -> int: + """Restores or saves, writing its notices and warnings to out, and returns the exit status: 1 only without a URL, + since any other failure only costs the job its cache.""" + parser = argparse.ArgumentParser() + parser.add_argument("mode", choices=["save", "restore"]) + parser.add_argument("--kind", choices=KINDS, required=True) + args = parser.parse_args(argv) + kind = KINDS[args.kind] + url = env.get("S3_CACHE_URL", "").rstrip("/") + if not url: + # Callers pass it from an organization variable, which a repository may not have. Failing the step, unlike + # the warnings below, keeps a job from running without its cache unnoticed. + out( + f"::error::{kind.label}: no S3 URL. Pass the action's url input, such as the organization variable" + " COMMON_GITHUB_BUILD_DEPENDENCY_CACHE." + ) + return 1 + archive = Path(env["RUNNER_TEMP"], f"s3-cache-{args.kind}.tar.zst") + start = effects.clock() + try: + # Built inside the try: mise_tools raises when mise's data directory is outside HOME, and that only costs the + # job its cache. + contents = kind.contents(env, home) + cache = Cache( + home=home, + base=location(url, env["GITHUB_REPOSITORY"].split("/")[-1], args.kind, env), + key=cache_key(effects.index(Path(env["GITHUB_WORKSPACE"])), contents), + contents=contents, + archive=archive, + ) + outcome = save(cache, effects) if args.mode == "save" else restore(cache, effects) + out(f"::notice::{kind.label}: {outcome} ({effects.clock() - start:.0f}s in all)") + # Its own try: stats that fail to compute cost the log a line, not the cache. + try: + for line in stats_lines(kind.label, home, contents): + out(line) + except Exception as e: # noqa: BLE001 -- any failure here costs the log a line, and no more + out(f"::warning::{kind.label}: couldn't measure what's on disk: {e}") + except Exception as e: # noqa: BLE001 -- any failure costs the job its cache, not the job itself + out( + f"::warning::{kind.label}: couldn't restore, so {kind.without_it}: {e}" + if args.mode == "restore" + else f"::warning::{kind.label}: couldn't save, so other runs restore an older one: {e}" + ) + finally: + archive.unlink(missing_ok=True) + return 0 + + +def main() -> None: + effects = Effects(s3=AwsCli(), archiver=Tar(), index=git_index, clock=time.monotonic) + raise SystemExit(run(sys.argv[1:], os.environ, Path.home(), effects, print)) + + +if __name__ == "__main__": + main() diff --git a/build-dependency-cache/setup-mise/action.yml b/build-dependency-cache/setup-mise/action.yml new file mode 100644 index 0000000..2e9c327 --- /dev/null +++ b/build-dependency-cache/setup-mise/action.yml @@ -0,0 +1,83 @@ +name: Set up mise +description: > + jdx/mise-action, with mise's data directory (the mise binary, and the tools and plugins it installs) kept in + S3 instead of GitHub's cache. Self-hosted runners in a private subnet reach GitHub's cache, which is Azure + storage, through their NAT gateway, and mise-action restored about 0.7 GB from it on every job; S3 in the + runners' region is reached through a free gateway endpoint. On a hit, mise-action finds the pinned binary and + every tool already installed, and downloads nothing but mise's signed checksums. On a miss, mise downloads + from GitHub releases, and a push to main saves the result. + + Use it in place of jdx/mise-action in any job that installs tools. A job that passes `install: false` gets + its tools elsewhere, so it keeps jdx/mise-action with `cache: false`. + + A composite action can't read repository variables, so callers pass their kill switch in as s3_cache, such + as the expression `vars.MISE_TOOLS_CACHE != 'off'`. With it off, mise downloads everything on every job; it + never falls back to GitHub's cache. (GitHub evaluates expressions even in this file's descriptions, so none + of them may contain one.) + +inputs: + version: + description: The mise version, as jdx/mise-action takes it. + required: true + install_args: + description: What `mise install` installs, as jdx/mise-action takes it. Empty installs everything the config pins. + default: "" + working_directory: + description: > + The directory mise runs in, as jdx/mise-action takes it. Its mise config pins the tools, so jobs in + different directories keep separate archives. + default: "" + s3_cache: + description: Whether to restore and save from S3, as "true" or "false"; the caller's kill switch. + required: true + url: + description: > + Base S3 URL, s3:///; callers pass the organization variable + COMMON_GITHUB_BUILD_DEPENDENCY_CACHE. The repository name and key go under it. The runners need read and + write there. Empty fails the step. + required: true + +# The cache steps run ../s3_cache.py themselves rather than through another action: an action in a shared +# repository can only reach a sibling action with `uses: /@`, and a commit can't +# name itself. ./ would point into the caller's checkout instead. +runs: + using: composite + steps: + - name: Restore the mise tools cache + if: inputs.s3_cache == 'true' + shell: bash + env: + S3_CACHE_URL: ${{ inputs.url }} + S3_CACHE_TOOLS: ${{ inputs.version }} ${{ inputs.working_directory }} ${{ inputs.install_args }} + run: python3 "$GITHUB_ACTION_PATH/../s3_cache.py" restore --kind mise + - name: Set up mise + uses: jdx/mise-action@8418fedb1110381a0d3ba51a7a415d7c1b884550 # v5.2.2 + with: + version: ${{ inputs.version }} + install_args: ${{ inputs.install_args }} + working_directory: ${{ inputs.working_directory }} + cache: false + # A new archive starts from the one it restored, so without this it keeps every tool version the pins ever + # named: a JDK bump would leave both JDKs in it. prune deletes the versions that no config this runner + # loaded still selects. mise-action loaded this job's, root and working_directory, so its tools stay. + # Only before a save, so pull requests leave the runner as they found it. + - name: Prune tool versions nothing pins + if: inputs.s3_cache == 'true' && github.event_name == 'push' && github.ref == 'refs/heads/main' + shell: bash + run: mise prune --yes --tools || echo "::warning::mise prune failed, so the saved archive keeps unused versions" + # Right after the install, not at the end of the job as cache-sbt saves, which is a trade-off. Saving at the + # end, from a post step, would let the job's real work start sooner: packing and uploading the ~0.7 GB archive + # takes seconds. We save first instead, because: + # - the data directory is complete now, and a later step (a `mise install`, a task) could add tools to it; + # - a job that fails later still saves the tools it installed, so the next runs don't download them again; + # - the archive is in S3 sooner, for the runs that start meanwhile. + # The cost is only paid on a push to main that brings a key with no archive yet (after a change to a mise + # config or install_args); otherwise the save is one existence check, and pull requests skip it. A post step + # would also need a JavaScript helper action: this one has to be composite to call mise-action. + - name: Save the mise tools cache + if: inputs.s3_cache == 'true' && github.event_name == 'push' && github.ref == 'refs/heads/main' + shell: bash + env: + S3_CACHE_URL: ${{ inputs.url }} + S3_CACHE_TOOLS: ${{ inputs.version }} ${{ inputs.working_directory }} ${{ inputs.install_args }} + run: python3 "$GITHUB_ACTION_PATH/../s3_cache.py" save --kind mise diff --git a/build-dependency-cache/tests/s3-cache.test.js b/build-dependency-cache/tests/s3-cache.test.js new file mode 100644 index 0000000..4478d55 --- /dev/null +++ b/build-dependency-cache/tests/s3-cache.test.js @@ -0,0 +1,74 @@ +// Tests ../s3-cache.js, which the JavaScript actions run, with fakes for spawnSync and console.log. Run with +// `node --test tests/s3-cache.test.js` from the folder above. +const assert = require("node:assert/strict"); +const { test } = require("node:test"); + +const { input, shouldSave, run, saveIfAsked } = require("../s3-cache.js"); + +const MAIN = { GITHUB_EVENT_NAME: "push", GITHUB_REF: "refs/heads/main" }; + +// Records each spawn, and answers with result. +function fakeSpawn(result) { + const calls = []; + const spawn = (command, args, options) => { + calls.push({ command, args, env: options.env }); + return result; + }; + return { calls, spawn }; +} + +test("input reads INPUT_, trimmed, and is empty when unset", () => { + assert.equal(input("working_directory", { INPUT_WORKING_DIRECTORY: " sub \n" }), "sub"); + assert.equal(input("scope", {}), ""); +}); + +test("saves only with save: true on a push to main", () => { + assert.equal(shouldSave({ ...MAIN, INPUT_SAVE: "true" }), true); + assert.equal(shouldSave({ ...MAIN, INPUT_SAVE: "false" }), false); + assert.equal( + shouldSave({ INPUT_SAVE: "true", GITHUB_EVENT_NAME: "pull_request", GITHUB_REF: "refs/pull/1/merge" }), + false, + ); + assert.equal( + shouldSave({ INPUT_SAVE: "true", GITHUB_EVENT_NAME: "push", GITHUB_REF: "refs/heads/feature" }), + false, + ); +}); + +test("run passes the kind, mode, url and scope to s3_cache.py", () => { + const { calls, spawn } = fakeSpawn({ status: 0 }); + const env = { INPUT_URL: "s3://bucket/prefix", PATH: "/bin" }; + assert.equal(run("uv", "restore", "sub", { env, spawn, log: () => {} }), 0); + assert.equal(calls.length, 1); + assert.equal(calls[0].command, "python3"); + assert.match(calls[0].args[0], /s3_cache\.py$/); + assert.deepEqual(calls[0].args.slice(1), ["restore", "--kind", "uv"]); + assert.equal(calls[0].env.S3_CACHE_URL, "s3://bucket/prefix"); + assert.equal(calls[0].env.S3_CACHE_SCOPE, "sub"); + assert.equal(calls[0].env.PATH, "/bin"); +}); + +test("run fails the step, and says why, when s3_cache.py fails", () => { + const lines = []; + const { spawn } = fakeSpawn({ status: 1 }); + assert.equal(run("sbt", "restore", "", { env: {}, spawn, log: (line) => lines.push(line) }), 1); + assert.match(lines[0], /^::error::sbt cache: couldn't restore, .*s3_cache\.py failed: exit status 1$/); +}); + +test("run fails the step, and says why, when python3 can't start", () => { + const lines = []; + const { spawn } = fakeSpawn({ status: null, error: new Error("spawnSync python3 ENOENT") }); + assert.equal(run("sbt", "restore", "", { env: {}, spawn, log: (line) => lines.push(line) }), 1); + assert.match(lines[0], /failed: spawnSync python3 ENOENT$/); +}); + +test("saveIfAsked runs a save only when asked, on main", () => { + const skipped = fakeSpawn({ status: 0 }); + assert.equal(saveIfAsked("sbt", "", { env: { INPUT_SAVE: "true" }, spawn: skipped.spawn }), 0); + assert.equal(skipped.calls.length, 0); + + const saved = fakeSpawn({ status: 0 }); + assert.equal(saveIfAsked("sbt", "agg", { env: { ...MAIN, INPUT_SAVE: "true" }, spawn: saved.spawn }), 0); + assert.deepEqual(saved.calls[0].args.slice(1), ["save", "--kind", "sbt"]); + assert.equal(saved.calls[0].env.S3_CACHE_SCOPE, "agg"); +}); diff --git a/build-dependency-cache/tests/test_s3_cache.py b/build-dependency-cache/tests/test_s3_cache.py new file mode 100644 index 0000000..f98126c --- /dev/null +++ b/build-dependency-cache/tests/test_s3_cache.py @@ -0,0 +1,461 @@ +import shutil +import subprocess +import tarfile +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path + +import pytest + +import s3_cache +from s3_cache import Effects, InS3, Nowhere, OnRunner + +# --- Decisions ------------------------------------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("path", "expected"), + [ + ("build.sbt", True), + ("aggregate/module.sbt", True), + ("mise.toml", True), + ("project/Dependencies.scala", True), + ("project/build.properties", True), + ("nql/project/plugins.scala", True), + ("sub/mise.toml", False), + ("src/main/scala/Main.scala", False), + ("build.properties", False), + ], +) +def test_sbt_build_files(path: str, *, expected: bool) -> None: + assert s3_cache.is_sbt_build_file(Path(path)) is expected + + +@pytest.mark.parametrize( + ("path", "expected"), + [ + ("mise.toml", True), + ("sub/.mise.toml", True), + ("sub/mise.lock", True), + (".tool-versions", True), + ("mise.toml.bak", False), + ], +) +def test_mise_config_files(path: str, *, expected: bool) -> None: + assert s3_cache.is_mise_config_file(Path(path)) is expected + + +HOME = Path("/home/runner") + + +@pytest.mark.parametrize( + ("env", "expected"), + [ + ({"MISE_DATA_DIR": "/opt/mise", "XDG_DATA_HOME": "/xdg"}, "/opt/mise"), + ({"XDG_DATA_HOME": "/xdg"}, "/xdg/mise"), + ({}, "/home/runner/.local/share/mise"), + ], +) +def test_mise_data_dir(env: Mapping[str, str], expected: str) -> None: + assert s3_cache.mise_data_dir(env, HOME) == Path(expected) + + +@pytest.mark.parametrize( + ("env", "expected"), + [ + ({"UV_CACHE_DIR": "/opt/uv", "XDG_CACHE_HOME": "/xdg"}, "/opt/uv"), + ({"XDG_CACHE_HOME": "/xdg"}, "/xdg/uv"), + ({}, "/home/runner/.cache/uv"), + ], +) +def test_uv_cache_dir(env: Mapping[str, str], expected: str) -> None: + assert s3_cache.uv_cache_dir(env, HOME) == Path(expected) + + +def test_mise_tools_leave_out_downloads() -> None: + contents = s3_cache.mise_tools({}, HOME) + assert contents.paths == (Path(".local/share/mise"),) + assert ".local/share/mise/downloads" in contents.excludes + + +def test_mise_tools_refuse_a_data_directory_outside_home() -> None: + with pytest.raises(ValueError, match="mise"): + s3_cache.mise_tools({"MISE_DATA_DIR": "/opt/mise"}, HOME) + + +def test_uv_packages_are_keyed_by_their_project_lock_and_leave_out_builds() -> None: + contents = s3_cache.uv_packages({"S3_CACHE_SCOPE": "/sub/"}, HOME) + assert contents.is_key_file(Path("sub/uv.lock")) + assert not contents.is_key_file(Path("uv.lock")) + assert ".cache/uv/builds-v0" in contents.excludes + + +def test_uv_packages_default_to_the_root_project() -> None: + assert s3_cache.uv_packages({}, HOME).is_key_file(Path("uv.lock")) + + +def index(entries: Mapping[str, str]) -> bytes: + """What `git ls-files --stage -z` prints for these paths and object IDs.""" + return b"".join(f"100644 {object_id} 0\t{path}\0".encode() for path, object_id in entries.items()) + + +def test_key_files_are_the_matching_paths_with_their_object_ids() -> None: + listed = index({"build.sbt": "a1", "README.md": "b2", "project/build.properties": "c3"}) + assert list(s3_cache.key_files(listed, s3_cache.is_sbt_build_file)) == [ + (Path("build.sbt"), "a1"), + (Path("project/build.properties"), "c3"), + ] + + +def test_the_key_ignores_order_and_other_files_but_not_content() -> None: + sbt = s3_cache.sbt_dependencies({}, HOME) + key = s3_cache.cache_key(index({"build.sbt": "a1", "project/build.properties": "c3"}), sbt) + assert s3_cache.cache_key(index({"project/build.properties": "c3", "build.sbt": "a1", "x.md": "d4"}), sbt) == key + assert s3_cache.cache_key(index({"build.sbt": "a2", "project/build.properties": "c3"}), sbt) != key + assert len(key) == 32 + + +def test_sbt_archives_live_under_the_repository_and_scope() -> None: + assert s3_cache.location("s3://b/p", "repo", "sbt", {}) == "s3://b/p/repo" + assert s3_cache.location("s3://b/p", "repo", "sbt", {"S3_CACHE_SCOPE": "/agg/"}) == "s3://b/p/repo/agg" + + +def test_mise_archives_live_under_a_hash_of_the_tools() -> None: + java = s3_cache.location("s3://b/p", "repo", "mise", {"S3_CACHE_TOOLS": "2026.11.10 java"}) + python = s3_cache.location("s3://b/p", "repo", "mise", {"S3_CACHE_TOOLS": "2026.11.10 sub python uv"}) + assert java.startswith("s3://b/p/repo/mise-tools/") + assert len(java.rsplit("/", 1)[1]) == 16 + assert java != python + + +def test_uv_archives_live_under_the_project() -> None: + assert s3_cache.location("s3://b/p", "repo", "uv", {"S3_CACHE_SCOPE": "sub"}) == "s3://b/p/repo/uv/sub" + assert s3_cache.location("s3://b/p", "repo", "uv", {}) == "s3://b/p/repo/uv" + + +def never(key: str) -> bool: + raise AssertionError(f"asked S3 about {key}") + + +@pytest.mark.parametrize( + ("marked", "latest", "saved", "expected"), + [ + ("k", None, (), OnRunner("k")), + (None, None, ("k",), InS3("k")), + (None, "old", ("k", "old"), InS3("k")), + (None, "old", ("old",), InS3("old")), + ("old", "old", (), OnRunner("old")), + (None, "k", (), Nowhere()), + (None, "", (), Nowhere()), + (None, None, (), Nowhere()), + ], +) +def test_where_a_restore_comes_from( + marked: str | None, latest: str | None, saved: tuple[str, ...], expected: s3_cache.Source +) -> None: + assert s3_cache.source("k", marked, latest, lambda key: key in saved) == expected + + +def test_a_key_the_runner_has_asks_nothing_of_s3() -> None: + assert s3_cache.source("k", "k", "old", never) == OnRunner("k") + + +def test_head_object_found() -> None: + assert s3_cache.head_object_found("s3://b/k", 0, "") + assert not s3_cache.head_object_found("s3://b/k", 254, "An error occurred (404) ...: Not Found") + with pytest.raises(RuntimeError, match="couldn't check s3://b/k: Access Denied"): + s3_cache.head_object_found("s3://b/k", 254, "Access Denied\n") + + +@pytest.mark.parametrize( + ("path", "expected"), + [ + (".cache/uv/builds-v0", True), + (".cache/uv/wheels-v5/builds-v0", False), + (".ivy2/cache/x.lock", True), + (".ivy2/cache/x.jar", False), + ], +) +def test_is_excluded(path: str, *, expected: bool) -> None: + assert s3_cache.is_excluded(Path(path), (".cache/uv/builds-v0", "*.lock")) is expected + + +def test_human_sizes() -> None: + assert s3_cache.human(3 * 2**20) == "3.0 MiB" + assert s3_cache.human(3 * 2**30) == "3.00 GiB" + + +def test_tar_commands() -> None: + archive = Path("/tmp/a.tar.zst") + assert s3_cache.pack_command(archive, HOME, [Path(".ivy2/cache")], ["*.lock"]) == [ + *("tar", "-I", "zstd -T0 -3", "-cf", "/tmp/a.tar.zst", "--exclude=*.lock"), + *("-C", "/home/runner", ".ivy2/cache"), + ] + assert s3_cache.unpack_command(archive, HOME) == [ + "tar", + "-I", + "zstd", + "-xf", + "/tmp/a.tar.zst", + "-C", + "/home/runner", + ] + + +# --- Disk ------------------------------------------------------------------------------------------------------------ + + +def write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + +def test_installed_versions_leave_out_alias_links(tmp_path: Path) -> None: + (tmp_path / "java" / "21.0.13").mkdir(parents=True) + (tmp_path / "java" / "21").symlink_to("21.0.13") + (tmp_path / "uv" / "0.13.7").mkdir(parents=True) + assert s3_cache.installed_versions(tmp_path) == ("java 21.0.13", "uv 0.13.7") + assert s3_cache.installed_versions(tmp_path / "missing") == () + + +def test_folder_stats_leave_out_excluded_files_and_folders(tmp_path: Path) -> None: + write(tmp_path / ".cache/uv/wheels-v5/a.whl", "12345") + write(tmp_path / ".cache/uv/x.lock", "1") + write(tmp_path / ".cache/uv/builds-v0/env", "1") + stats = s3_cache.folder_stats(tmp_path, Path(".cache/uv"), (".cache/uv/builds-v0", "*.lock")) + assert (stats.size, stats.files) == (5, 1) + + +def test_git_index_lists_what_git_tracks(tmp_path: Path) -> None: + write(tmp_path / "build.sbt", "lazy val root = project\n") + subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) + subprocess.run(["git", "-C", str(tmp_path), "add", "build.sbt"], check=True) + assert [path for path, _ in s3_cache.key_files(s3_cache.git_index(tmp_path), s3_cache.is_sbt_build_file)] == [ + Path("build.sbt") + ] + + +def test_git_index_fails_outside_a_repository(tmp_path: Path) -> None: + with pytest.raises(RuntimeError, match="git ls-files failed"): + s3_cache.git_index(tmp_path) + + +@pytest.mark.skipif( + shutil.which("zstd") is None + or "GNU tar" not in subprocess.run(["tar", "--version"], capture_output=True, text=True, check=False).stdout, + reason="needs GNU tar and zstd, as the runners have; macOS's tar reads -I as --files-from", +) +def test_tar_round_trip(tmp_path: Path) -> None: + write(tmp_path / "home/.ivy2/cache/a.jar", "jar") + write(tmp_path / "home/.ivy2/cache/a.lock", "lock") + archive = tmp_path / "a.tar.zst" + s3_cache.Tar().pack(archive, tmp_path / "home", [Path(".ivy2/cache")], ["*.lock"]) + (tmp_path / "restored").mkdir() + s3_cache.Tar().unpack(archive, tmp_path / "restored") + assert (tmp_path / "restored/.ivy2/cache/a.jar").read_text() == "jar" + assert not (tmp_path / "restored/.ivy2/cache/a.lock").exists() + + +# --- Restore and save, against an S3 in memory ----------------------------------------------------------------------- + + +@dataclass +class FakeS3: + objects: dict[str, bytes] = field(default_factory=dict) + + def exists(self, url: str) -> bool: + return url in self.objects + + def read_text(self, url: str) -> str | None: + return self.objects[url].decode() if url in self.objects else None + + def download(self, url: str, path: Path) -> None: + path.write_bytes(self.objects[url]) + + def upload(self, path: Path, url: str) -> None: + self.objects[url] = path.read_bytes() + + def write_text(self, url: str, text: str) -> None: + self.objects[url] = text.encode() + + def keys(self, suffix: str) -> list[str]: + return sorted(url for url in self.objects if url.endswith(suffix)) + + +class PlainTar: + """An uncompressed tar through tarfile, leaving out what tar's --exclude would: the runners' GNU tar and zstd + aren't on every laptop.""" + + def pack(self, archive: Path, root: Path, paths: Sequence[Path], excludes: Sequence[str]) -> None: + with tarfile.open(archive, "w") as tar: + for path in paths: + tar.add( + root / path, + arcname=str(path), + filter=lambda info: None if s3_cache.is_excluded(Path(info.name), excludes) else info, + ) + + def unpack(self, archive: Path, root: Path) -> None: + with tarfile.open(archive) as tar: + tar.extractall(root, filter="tar") + + +class BrokenTar(PlainTar): + def unpack(self, archive: Path, root: Path) -> None: + write(root / ".cache/coursier/half.jar", "half") + raise OSError("disk full") + + +@dataclass +class Runner: + """One runner's HOME and workspace, and what it runs s3_cache.py against.""" + + root: Path + s3: FakeS3 = field(default_factory=FakeS3) + archiver: s3_cache.Archiver = field(default_factory=PlainTar) + tracked: dict[str, str] = field(default_factory=lambda: {"build.sbt": "a1", "mise.toml": "b2"}) + + @property + def home(self) -> Path: + return self.root / "home" + + def run(self, *argv: str, **env: str) -> tuple[int, list[str]]: + lines: list[str] = [] + (self.root / "tmp").mkdir(parents=True, exist_ok=True) + effects = Effects(s3=self.s3, archiver=self.archiver, index=lambda _: index(self.tracked), clock=lambda: 0.0) + status = s3_cache.run( + argv, + { + "S3_CACHE_URL": "s3://bucket/prefix/", + "RUNNER_TEMP": str(self.root / "tmp"), + "GITHUB_REPOSITORY": "narrative-io/example", + "GITHUB_WORKSPACE": str(self.root / "ws"), + **env, + }, + self.home, + effects, + lines.append, + ) + return status, lines + + def outcome(self, *argv: str, **env: str) -> str: + status, lines = self.run(*argv, **env) + assert status == 0 + return lines[0] + + def new_runner(self, name: str) -> "Runner": + """Another runner of the fleet: same S3 and workspace, an empty HOME.""" + return Runner(self.root.parent / name, self.s3, self.archiver, self.tracked) + + +@pytest.fixture +def runner(tmp_path: Path) -> Runner: + return Runner(tmp_path / "first") + + +def test_save_uploads_the_archive_and_latest(runner: Runner) -> None: + write(runner.home / ".cache/coursier/v1/a.jar", "jar") + status, lines = runner.run("save", "--kind", "sbt") + assert status == 0 + assert lines[0].startswith("::notice::sbt dependency cache: saved ") + assert lines[1] == "::notice::sbt dependency cache: on disk, 0.0 MiB in 1 files" + assert runner.s3.keys("/latest") == ["s3://bucket/prefix/example/latest"] + assert runner.s3.keys(".tar.zst")[0].startswith("s3://bucket/prefix/example/") + + +def test_a_saved_key_is_not_saved_again(runner: Runner) -> None: + write(runner.home / ".cache/coursier/v1/a.jar", "jar") + runner.run("save", "--kind", "sbt") + assert "is already saved" in runner.outcome("save", "--kind", "sbt") + + +def test_save_warns_when_there_is_nothing_to_save(runner: Runner) -> None: + assert runner.outcome("save", "--kind", "sbt").startswith( + "::warning::sbt dependency cache: couldn't save, so other runs restore an older one: none of .cache/coursier" + ) + + +def test_a_fresh_runner_restores_and_a_warm_one_skips_the_download(runner: Runner) -> None: + write(runner.home / ".cache/coursier/v1/a.jar", "jar") + write(runner.home / ".ivy2/cache/x.lock", "lock") + runner.run("save", "--kind", "sbt") + fresh = runner.new_runner("second") + assert "restored " in fresh.outcome("restore", "--kind", "sbt") + assert (fresh.home / ".cache/coursier/v1/a.jar").read_text() == "jar" + assert not (fresh.home / ".ivy2/cache/x.lock").exists() + assert "runner already has " in fresh.outcome("restore", "--kind", "sbt") + + +def test_another_scope_has_its_own_archive(runner: Runner) -> None: + write(runner.home / ".cache/coursier/v1/a.jar", "jar") + runner.run("save", "--kind", "sbt") + assert "no archive for " in runner.outcome("restore", "--kind", "sbt", S3_CACHE_SCOPE="agg") + + +def test_a_changed_build_file_falls_back_to_latest(runner: Runner) -> None: + write(runner.home / ".cache/coursier/v1/a.jar", "jar") + runner.run("save", "--kind", "sbt") + runner.tracked["build.sbt"] = "a2" + assert "already has" in runner.outcome("restore", "--kind", "sbt") + assert "(newest from main; wanted " in runner.new_runner("second").outcome("restore", "--kind", "sbt") + + +def test_a_failed_extraction_leaves_nothing_behind(runner: Runner) -> None: + write(runner.home / ".cache/coursier/v1/a.jar", "jar") + runner.run("save", "--kind", "sbt") + broken = Runner(runner.root.parent / "second", runner.s3, BrokenTar(), runner.tracked) + write(broken.home / ".cache/sbt-dependency-cache/other", "k") + assert broken.outcome("restore", "--kind", "sbt") == ( + "::warning::sbt dependency cache: couldn't restore, so sbt resolves everything: disk full" + ) + assert not (broken.home / ".cache/coursier").exists() + assert not (broken.home / ".cache/sbt-dependency-cache").exists() + + +def test_an_empty_url_fails(runner: Runner) -> None: + assert runner.run("restore", "--kind", "sbt", S3_CACHE_URL="") == ( + 1, + [ + ( + "::error::sbt dependency cache: no S3 URL. Pass the action's url input, such as the organization" + " variable COMMON_GITHUB_BUILD_DEPENDENCY_CACHE." + ) + ], + ) + + +def test_mise_saves_its_data_directory_but_not_its_downloads(runner: Runner) -> None: + mise = runner.home / ".local/share/mise" + write(mise / "bin/mise", "mise") + write(mise / "installs/java/21.0.13/bin/java", "jdk") + (mise / "installs/java/21").symlink_to("21.0.13") + write(mise / "downloads/jdk.tar.gz", "tarball") + tools = {"S3_CACHE_TOOLS": "2026.11.10 java"} + _, lines = runner.run("save", "--kind", "mise", **tools) + assert "java 21.0.13" in lines + assert runner.s3.keys("/latest")[0].startswith("s3://bucket/prefix/example/mise-tools/") + fresh = runner.new_runner("second") + assert "restored " in fresh.outcome("restore", "--kind", "mise", **tools) + restored = fresh.home / ".local/share/mise" + assert (restored / "installs/java/21/bin/java").read_text() == "jdk" + assert not (restored / "downloads").exists() + assert "no archive for " in fresh.outcome("restore", "--kind", "mise", S3_CACHE_TOOLS="2026.11.10 sub python uv") + + +def test_a_mise_data_directory_outside_home_only_warns(runner: Runner) -> None: + assert runner.outcome( + "restore", "--kind", "mise", MISE_DATA_DIR="/elsewhere/mise", S3_CACHE_TOOLS="2026.11.10 java" + ).startswith("::warning::mise tools cache: couldn't restore, so mise downloads its tools: ") + + +def test_uv_saves_its_cache_but_not_its_builds(runner: Runner) -> None: + runner.tracked["sub/uv.lock"] = "c3" + write(runner.home / ".cache/uv/wheels-v5/pypi/requests.whl", "wheel") + write(runner.home / ".cache/uv/builds-v0/tmp/env", "build") + runner.run("save", "--kind", "uv", S3_CACHE_SCOPE="sub") + assert runner.s3.keys("/latest") == ["s3://bucket/prefix/example/uv/sub/latest"] + fresh = runner.new_runner("second") + assert "restored " in fresh.outcome("restore", "--kind", "uv", S3_CACHE_SCOPE="sub") + assert (fresh.home / ".cache/uv/wheels-v5/pypi/requests.whl").read_text() == "wheel" + assert not (fresh.home / ".cache/uv/builds-v0").exists() + assert "no archive for " in fresh.outcome("restore", "--kind", "uv") diff --git a/build-dependency-cache/uv.lock b/build-dependency-cache/uv.lock new file mode 100644 index 0000000..081659b --- /dev/null +++ b/build-dependency-cache/uv.lock @@ -0,0 +1,149 @@ +version = 1 +revision = 5 +requires-python = ">=3.11" + +[[package]] +name = "build-dependency-cache" +version = "0.1.0" +source = { virtual = "." } + +[package.dev-dependencies] +dev = [ + { name = "pytest" }, + { name = "pytest-randomly" }, + { name = "ruff" }, + { name = "ty" }, +] + +[package.metadata] + +[package.metadata.requires-dev] +dev = [ + { name = "pytest", specifier = ">=9.1.1,<10.0.0" }, + { name = "pytest-randomly", specifier = ">=4.1.0,<5.0.0" }, + { name = "ruff", specifier = "==0.17.4" }, + { name = "ty", specifier = "==0.0.107" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, +] + +[[package]] +name = "packaging" +version = "26.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/75/ffb1dc0ed12352139fb4ca0e3fde4325a23e3d0f3f40efe89717bc4f557b/packaging-26.4.tar.gz", hash = "sha256:c4b671c41ddb9bf26e543c37723610d28fb6bf7affc4da17cf048d419d2c062a", size = 355877, upload-time = "2026-11-23T21:44:11.152Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ba/7b/5504f91c9c2733f693d7759e50ede5d27119d4da7e5836c46d3b5ff81d56/packaging-26.4-py3-none-any.whl", hash = "sha256:81383611a09c1bc0b08b76e0fd5829d7c6824c65b27a6aee339da133f4233ea2", size = 140049, upload-time = "2026-11-23T21:44:09.531Z" }, +] + +[[package]] +name = "pluggy" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, +] + +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "pytest" +version = "9.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" }, +] + +[[package]] +name = "pytest-randomly" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/27/b3/36192dacc0f470ac2cc516f73e01739c9a48a8224f76beada4f85e1c8a89/pytest_randomly-4.1.0.tar.gz", hash = "sha256:47f1d9746c3bc3efabd53ae1ebfb8bb385cf3d4df4b505b6d58d9c97a3dfe70f", size = 14302, upload-time = "2026-04-20T13:01:51.831Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9a/db/2df9a1fca597a273f957a559c20c2d95d629928384507b2afa43ba6909d1/pytest_randomly-4.1.0-py3-none-any.whl", hash = "sha256:f55e89e53367b090c0c053697d7f9d77595543d0e0516c93978b50c0f6b252f9", size = 8353, upload-time = "2026-04-20T13:01:50.382Z" }, +] + +[[package]] +name = "ruff" +version = "0.17.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/84/0e/3d154514b5bad104f7e1c13169c2d09aa9959fccdc06eb47610ccdfa83ed/ruff-0.17.4.tar.gz", hash = "sha256:f32d178b50e826e00f6c6c1be3f56333068acb9b67fe167143527fa9b81e890d", size = 5357750, upload-time = "2026-11-05T18:52:17.638Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/61/c83c78bbb6108f6c6270a106cf12b54175f4f42da088b9bb880f18e31289/ruff-0.17.4-py3-none-linux_armv6l.whl", hash = "sha256:2b08c4ff98dc234f4a3871a3105353b922fa875ea1073ca31001eb8c06bb4d89", size = 10252195, upload-time = "2026-11-05T18:51:36.594Z" }, + { url = "https://files.pythonhosted.org/packages/0a/12/dd158708378866e8b53e145a465dbc51a7cccb9fa197a74d67eaedde7234/ruff-0.17.4-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:13e781c3c5f663e7fba737eaaeb70dd943dd55171daf316afb25cd5268cfe0c7", size = 10266044, upload-time = "2026-11-05T18:51:39.502Z" }, + { url = "https://files.pythonhosted.org/packages/28/32/89a94a8eb11fd505a381ae6f04e190d038d9958695209dc1786ce5cfcda3/ruff-0.17.4-py3-none-macosx_11_0_arm64.whl", hash = "sha256:7ed2f416349944f908f9574215994602242b0836844eba48eec61473033afca0", size = 9432227, upload-time = "2026-11-05T18:51:41.968Z" }, + { url = "https://files.pythonhosted.org/packages/58/de/a392dc38b215798ae72e639d228b7f6c02d826a95d1c0ad7c4c0ee49ef5b/ruff-0.17.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8ea6e0017c785f7282092b11e46338e4ebed1b9e575ebf2e55a8a1eda968241a", size = 10136900, upload-time = "2026-11-05T18:51:44.562Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8f/a880f60f42005f6ffdf58f77af34c7ee327000b5607f48a2f6a69d8b242c/ruff-0.17.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7e061dcc0933c7031a616ac8d66ac540309b2aa21ab558101a8f53e9ac7a1185", size = 10051245, upload-time = "2026-11-05T18:51:46.7Z" }, + { url = "https://files.pythonhosted.org/packages/09/55/98844264108af7d5ec27ca3a9cd5a989094ca657a14599c4b69a537a0e9a/ruff-0.17.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f99e95a1515161138be3cbd1b06c06e739d8feb38ade35564556999fffc3686e", size = 10704341, upload-time = "2026-11-05T18:51:49.228Z" }, + { url = "https://files.pythonhosted.org/packages/28/a2/5edf97659c3ac7c73f978003bd314936f671037fdac6b978e9de3e4b2b65/ruff-0.17.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5f28cf0dd37cb172fa5a8d2e92e6ada3a9dbd0609f094ed24039929eef0b7524", size = 11394465, upload-time = "2026-11-05T18:51:51.534Z" }, + { url = "https://files.pythonhosted.org/packages/f2/8f/51371ae856b2bef4d15a044a574695fbc0f6ae63aafa42a2a22428070fb6/ruff-0.17.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b21c771b296888e8a35c6f48555f4b44e4483f61675d6ed51810a5203469ce6", size = 10988262, upload-time = "2026-11-05T18:51:53.91Z" }, + { url = "https://files.pythonhosted.org/packages/af/1b/62874f14c7873f27c7887d2b1ea41de990e14ba9518801ffe8eacb5d51a6/ruff-0.17.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2cd025509b2e15721b426fc70fd946d71f43b3db3b08e946dfec2d696d911690", size = 10572829, upload-time = "2026-11-05T18:51:56.129Z" }, + { url = "https://files.pythonhosted.org/packages/98/30/860b9dae67432b16b88558a9cb2d3194825fa62838f8b9cc49f5d9022095/ruff-0.17.4-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:49b77f7b3921669466882a4881168801bdb06ec2cd83fb936049016cf5fdece1", size = 10617545, upload-time = "2026-11-05T18:51:58.172Z" }, + { url = "https://files.pythonhosted.org/packages/0f/08/781a4b41a1c83fd6e30fea610d6502a6f94e49cf94693fd37bdcbc6bfe11/ruff-0.17.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:e3b84eb74f260d1c2dbd236fd9d4c011d4fdd0a52bdf8aea57a10e3a1b71fca5", size = 10111955, upload-time = "2026-11-05T18:52:00.59Z" }, + { url = "https://files.pythonhosted.org/packages/3c/e9/94b1c7b677120f30839254518924f73a8157e9bcfa200edcd5796fecdb99/ruff-0.17.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:20e43d7a08e712e33067ba887e6574546c79bd4831596ce8f16803ac7ff9ad90", size = 10058355, upload-time = "2026-11-05T18:52:03.61Z" }, + { url = "https://files.pythonhosted.org/packages/27/5f/a825910b9f309336dc33cb8c0774126662c1d2f765699b3e0a1bd538d01f/ruff-0.17.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:0d1f4848fd2ec0499be4046db9b7dfcc952666885f00233cc7033515282556a8", size = 10415932, upload-time = "2026-11-05T18:52:06.264Z" }, + { url = "https://files.pythonhosted.org/packages/8b/b8/0796468423413ea4df1a6e2442ae26cf49b8f7dda0eecf246e0d5d0dde54/ruff-0.17.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:6007e7f3a0e55b0fbdb947af69cf24c21b4928df6be8ef3e767c69b5ccccf496", size = 10826033, upload-time = "2026-11-05T18:52:08.675Z" }, + { url = "https://files.pythonhosted.org/packages/b9/ab/d8e407669ffe5014429baf780c2df47e001968a6e4c17f615e2e7b13a9ba/ruff-0.17.4-py3-none-win32.whl", hash = "sha256:3971a78cba76298b284c8321e6d40d93045ed348bec5c369d85099efc97fb7cf", size = 9931993, upload-time = "2026-11-05T18:52:11.169Z" }, + { url = "https://files.pythonhosted.org/packages/bd/15/42af8a72d8946e3c9efd2bbf6641e462b6832783b0d043d63ef5b280ba7f/ruff-0.17.4-py3-none-win_amd64.whl", hash = "sha256:67c5a894fc054cf41f75f7afa24815de5a74329d97634126c2a1015740ff4e8c", size = 10292922, upload-time = "2026-11-05T18:52:13.436Z" }, + { url = "https://files.pythonhosted.org/packages/68/9e/f1dbffcfb8ff25dadbc21f87a8b73c3848abe4abada9d4b08ccef8bec40c/ruff-0.17.4-py3-none-win_arm64.whl", hash = "sha256:181ae38a9a8fb94925bf7d0794327b48d7fd7f4b50cfd84c0e999cc09ef8d131", size = 9889396, upload-time = "2026-11-05T18:52:15.549Z" }, +] + +[[package]] +name = "ty" +version = "0.0.107" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e1/21/096166a4d1118a6ce923223d53d14dc6262046604b6f1e667882db8d80b3/ty-0.0.107.tar.gz", hash = "sha256:e792277547cd55f5e75208665da705825f0af627397aa7abb169d5ad994277ca", size = 8342007, upload-time = "2026-11-18T21:08:00.423Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ea/b3/ed4d2f9899657b3fef03df61f5937570ff68c5fe43b1110b70350487e986/ty-0.0.107-py3-none-linux_armv6l.whl", hash = "sha256:dcf2567fe5ed95f21bf3e3fcc5de68a4b570a8b0e6029b3a57b8098e784b90d1", size = 15002472, upload-time = "2026-11-18T21:07:11.018Z" }, + { url = "https://files.pythonhosted.org/packages/cb/ae/164d1aeaf968a4d4104bf48c978a8bef8de1e258574b33fdb2d9fa9f5c21/ty-0.0.107-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:39dfc6a2ce0b1df3e53a518e92cd331f30c11355e44f55df9096581437be1e24", size = 14576636, upload-time = "2026-11-18T21:07:14.615Z" }, + { url = "https://files.pythonhosted.org/packages/a7/a4/c7b60685da0db9d7699459afe75fd17b1143e6fc14f6484fc55c2e705c1a/ty-0.0.107-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6f4169889ecb5ee42e15227c6b6f978c6638548c9929cb19f76022afef903361", size = 13973376, upload-time = "2026-11-18T21:07:17.377Z" }, + { url = "https://files.pythonhosted.org/packages/00/12/bf50a964941e6e03e3d526576a3f3c942029e06666f8db4a4541940ff743/ty-0.0.107-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9733e57559906229a897ed2834b7175013455c6b800aa3c029b15876fa11a75e", size = 14914214, upload-time = "2026-11-18T21:07:20.148Z" }, + { url = "https://files.pythonhosted.org/packages/a8/7f/1b283835c397fcb58d86a6355f8b138978e9c1121fe7514e4247dc9f7038/ty-0.0.107-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8ffa6cad4f057f45a7f68605622b16ed18fcb5a817ea1a1130ad689d0ec69c82", size = 14727467, upload-time = "2026-11-18T21:07:23.377Z" }, + { url = "https://files.pythonhosted.org/packages/7b/91/6a59b43159a9810f42d185e4d04fb52e5c8f48e786a75facd56f5990fa3a/ty-0.0.107-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6693dfa209355f0257a904f65eb6a37e50633af5bad9d304291956d84084c15e", size = 15718081, upload-time = "2026-11-18T21:07:26.053Z" }, + { url = "https://files.pythonhosted.org/packages/e0/62/c2d5a02dcaa19e674c79e527f1706f6691278c7ca85504a83240a602734a/ty-0.0.107-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f915ce2277bcb914c36134d8142ff7c209e0fe43647055a28df5001bdf1b173b", size = 16153080, upload-time = "2026-11-18T21:07:28.941Z" }, + { url = "https://files.pythonhosted.org/packages/88/f2/94af1c34c93ae9226e4c58f3c0a6ccb848f962f2838bf36d300f5a70f4a1/ty-0.0.107-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4d9f968afebb4e25239383029600073bbcdd2e82a1a7d3ff438d1ae8efd662c1", size = 16018858, upload-time = "2026-11-18T21:07:31.757Z" }, + { url = "https://files.pythonhosted.org/packages/21/17/16cb65301cd21f50634480b4fff3d4c25e61c4cd73f7e9c850681dddc08f/ty-0.0.107-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1fe5917b9ed2b4e500610cafb90f4a84ba936cf83eb3e2b8a9e44449b59b77cb", size = 17434891, upload-time = "2026-11-18T21:07:34.618Z" }, + { url = "https://files.pythonhosted.org/packages/14/54/dba49f1255a2fe2b49fed88e56ae385a977f3ab5b9c0579e92fb1380b235/ty-0.0.107-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:714447884645175ce96f566063fd31539960832423f748af5a4c3b5c817f0604", size = 15540910, upload-time = "2026-11-18T21:07:37.448Z" }, + { url = "https://files.pythonhosted.org/packages/c2/90/f87b2c5fa3323fd1d4ab30a7a78f4b363ca8337087dea9532be53fd02c5d/ty-0.0.107-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:bc37c53103d447c8a4d2eba6f746f9ded12c8aea66bd8c03d7039a976069aad4", size = 14401178, upload-time = "2026-11-18T21:07:40.233Z" }, + { url = "https://files.pythonhosted.org/packages/7a/33/b6cad6f43aeaca2988839827f40d6f0a62b062f352be472a2131f35ff0fc/ty-0.0.107-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:fe0aedb5047ac9e5fc2812e4ba36778efd2e5187c9056acf65bd67e85fa83418", size = 14742847, upload-time = "2026-11-18T21:07:43.269Z" }, + { url = "https://files.pythonhosted.org/packages/e0/4e/f467a0b8e151bf2162d9180e824c2dee30092c1284ed123fd787c1572fc9/ty-0.0.107-py3-none-musllinux_1_2_i686.whl", hash = "sha256:2eafaffdeb80484831e2c16e3cec3e1e45176c88cb08a82395138cc6a7695aa9", size = 15103370, upload-time = "2026-11-18T21:07:45.918Z" }, + { url = "https://files.pythonhosted.org/packages/59/76/e0df8db6f22ba0380b0775d7668e3e93cb12b7ab33326a1199f8e88d1d0b/ty-0.0.107-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:2e8fc59467d57762b4b171b597092ba7ebb91071b6dffda8ca3be393cebd437a", size = 15438466, upload-time = "2026-11-18T21:07:48.842Z" }, + { url = "https://files.pythonhosted.org/packages/cd/fe/fc14a66f6a7464a6b7ebd2440f7becd2146aa865f7516b22d44df29c1f3a/ty-0.0.107-py3-none-win32.whl", hash = "sha256:40b4c00666db9bcfe112b320522192ae598c0982f3c7270ce62eb313ffabb373", size = 13966366, upload-time = "2026-11-18T21:07:51.826Z" }, + { url = "https://files.pythonhosted.org/packages/a0/ad/1c992fb038f33a34f32f1ebc57ac4023ab60b4530e2bbf3fdd5e6d97753e/ty-0.0.107-py3-none-win_amd64.whl", hash = "sha256:e9b5e292a0b39105e1068ff176f355eb645b45d9f6aa91765ca739069ed13c12", size = 14895905, upload-time = "2026-11-18T21:07:54.814Z" }, + { url = "https://files.pythonhosted.org/packages/4e/93/83c2fa56dd6ab9f9d1253621ae79a5bbc2f3fc2bb3e562f2e8cd1ad5df5c/ty-0.0.107-py3-none-win_arm64.whl", hash = "sha256:c5f4eb4ea3c84ab755dafb7d09abee8d6fbd582db5371d858443f0c85e72dcd3", size = 14031494, upload-time = "2026-11-18T21:07:57.714Z" }, +] diff --git a/mise.lock b/mise.lock new file mode 100644 index 0000000..e749ca7 --- /dev/null +++ b/mise.lock @@ -0,0 +1,83 @@ +# @generated - this file is auto-generated by `mise lock` https://mise.jdx.dev/dev-tools/mise-lock.html + +lockfile_version = 4 + +[[tools.node]] +version = "24.19.0" +backend = "core:node" +specifiers = ["24.19.0"] + +[tools.node."platforms.linux-arm64"] +checksum = "sha256:d28c8a5bf0a808f0ed434a1dce8c54ae98f0371c0bd86ac58abc613f73e6643f" +url = "https://nodejs.org/dist/v24.19.0/node-v24.19.0-linux-arm64.tar.gz" + +[tools.node."platforms.linux-arm64-musl"] +checksum = "sha256:20824e4d35948fae5b337dccef47813b04d8995312f59df7386f2256d9f9ab7e" +url = "https://unofficial-builds.nodejs.org/download/release/v24.19.0/node-v24.19.0-linux-arm64-musl.tar.gz" + +[tools.node."platforms.linux-x64"] +checksum = "sha256:f625d97cd707df4ff96254916fbc5ff014f09c09effe5a1e0ca8f6d41a8789d4" +url = "https://nodejs.org/dist/v24.19.0/node-v24.19.0-linux-x64.tar.gz" + +[tools.node."platforms.linux-x64-musl"] +checksum = "sha256:c60223786df14a5d23e220ebb8e60318f5322640a62f90e6d9e54d3a18da532e" +url = "https://unofficial-builds.nodejs.org/download/release/v24.19.0/node-v24.19.0-linux-x64-musl.tar.gz" + +[tools.node."platforms.macos-arm64"] +checksum = "sha256:8294b7aa9b03997481c06babf1e8b270c859358f27da57a11509afe537ac381d" +url = "https://nodejs.org/dist/v24.19.0/node-v24.19.0-darwin-arm64.tar.gz" + +[tools.node."platforms.macos-x64"] +checksum = "sha256:d1b5e999db158c62fe8f7267a4476b035d8bd93b1a605bac24a3f0dd166e3316" +url = "https://nodejs.org/dist/v24.19.0/node-v24.19.0-darwin-x64.tar.gz" + +[tools.node."platforms.windows-x64"] +checksum = "sha256:57f71ab3652e797d84acddc79c81cc9ff1c6ddb2a1974cdb83f00fee9bff4c73" +url = "https://nodejs.org/dist/v24.19.0/node-v24.19.0-win-x64.zip" + +[[tools.uv]] +version = "0.13.7" +backend = "aqua:astral-sh/uv" +specifiers = ["0.13.7"] + +[tools.uv."platforms.linux-arm64"] +checksum = "sha256:71279f8d3c67241e807b9d8db872d1bf541579fb9f08b7d1eb1682196d1e57dc" +url = "https://github.com/astral-sh/uv/releases/download/0.13.7/uv-aarch64-unknown-linux-gnu.tar.gz" +url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/704009469" +provenance = "github-attestations" + +[tools.uv."platforms.linux-arm64-musl"] +checksum = "sha256:2d3ec076a0c4c0e8250bb6418c44080828b544f1a3be0b6e46adf9fb6923de45" +url = "https://github.com/astral-sh/uv/releases/download/0.13.7/uv-aarch64-unknown-linux-musl.tar.gz" +url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/704009487" +provenance = "github-attestations" + +[tools.uv."platforms.linux-x64"] +checksum = "sha256:c5221ff41b7892bfc223543883600125f6a47fe845093e0f5bdff4f359196d83" +url = "https://github.com/astral-sh/uv/releases/download/0.13.7/uv-x86_64-unknown-linux-gnu.tar.gz" +url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/704009823" +provenance = "github-attestations" + +[tools.uv."platforms.linux-x64-musl"] +checksum = "sha256:287491da03f2a785c70fa75b13e1f849918c2f2b5415fe84876b8214eeb792f9" +url = "https://github.com/astral-sh/uv/releases/download/0.13.7/uv-x86_64-unknown-linux-musl.tar.gz" +url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/704009859" +provenance = "github-attestations" + +[tools.uv."platforms.macos-arm64"] +checksum = "sha256:81b811b57e4624df7ed3aac148e0359100d9962f3d9dce00aec533dc2e086731" +url = "https://github.com/astral-sh/uv/releases/download/0.13.7/uv-aarch64-apple-darwin.tar.gz" +url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/704009442" +provenance = "github-attestations" + +[tools.uv."platforms.macos-x64"] +checksum = "sha256:20c47e4c1f630b8abaff8c291fa9b9aa300fef92c4fbff95adf198b55287cda7" +url = "https://github.com/astral-sh/uv/releases/download/0.13.7/uv-x86_64-apple-darwin.tar.gz" +url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/704009775" +provenance = "github-attestations" + +[tools.uv."platforms.windows-x64"] +checksum = "sha256:0cdc5b38fe5a8168ed6a25814f5ba43c21d313dd3187314fccb37b7cec46e021" +url = "https://github.com/astral-sh/uv/releases/download/0.13.7/uv-x86_64-pc-windows-msvc.zip" +url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/704009796" +provenance = "github-attestations" diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..582e27c --- /dev/null +++ b/mise.toml @@ -0,0 +1,8 @@ +[tools] +# What build-dependency-cache's tests need beyond the Python its own mise.toml pins: uv to run them, node for its +# JavaScript tests. The same versions as narrative-marketplace-backend's root mise.toml. +node = "24.19.0" +uv = "0.13.7" + +[settings] +lockfile = true diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..67f2617 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,27 @@ +# A copy of narrative-marketplace-backend's ruff.toml, the lint rules its Python style guide relies on, so that +# build-dependency-cache, which moved here from there, keeps the same rules. Change them there first, then here. +[lint] +extend-select = [ + "ANN", # annotate every parameter and return type, and don't use Any + "B", # likely bugs, such as a mutable default argument or a raise that drops its cause + "C4", # build collections with comprehensions + "DTZ", # no naive datetime + "ERA", # no commented-out code + "FBT", # a boolean parameter is keyword-only + "I", # sorted imports + "PERF", # no loop that appends to an empty list, and other slow idioms + "PGH", # no blanket type: ignore or noqa + "PIE", # no unnecessary pass, placeholder or duplicate + "PT", # pytest style + "RUF012", # no mutable default on a class attribute + "RUF013", # no implicit Optional + "RUF100", # no unused noqa + "TID251", # the banned APIs below + "UP", # the syntax of the Python the project runs +] + +# Tests pass a fake in rather than patching a dependency. Banning the fixture's type bans the fixture: ANN makes every +# test that takes `monkeypatch` annotate it. +[lint.flake8-tidy-imports.banned-api] +"unittest.mock".msg = "Pass a fake in instead of mocking." +"pytest.MonkeyPatch".msg = "Pass the dependency in instead of patching it."